Unity realizes mouse point 2D to 3D for rotation

Time:2020-11-24

In this paper, we share the specific code of unity to turn 2D mouse to 3D for your reference. The specific content is as follows

The code is as follows:

using UnityEngine;

public class GunFollowMouse : MonoBehaviour {
  public RectTransform UGUICanvas;
  public Camera mainCamera;
  //Slow motion rate of camera rotation
  private float rotateSpeed = 5;
  void Start () {
 
 }
 
 void Update () {
    //The mouse point that defines a world coordinate
    Vector3 mousePos;
    //Get the two-dimensional coordinates of the mouse under the current canvas and convert them into three-dimensional out
    RectTransformUtility.ScreenPointToWorldPointInRectangle(UGUICanvas,
      new Vector2(Input.mousePosition.x, Input.mousePosition.y),
      mainCamera, out mousePos
      );
    //Turret rotation angle
    float angle;
    //The vector dirmouse is the mouse vector minus the gun start vector to get the direction vector from the gun to the mouse position
    Vector3 dirMouse = mousePos - transform.position;
    Angle = vector3. Angle (dirmouse, vector3. Up); // get the angle between two vectors directly. This angle has no positive or negative
    if (mousePos.x > transform.position.x)
    {
      angle = - angle;
    }
    transform.localRotation = Quaternion.Lerp(transform.localRotation, Quaternion.Euler(0, 0, angle)
      , Time.deltaTime * rotateSpeed);
 }
}

The rotation effect is as follows:

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.