Unity : Raycast (Part I)
Today we talk about Raycast.
Starting with a simple question : what is a Raycast?
Here we have the reference
Raycasting is incredible useful, and understand when and how use it, can be open our possibility to implement it in many mechanics of our games.
Unlike the 95% of documentation, the Raycast documentation is not “so great” but anyway, let’s create a simple scene in Unity and make some test to clarify as many things possible.
In this scene I have a Cube at 0, 0, 0 and Player script attached to Main Camera.
The purpose of this test is this :
we click an object, in this case the cube, and we change its color to red (or whatever you want)
Break the problem in to small pieces with pseudocode :
Now, in the documentation what we really need to know is this.
After reading this part, we now know that we need an origin point, hence a starting point for the Raycast, a direction and a maximum distant.
Other really important thing, and we can see in this example, is the first variable
In this variable we store information of object we hit.
If this can be help you, is the same logic when we use
OnTriggerEnter or OnCollisionEnter
Inside “other” and “collision” we store the information of object we collide (or trigger).
Ok, let’s back to Unity.
I continue to use new Input System, so at the top :
And we test if we press the left mouse button.
Mouse Input works.
Now, how can we fire a Raycast from the Camera?
We need to search it, because we can’t know everything, so we research.
If we Google “How can Raycast from Camera in Unity”
This is the first result.
And this is a documentation, so we open it
Here’s a link
This is what we need to know.
And we use this example in our project to test it.
Now, we have an error, and this can be an interesting thing.
If we over the mouse on error
We can’t convert “Vector2Control” to “Vector3”
Now, if store it into a variable like this
We see that this is not a Vector2, but Vector2Control.
To convert this value into Vector3, we need to add this piece of information at the end of Mouse.current.position
We back to Raycast syntax, and we use the first info we find in the documentation
If we test it
When we left click on the Cube, in the Console we can read “Hit something”.
In the next article we finish this little test with Raycast!