If you want to have the tank look at your mouse, with a top-down perspective, I assume you want to the tank to rotate only on the y-axis towards the mouse, and that the camera is looking directly down onto the world with a 90-degree angle.
Given that the camera is directly looking down onto the tank, and is always centred on the tank, you can simply take the mouse position: Mouse.current.position.ReadValues()
/ Input.mousePosition
(depending on if you are using the new input system or not) and subtract the centre screen position: new Vector2(Screen.width/2, Screen.height/2)
With this direction vector, you can either create a new rotation with Quaternion.LookRotation()
, or use transform.LookAt()
public class LookAtMouse : MonoBehaviour
{
private readonly Vector2 screenCenter = new Vector2(Screen.width/2.0f, Screen.height/2.0f);
private void Update()
{
Vector2 mousePosition = Mouse.current.position.ReadValue(); // Input.mousePosition in the old input system
Vector2 directionToMouse = (mousePosition - screenCenter).normalized;
transform.rotation = Quaternion.LookRotation(new Vector3(directionToMouse.x, 0, directionToMouse.y), Vector3.up);
// - or -
transform.LookAt(transform.position + new Vector3(directionToMouse.x, 0, directionToMouse.y));
}
}
If you want to have a camera that may be at an angle, the solution becomes a bit more involved because you want to calculate the position of the mouse in your world, or rather, you want to calculate the world position of the point your mouse points at.
This can be done with a raycast, which would also support 3d models that are sticking out from a flat surface, but a faster approach that only considers the flat “floor” can be achieved by calculating a vector from your camera into the world to where you mouse is pointing at and then calculating the intersection with the “floor plane”, to get the world position of the point your mouse is pointing at. With this you can either do transform.LookAt()
or, similar to the code above, subtract the tanks world position to get the direction vector from your tank to the world position of the point your mouse is pointing at and do Quaternion.LookRotation()
.
If you are interested in that because the camera might not always be centred on the tank or might not always look down at the tank at a 90-degree angle, I’ll happy to provide you with some code about the more complex solution I just described.