How to Get Mouse Position in Unity
In the realm of game development with Unity, determining the mouse position is a common requirement for various tasks such as UI interaction, enemy targeting, or camera control. Unity provides several ways to achieve this, which we'll explore in this guide.
Before we delve into the methods, let's understand the mouse position coordinate system. In Unity, the mouse position is represented as a 2D Vector2 or a 3D Vector3, with the origin (0,0) in the top-left corner of the screen. The x-axis increases to the right, and the y-axis increases downwards.
Getting the Mouse Position on Screen
The Screen class in Unity offers several static methods to get the mouse position relative to the screen. Let's look at the two most useful methods:
Screen Space
The Input.mousePosition method returns the mouse position in screen space as a Vector3. The values range from 0 to the screen's width and height. Here's a simple example:
Vector3 mousePos = Input.mousePosition;
Please note that this method returns the position in pixels, not normalized coordinates. To get the position as a normalized value between 0 and 1, use:
Vector3 mousePosNormalized = Input.mousePosition / new Vector2(Screen.width, Screen.height);
World Space
To get the mouse position in world space, you can use Physics.Raycast or Camera.ScreenToWorldPoint. The latter is more straightforward and converts the screen point to world space:
Vector3 mousePosWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Getting the Mouse Position in the Game World
Sometimes, you might need the mouse position relative to the game world, especially for 3D games. This is where Physics.Raycast comes in handy. Here's a step-by-step guide:
Raycasting from the Camera
First, cast a ray from the camera through the mouse position to find the hit point:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
bool hit = Physics.Raycast(ray, out RaycastHit hitInfo);
The hitInfo.point will give you the 3D position where the ray hit something in the game world.
Raycasting from the Mouse Vertical Plane
Another approach is to raycast from the mouse position along the player's forward vector to find the first hit:
Plane playerPlane = new Plane(Camera.main.transform.forward, Camera.main.transform.position);
Ray ray = Camera.main.GetComponent().ScreenPointToRay(Input.mousePosition);
float enter = 0.0f;
if (playerPlane.Raycast(ray, out enter))
{
Vector3 hitPoint = ray.GetPoint(enter);
// Do something with hitPoint
}
In conclusion, Unity provides several ways to get the mouse position, making it a powerful tool for developers. Understanding how to use these methods is crucial for creating engaging and interactive game experiences. So, start exploring these techniques in your Unity projects today!