Mouse Controls in Unity
In this tutorial, you will learn how to implement basic mouse controls in Unity. We will cover mouse input detection, handling mouse clicks, mouse movement, and interacting with game objects using the mouse.
Setting Up the Project
Before we start coding, let's set up a simple Unity project:
- Create a new Unity project.
- Add a new 3D or 2D object to the scene (e.g., a Cube or a Sprite).
- Create a new C# script named
MouseController
and attach it to the main Camera or any empty GameObject.
Detecting Mouse Input
Unity provides built-in methods to detect mouse input. We can use the Input.GetMouseButtonDown
method to detect mouse button presses.
using UnityEngine;
public class MouseController : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0)) // Left mouse button
{
Debug.Log("Left mouse button pressed");
}
if (Input.GetMouseButtonDown(1)) // Right mouse button
{
Debug.Log("Right mouse button pressed");
}
}
}
Handling Mouse Clicks
To handle mouse clicks on objects, we need to use Raycasting. Raycasting allows us to detect if a mouse click intersects with any game objects in the scene.
using UnityEngine;
public class MouseController : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.Log("Hit: " + hit.transform.name);
// Perform actions on the hit object here
}
}
}
}
Mouse Movement
Detecting mouse movement in Unity can be done using Input.GetAxis
. We can use the Mouse X
and Mouse Y
axes to get the mouse movement in the horizontal and vertical directions.
using UnityEngine;
public class MouseController : MonoBehaviour
{
void Update()
{
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
if (mouseX != 0 || mouseY != 0)
{
Debug.Log("Mouse moved. X: " + mouseX + " Y: " + mouseY);
}
}
}
Interacting with Game Objects
Let's extend our script to interact with game objects. We will change the color of an object when it is clicked.
using UnityEngine;
public class MouseController : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Renderer renderer = hit.transform.GetComponent();
if (renderer != null)
{
renderer.material.color = Random.ColorHSV();
}
}
}
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
if (mouseX != 0 || mouseY != 0)
{
Debug.Log("Mouse moved. X: " + mouseX + " Y: " + mouseY);
}
}
}
Conclusion
We've covered the basics of mouse controls in Unity. We learned how to detect mouse input, handle mouse clicks, track mouse movement, and interact with game objects using Raycasting. These concepts can be expanded to create more complex interactions in your Unity projects.