Seeing with the Dot Product in Unity

Ben Mercier
2 min readMar 16, 2021

In Unity, we primarily know Vector2s and Vector3s as a way to represent and modify 2D and 3D positions, directions, and Euler angle rotations in our scenes, respectively. However, these vector representations also include functions which allow us to execute common vector operations, including the dot product.

Like our own vision which may be limited by where we’re facing, what we’re facing, how we’re facing, or (semi-spoiler alert!) whose Hex we’re in, the vision and line of sight of game objects may also need to be limited once defined. Per the Wiki, the dot product is the product of the Euclidean magnitudes of two vectors and the cosine of the angle between them (got it?). For our purposes, the .Dot() function will essentially provide a way for our game object (an enemy mech) to know what, if any, objects (our turrets) are in front of it by returning a float value between 1 and -1. If the float value is greater than 0, then the turret is in front, but if it’s less than 0, then then enemy has passed it.

I’m a classically trained Excel painter!

To use Vector3.Dot() with our enemy, we need both a reference to its forward direction as well as the direction of any turret we want to check. For the enemy’s forward, simply access the transform.forward of the enemy object, and for the direction to the turret, take the turret’s current Vector3 and subtract the current Vector3 of the enemy (heading = destination-origin).

Note that transform.forward is a normalized vector representing the blue axis in the scene view, and when a vector is normalized it maintains its same direction while having its length set to either 1 or 0. For example, a normalized Vector3(7, 0, 0) would return Vector(1, 0, 0).

Green > 0, Red < 0, Yellow = 0

Next, input your heading and forward direction into your Vector3.Dot(), and the float value that’s returned will allow you to incorporate further logic telling your game object how it should respond or what state it should switch to. With our enemy, it’ll tell us when it’s time to fire!

I’ll try spinning, that’s a good trick!

Oops, not like that. Unfortunately, this is Unity and you’re a programmer so of course you mistakenly set the wrong localRotation!

Dissolve shader not included.

Better! Now, when the turret collides with the enemy’s attack radius, the enemy rotates towards the turret so long as the turret is in front of it (Vector3.Dot() > 0), or the turrets finally do their job.

--

--

Ben Mercier

I’m an emergent software developer with a longtime love of games and a growing understanding of how to actually build them.