Raycasting in Unity Part 1: Vectors

This is the first post in a three part series on Raycasting in Unity. The follow up posts are:

Find the code on GitHub

Introduction

Raycasting is the process of pointing (“casting”) a line (“ray”) in a direction and seeing what it hits.

The process is useful for, among other things, placing and selecting objects, giving AI agents a sort of vision, and building hoverbikes or a flock of sheep.

This guide will walk through some of the foundational concepts, and then build some basic examples in Unity.


Intro to Vectors

Most of the heavy maths is done for us by Unity, but there are some concepts which will be helpful for us to have a solid grasp on going forward. If you’re confident using vectors in Unity, skip to the next section.

There are a few way to think about vectors, depending on who you are. This guide will give the briefest overview of vectors from a graphics perspective. It is my intention to provide just enough of an intuition that we can start experimenting meningfully. If you’re interested in diving deeper into the world of vectors I can’t recommend threeblueonebrown more highly.

The Basics

A vector is a line with a direction.

This line could represent either a specific position, or a general direction.

Magnitude

“Magnitude” is the fancy term for the length of the line. In high school they’d tell you that to find the magnitude you need to take the square root of the sum of the squares of the length of each axis, but Unity does this for us. Conceptually, all you need to know is that the magnitude of the vector is the length of the line it represents.

Normalising

A normalised (normalized for Americans) vector is a vector whose magnitude is 1. To normalise a vector is to squish it down (or strech it out) so that it still points the same way, but its length is 1. This is useful for getting a ‘pure’ direction vector without any stretching.

Normals

Separate to normalising, a Normal is a vector that points perpendicular to a surface. In the case of 2D vectors (such as the image below), the Normal points perpenducular to a line.

Now that we have a sense of Vectors, let’s apply them! Head to Foundations of Raycasting to continue this guide

Leave a Reply

Your email address will not be published. Required fields are marked *