Click to Move System Using Raycasting in Unity
Objective: To move a game object to a location using Raycasting in Unity.
For the final article for the raycasting series, I am going to create a click to move system using Raycasting!
Getting the Scene Setup
I have used a 3D cube to create a simple floor and added in another cube for our Player. Added a material to make our floor stand out. And thats it!
I am going to use 2 scripts for this, one is going to be for the mouse click called ‘Pointer’ and the other is going to be for the player movement called ‘MovePlayer’. Let’s start with Pointer:
First, we are going to need a reference to our ‘MovePlayer’ class so that we can call the UpdateDestination() method — Which is going to continually set a new Vector3 location everytime we click the mouse on the floor.
Then, within the Start() method we are going to find the only instance our the ‘MovePlayer’ script using FindObjectOfType<>, whilst null checking to make sure we find the class.
Then within the Update() method we are going to check for when the left button on the mouse was clicked.
Now, let’s build our Raycast system — Starting with a Ray that is going to be cast from the main camera to the mouse clicked position, utilising the poll feature (ReadValue()) in Unity’s New Input System.
We are also going to need some information about the impact point between the ray and the floor — So let’s setup a RayCastHit variable to store this information — ‘_hitInfo’.
Lastly, let’s shoot our raycast out and check to see if the ray hits a collider with the name “Floor”.
If it does, then we have successfully created a new destination point which we are going to pass in as a Vector3 parameter to the UpdateDestination() method on the ‘MovePlayer’ script.
To get started I will need a _speed variable and a _targetDestination for the player to move to.
Within Update(), I have a simple LookAt() method which just instantly snaps its focus to the new _targetDestination when this is updated. Then, I am going to move the players position using Vector3.MoveTowards() method from it’s current position to the _targetDestination multiplied by _speed and realtime.
Lastly, make sure the UpdateDestination() method is public so that we can call it from the ‘Pointer’ class. I need a Vector3 parameter to be passed in. I have also set the Y — axis value to 1 so that this doesn’t change and the player simply moves along the X and Z axis.
ScreenPointToRay — Unity Documentation
Physics Raycast — Unity Documentation
RayCastHit — Unity Documentation
RayCastHit.point — Unity Documentation
Ray — Unity Documentation
Transform.LookAt — Unity Documentation
Vector3.MoveTowards — Unity Documentation
FindObjectOfType — Unity Documentation
Casting Raycasts from Mouse Position in Unity
Placing Objects via Raycast Hits in Unity
Raycasting With LayerMasks in Unity
Creating Bullet Holes via Raycasting in Unity