I’m trying to make a top-down in 3d and want my character to rotate towards the mouse position but it only works right when the game starts (the character rotates to wherever my mouse is at the beginning) and then no matter where I move it the character just stays still…
private void Update()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePos - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(-angle, Vector3.up);
}
Any type of support is greatly appreciated, Thanks!
Hi, i was looking for exactly same thing and came with this…
moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput * moveSpeed;
Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayLength;
if (groundPlane.Raycast(cameraRay, out rayLength))
{
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
Debug.DrawLine(cameraRay.origin, pointToLook, Color.cyan);
transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
}
The reason you aren’t seeing updates is that you need to tell ScreenToWorldPoint
how far away from the camera you want your point to be. If you feed the mouse position in directly, your z value will be zero, indicating that you want a point distance 0 away from you camera. Since your camera is a point, no matter where you put your mouse on the screen it will always return the position of the camera. If you add a z amount to your mouse position
Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3(0,0,depth);
Then you will start to see your object rotate. Your code above won’t quite work though, you need to add an extra check for whether the mouse is above or below your object