Homing Calculations for Beams and Missiles

Hello. I'm Hirayama from the Technology Department.
On June 25, 2019, there was a joint lightning-talk event by four companies. The audience was people from the IT industry, and I had no idea what to talk about, so I ended up just presenting something I'd happened to make as a hobby. This article focuses only on the homing calculation in that demo.
Note: please don't use the particle calculation part of this demo as a reference. Use the standard ParticleSystem. That part is purely a hobby.
By the way, I'll be writing articles about the other parts of this demo as well, one at a time.
- Spherical distributions and rotating vectors
- Camera control
Demo overview
I've prepared a demo that runs in WebGL. The source code is on GitHub.
The gauge at the top right is the processing load. The number on the left is the average time over the last 60 frames, and the number on the right is the maximum time over the last 60 frames. If the average stays within 16, it's running nicely at 60 frames per second.
Press the Fire button and a beam flies toward the enemy. Press the Fire16 button and 16 beams are fired at once.
The Thread button turns on multithreaded parallelization, but WebGL can't use threads, so it does nothing there. The particle count is set to 100,000 on Standalone and 20,000 on everything else (if you fire a lot of beams, particles run out and things start looking a bit sparse). On a 2018 MacBook Pro, a PC build kept almost 60 fps even with 100,000 particles. But you can put out far more with the standard particles, so it doesn't really matter.
Why I made this demo
This goes back a long way, but in 2003 a game called ANUBIS came out, and its beams, snow, smoke and so on blew me away (search and you'll find plenty of videos). Its particle effects were so cool.
Around the same time, my own job also involved making beams and the like, and I experimented with particle effects for things like the sparks when a beam hits and snowflakes, but I never went as far as "exploring effects designed around particles" (I was in my first year out of university, after all).
Later I heard a GDC talk along the lines of "from now on you can put out a million particles with shaders" and started thinking "couldn't the whole thing, beam body included, be done with particles?", but I had too much else going on, and time passed without me doing anything about it.
Then, while I was trying to come up with "a five-minute talk that would give people who know nothing about games a feel for what making games is like", I suddenly remembered the beams.
The class that does the homing
The beam homing I'm explaining here is handled by the Beam class. Beam itself doesn't draw anything, so it's not a MonoBehaviour.
Internally, I implemented the beam not as a line but as a moving point. The idea is that it leaves particles along its path as it moves, so the result looks like a line. Only the head has a hit check. Depending on the game you might want hit checks along the middle or at the tail too, but once the beam curves you need a position history, which is a hassle, so I skipped it here.
Of the data it holds, the values that change every frame are:
- position (position)
- velocity (velocity)
- whether it's active (judged by time >= 0)
Update() integrates and updates them. The constant parameters are:
- the maximum acceleration for turning (maxCentripetalAccel)
- the propulsive acceleration (propulsion)
- air resistance (damping)
These are the parameters for homing and for keeping the speed constant.
Various ways to home in
There are several ways to chase an enemy. The three main ones are probably these.
- Move the vertical and horizontal angles independently
- Use Quaternion interpolation
- Bend the path by adding acceleration
Moving the vertical and horizontal angles independently
The most straightforward is to handle the vertical angle (elevation/depression; the x of the Euler angles) and the horizontal angle (azimuth; the y of the Euler angles) separately. It requires the least math.
Say that, from where the beam is now, the target appears 20 degrees up and 40 degrees to the left. You decide how much the angles can change per frame; let's say "2 degrees vertically, 3 degrees horizontally". In the next frame, you correct the vertical angle to 18 degrees and the horizontal angle to 37 degrees left. In the frame after that you measure the angles again and correct them again. You repeat this.
This method is easy to work with in "games with a clear sense of which way is ground and which way is sky", and has the advantage that the game balance is easy to tune. For example, by tuning it to "not track much vertically but chase well horizontally", you can give it a character like "easy to dodge by jumping, impossible to dodge by running".
However, in games "without an up or down", like space games or fighter-jet games, problems appear. It's fine as long as the beam is facing roughly sideways (a vertical angle near 0), but it breaks down near straight up or straight down.
Say the vertical angle is 89 degrees and the horizontal angle faces south (-90 degrees). To point it north (+90 degrees), the shortest way is to turn 2 degrees vertically, over the top. But if you compute vertical and horizontal independently, the vertical angle is 89 degrees both before and after, so it doesn't change, and the horizontal angle has to turn 180 degrees. At 3 degrees per frame, that takes 60 frames.

So unless the game design wants the vertical and horizontal angles to be separate, I can't recommend this method. Working with angles also means going through trigonometric functions every time, so it's expensive too.
Using a Quaternion
"The direction it's facing now" can be expressed with two angles, vertical and horizontal, but another way to express it is the Quaternion (if you follow the convention of writing a final "r" as a long vowel, I think the Japanese spelling should really be "kuotānion". A digression).
With this, in the earlier example you can "take the shortest route, over the top, to the other side". You only need a single angle that doesn't separate vertical and horizontal, like "can turn 2 degrees per frame", so there are fewer parameters, which makes things easier.
However, Unity's Quaternion is rather short on features, and there aren't many articles explaining how to use it. Quaternions are very handy, so I'll cover them on this blog at some point, but here I'll use a different method.
Adding acceleration to the velocity vector
This is the method I went with, and I'll explain it in detail.
The homing calculation in detail
The Beam class already has a velocity vector, velocity, so I add an acceleration vector to it to bend its direction.

If you're at A heading due north toward B, and the enemy is at C to the northeast, then adding east (vector BC) to the direction of travel (vector AB) points you northeast (AC), right? That's the idea.
The code is below.
var toTarget = target - position;
var vn = velocity.normalized;
var dot = Vector3.Dot(toTarget, vn);
var centripetalAccel = toTarget - (vn * dot);
var centripetalAccelMagnitude = centripetalAccel.magnitude;
if (centripetalAccelMagnitude > 1f)
{
centripetalAccel /= centripetalAccelMagnitude;
}
var force = centripetalAccel * maxCentripetalAccel;
force += vn * propulsion;
force -= velocity * damping;
velocity += force * deltaTime;
First, get the vector toward the enemy (toTarget). "The vector from A to B is B-A." If you're not used to vector
math, chant it out loud: "B-A goes from A to B! From A to B is B-A!" Once it's drilled in, you'll never get it
wrong.
Next, compute "the vector that bends the velocity toward the enemy". In a diagram, it looks like this.

In the diagram, P is the current position, T is the enemy's position and v is the velocity vector, and c is the vector we want. First, prepare the normalized velocity vector (vn in the code). Then project the vector toward the enemy onto vn.
Projecting literally means "casting a shadow", and here it means finding T' in the diagram. Look at the diagram below.

If you want the position of point D that you get by projecting vector AB onto vector AC, then
cosθ = Dot(AB, AC) / |AB||AC|
and
cosθ = |AD|/|AB|
so
|AD| = cosθ*|AB|
= (Dot(AB, AC) / |AB||AC|) * |AB|
= Dot(AB, AC) / |AC|
If you normalize AC (which corresponds to v earlier) beforehand, the division by |AC| goes away. In code:
AC.Normalize();
D = A - (AC * (Vector3.Dot(AB, AC));
D corresponds to centripetalAccel in the original code, so this is what we were after. All that's left is to tweak its length as needed and add it to the velocity, and the velocity bends.
The "tweak its length as needed" part is this.
var centripetalAccelMagnitude = centripetalAccel.magnitude;
if (centripetalAccelMagnitude > 1f)
{
centripetalAccel /= centripetalAccelMagnitude;
}
var force = centripetalAccel * maxCentripetalAccel;
The variable with the oddly long name, centripetalAccel, is the acceleration added to bend the path. centripetal means
"directed toward the center". When you swing a weight on a string round and round, the weight doesn't fly off
because the string pulls it toward the center, and this is called
centripetal force. Here I handle the acceleration
directly, so it's "acceleration" rather than "force", hence the Accel, but it's the same thing.
If the length (magnitude) of centripetalAccel is 1 or more, I normalize it to length 1. If it's less than 1, I leave it as is. Then I multiply by maxCentripetalAccel. This gives the behavior "if the length is maxCentripetalAccel or less, leave it; if more, make the length maxCentripetalAccel". In other words, maxCentripetalAccel is "the maximum size of the bending force".
Making the parameters easy to handle
Unlike the previous two methods, "how much to bend each frame" is defined not as an angle but as an acceleration, which isn't intuitive as it stands. So the class takes a different parameter from the outside.
public void Emit(
Vector3 position,
Vector3 velocity,
float speed,
float curvatureRadius,
float damping)
{
this.position = position;
this.velocity = velocity;
// When drawing a circle with speed v and radius r, the centripetal force is v^2/r. Compute it here.
this.maxCentripetalAccel = speed * speed / curvatureRadius;
maxCentripetalAccel is computed internally and isn't visible from outside. What it takes from outside is
curvatureRadius, the "radius of curvature", which basically says "it can turn along a circle with a radius of this
many meters". The smaller it is, the more sharply it turns and the better it chases. For example, if you want it to
hit even when it's pointing in completely the wrong direction with the target 100 m away, the radius of curvature
has to be 50 m or less. Otherwise, like the Moon going around the Earth, it will never hit. I think
this makes "how sharp the homing is" easier to grasp than "degrees per second". What do you think?
And the centripetal force is found as speed squared / radius of curvature.
Keeping the speed constant
In this demo, the beam travels at a constant speed. Let's see how to make that happen.
Note that I said "speed" there, as distinct from "velocity". "Speed" means "the length of the velocity vector". In the code it's speed, and the velocity vector is velocity. This distinction between "speed" and "velocity" is a fairly common one, I think.
What I want here is to keep the speed constant even when the beam curves. But adding to the velocity vector naturally changes the speed. So, to keep the speed constant, I slow the velocity every frame with damping, and also accelerate it every frame with propulsion, which is given as a parameter.
"Why not just normalize the velocity vector?" you might think. That would work too, in a way, but since I had the chance, I tried sticking to a basic rule of physics simulation: "control things by applying forces, and never touch position and velocity directly".
For example, if damping is 0.1, the velocity drops to 90% over one second. This makes the effect of the acceleration from bending fade away steadily. Then, to keep the speed constant, propulsion accelerates the beam in the direction of its velocity. Eventually resistance and propulsion balance out and the speed becomes constant. If you think of propulsion as a missile burning fuel to move forward and damping as air resistance, it's easy to interpret in real-world physical terms.
force += vn * propulsion; // propulsion
force -= velocity * damping; // air resistance
velocity += force * deltaTime; // integrate velocity
Since it stays within the framework of physics simulation, you can use it even when you're building on top of a physics simulation framework (like Rigidbody) and can't write the integration yourself.
Making the parameters easy to use
As with the radius of curvature earlier, passing in the propulsion directly is inconvenient, so the class takes something else instead.
public void Emit(
Vector3 position,
Vector3 velocity,
float speed,
float curvatureRadius,
float damping)
{
//...omitted...
this.propulsion = speed * damping;
It simply takes the speed (speed) and computes propulsion from that and damping.
The drag from damping is -velocity * damping, and we just need propulsion to cancel it out once the magnitude of
velocity reaches speed, so propulsion should be speed * damping.
In this case the value of damping barely matters, so you could just hard-code something like 0.1 inside instead of taking it as a parameter, but that's a minor detail.
Summary
The advantages of the homing calculation introduced here are:
- It can be written with ordinary vector math alone
- No quaternions or matrices needed
- No trigonometric functions appear
- It stays within the framework of physics simulation
In particular, being "written with ordinary vector math alone" also means that "the code is almost identical in 2D and 3D". In fact, just replacing Vector3 with Vector2 turns it directly into homing for a 2D game.
The disadvantages would be something like:
- Strictly speaking, it can't keep a constant speed
- Air resistance, a parameter you don't really need, gets involved
- It's hard to follow if you're not used to working with vectors
- If the radius of curvature is too small, it overshoots, never settles and the path wobbles
Note that if you want "homing that always hits at a fixed time", I think there's yet another method (from around page 24). The calculation here assumes that "it doesn't necessarily hit, and its homing ability is limited".