Rotate the object to follow the direction of the mouse in the 2D screen (vector method)

void Update () {
            //Get the coordinates of the mouse, the mouse is the screen coordinates, the Z axis is 0, no conversion is done here  
            Vector3 mouse = Input.mousePosition;
            //Get the coordinates of the object, the coordinates of the object are the world coordinates, and convert it to the screen Coordinates, always with the mouse  
            Vector3 obj = Camera.main.WorldToScreenPoint(transform.position);
            //Subtract the screen coordinate vector to get the target vector pointing to the mouse point, that is, the yellow line segment  
            Vector3 direction = mouse - obj;
            //The Z axis Set to 0, keep it in the 2D plane  
            direction.z = 0f;
            //Change the length of the target vector to 1, that is, the unit vector, the purpose here is to only use the direction of the vector, not the length, so it becomes 1  
            direction = direction. normalized;
            //The Y axis of the object itself and the target vector remain the same, and the XY axis will change the value during this process  
            transform.up = direction;
        }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325867314&siteId=291194637