In this article we continue to learn how works Raycast and when (and for what) we can use it.
In the previous part we had seen which syntax is and how works the Raycast, how we store the information into RaycastHit hit and every time we hit something we retrieve the informations.
Nothing so hard right?
Today, instead, we try to Instantiate something on a simple Plan thanks to Raycast.
Let’s set up a simple scene with a Plane
We create a Sphere and make it a prefab.
I create a material and apply to the sphere, feel free to don’t do it, for the test it’s not necessarily to do it.
And we create a Player script and attached to the Camera.
Open the script, and in pseudo code we write what we need to do :
I continue to use the new Input System, because it’s an exercise even for me ^^
Ok, let’s try to figure out how we can do it.
A part of this code is nearly equal to the previous.
As we can see in the image above, we check if we press the left button,
then we take create a variable that store the mousePosition,
and we create a var(Ray) ray which store the origin point of the Ray.
And of course, we need a RaycastHit variable to store the information of the object we collide with.
Now we have to create another If Statement for the Raycast
Inside Physics.Raycast() , we need another check :
if we hit something called a “Plane”, then we can Instantiate the Sphere.
Note : we need a reference to the Sphere and drag and drop it in the editor.
This is our script until now.
Try to test it
It works, BUT we need to change something, because in this moment we can Instantiate a billion of Sphere every time we click, but the position is not which we want.
And this happen becuase when we use Instantiate, we pass only the Sphere, so the position is that we have inside the prefab.
probably you know already, but if we a have a prefab and we try to Instantiate it, if in this method we don’t set a position, the position of Instantiation is the same that we store inside the prefab.
To make this clear, if we have this position in the prefab
If we press Play
Ok, back to our first problem.
The position where we want the Sphere is the same that Raycast hit right?
In this case, we need to access to “hit” and use POINT.
Point return the position of collision of RaycastHit, and in this case is exactly what we need.
If we test it now
A part the fact the sphere is half under the Plane, it works as we want!
An easy way to fix the problem is create a variable that store a Vector3 spherePos and on y axis we add 0.5f.
I see you in the next articles!