Hello,
I’m trying the make the player (an object in 3D space) face the mouse cursor, responding only in the XZ-Plane.
However, the object consistently rotates at a very high speed and doesn’t follow the cursor.
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Camera cam;
void Update()
{
// Transforms the object's (player) position to a 2D-screen position
Vector2 playerPos = cam.WorldToViewportPoint(transform.position);
// Gets the position of the mouse
Vector2 mousePos = Input.mousePosition;
// Creates a vector going from the position of the player to the position of the mouse (in 2D space), and normalizes it
Vector2 vector = (mousePos - playerPos).normalized;
// Gets the direction which the player is facing, converts it to 2D
Vector2 playerFacing = cam.WorldToViewportPoint(transform.forward);
playerPos.Normalize();
// Using scalar multiplication in order to find the angle between 'playerFacing' and 'vector'
float angle = Mathf.Acos((vector.x * playerFacing.x * + vector.y * playerFacing.y))*180/Mathf.PI;
// Rotation the player 'angle' degress
transform.Rotate(0, angle, 0);
}
Why wouldn’t it work?
I’ve also tried another method, creating a vector going through the camera and the mouse position (converted to a world point), then finding the point of intersection between the straight line going through these points and the XZ-Plane and then telling the object to rotate to that point. Thought it would work since the point of intersection is ‘hidden’ by the cursor, thus making it seem like the object is facing the cursor itself.
The result is better than the code written above, yet not good enough.
Thank you!