In this lesson, you will learn how to bridge the gap between a 2D screen click and a 3D object by using Physics Raycasting to detect user interactions.
From Pixels to 3D Space
When a player clicks their mouse, the computer only knows the X and Y coordinates on the screen. However, your game lives in a 3D world. To tell which 3D object the player meant to click, we use a Raycast.
Think of a raycast like a laser pointer. When you click, Unity shoots an invisible "laser" from your Camera into the scene, starting from the mouse position and traveling deep into the 3D space. If that laser hits a Collider on any object, Unity tells you exactly what it touched.
Implementing the Raycast
To perform this, we combine the Camera.main.ScreenPointToRay method with a RaycastHit structure. The RaycastHit acts as a container that stores data about the object we collided with.
void Update() {
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
// Check if the ray hits an object with a Collider
if (Physics.Raycast(ray, out hit)) {
Debug.Log("You clicked on: " + hit.transform.name);
}
}
}
Why Filter with Raycasting?
Sometimes you have many objects in a scene, but you only want to interact with specific ones (like treasure chests). By checking the hit object, you can "filter" your interactions. You might check if the object has a specific Tag or component:
if (Physics.Raycast(ray, out hit)) {
if (hit.transform.CompareTag("Interactable")) {
// Only trigger interaction logic for tagged objects
hit.transform.GetComponent<Chest>().Open();
}
}
By using raycasting, you ignore clicks on the background or floor and focus only on the objects that matter to your gameplay mechanics. This effectively translates a generic "screen click" into a purposeful "world interaction."
Key Takeaway: Raycasting turns a 2D screen coordinate into a 3D line, allowing you to identify and filter which objects the player is interacting with in the game world.