Rayasting in Unity 3D
3D Game Design with Unity
π This lesson will take about 19 minutes
Raycasting involves sending out an invisible βrayβ and finding out what it hits. Raycasting is used by game developers to find the distance between players and another object, aiming at and detecting nearby objects, and finding line of sight.
Is YouTube blocked at school? Watch on Google Drive.
The code below is one example of using the Raycast method.
There are a few parameters that this method takes. The first is the Vector3 origin or position of where the ray starts and can hold three floats (the x, y and z coordinates). The second, Vector3 direction, is the direction that the ray will travel. The third, float distance, is the distance that the ray will travel before it stops. The last parameter is mask, which specifies what layers will be hit by the ray. The distance and mask parameters are optional. If they are left out, the ray will travel forever and hit all objects.
The code below could be added to the Update() method of a script attached to a camera in your game and used to detect whether an object is in front of the camera.
There is also another way that the Raycast method can be used. It can be used to find out which object the ray collided with. It can use a type of variable called a RaycastHit. Here is an example of what it can look like:
Where you see βoutβ, it means that whatever object was hit by the raycast will be stored in the βhitβ variable when the method finishes running.
Try it out
So letβs give Raycasting a go!
Step 1 β Create a new scene in your project and add a few 3D shapes around the main camera in your scene. The shapes should be close enough to the camera so you can see them clearly when you run the game.
Step 2 β Add at least three or four shapes that are spaced out nicely.
Step 3 β Create a new script called RaycastingScript and attach it to your main camera. Use the following code:
Step 5 β Now run the scene. You will notice that the mouse will now move the camera around. When you center the camera on each object in your scene, those objects will be destroyed and a message will be displayed in the console (if you already have a character controller that moves the camera around with mouse or keyboard movement, then you can xDirection and yDirection variables and the transform.Rotate(β¦) line of code that rotates the camera.
Next lesson: Graphical User Interface (GUI) design in Unity