Implementing Physics.Raycast Based on Mouse Position in Unity 2021
--
In this article we’ll use Physics.Raycast to determine if a player has clicked on a 3D game object in the scene.
Prototype Project Setup
Create a new Unity project with the following elements:
· 3D cube game object
· Cube material
· PlayerInput script
I’ll be using the new Input System, so install the Input System package from the Package Manager.
Rather than go through the trouble of setting up an Action Map asset with Actions and bindings, we’ll use the techniques previously covered in:
Next, assign the Cube_mat material to the Cube game object.
Let’s also create an empty game object and name it “InputManager” to which we will assign the PlayerInput script.
Raycasting From the Camera
Per Unity:
“The most common use of a Ray from the camera is to perform a raycast out into the scene.
A raycast sends an imaginary “laser beam” along the ray from its origin until it hits a collider in the scene.
Information is then returned about the object and the point that was hit in a RaycastHit object.
This is a very useful way to locate an object based on its onscreen image.”
Using the code example provided by the Unity documentation, we’ll add raycast detection to our Update() method.
Since we are using the new Input System, we’ll need to replace the “Input.mousePosition” legacy input call.
Once you have created the _mainCamera variable, you will need to assign the Main Camera game object to the PlayerInput script component as shown above.
Last, we need to add our change color logic using the UnityEngine.Random.ColorHSV() method.
If we fire up the game, we can see that clicking on nothing does nothing while clicking on the cube changes the color of the cube.