Week 4 Tutorial Exercise - Raycasting and Unity AI


This week's tutorial was all about getting familiar with Unity's Navigation Mesh system for artificial intelligence, as well as some additional topics like raycasting and creating game-friendly level designs. As I discovered, the environment I created for last week's self-study (the Tasmanian tourist location) was not ideal for this week's teachings, so I opted to use the environment provided in the tutorial files instead.

One of the most important things for this tutorial was getting our projects to look more like actual games. This meant in this case we needed to have a third-person camera attached to our player controller, and a moving obstacle in the environment to add complexity to movement and pathing. For the camera, I used a Cinemachine Virtual Camera with some settings adjusted to follow the player around at all times. For the moving obstacle, I created a wall in the centre of the environment hooked up to a simple script that uses the Mathf.PingPong function to move it back and forth a set distance. Here's an animation showing both of these things in action: 

The next part of the tutorial was more involved, and required using Unity's Nav Mesh system alongside AI "agents" to create an enemy that follows the player around. As for how the enemies are spawned into the game world, I created a script that uses Raycasting from the user's mouse position on the screen to the targeted position in the environment, in order to instantiate an enemy at that position. This animation shows how it works:


The last thing to get working was the enemy pathing (which you can sort of see in action in the image above). These enemies all use a NavMeshAgent component, along with a script that continuously sets their destination to predict the player's movement, using a combination of their position and speed. This meant that they would move around the environment, even jumping over small gaps, in order to chase down the player. (I don't think they were too happy about not being able to get me at the end...)


For this week's self study I'll be taking what I learned in this tutorial and applying it to a somewhat more in-depth game, with actual mechanics, so stay tuned for that!

Leave a comment

Log in with itch.io to leave a comment.