Today, we talk about two very interesting features, vector subtraction and Quaternion.LookRotation on a missile example.
First, we need to find a direction from point A to point B, and we do this by subtracting two Vectors:
Direction = Target position — Missile position
Then, we translate the direction into rotation. In Unity we use Quaternions to handle rotations.
There is a good method that Unity offers named Quaternion.LookRotation(). It takes direction and calculates rotation around Y axis (which is sky by default).
private void AimMissile()
{
foreach (var missile in missiles)
{
// Distance/Direction between missile and target
var shootingDistance = target.position - missile.transform.position;
// Quaternion.LookRotation takes shootingDistance Vector3
// to rotate missile in target's direction
var missileRotationToTarget = Quaternion.LookRotation(shootingDistance);
// And finally update missile transform
missile.transform.rotation = missileRotationToTarget;
}
}
So, every frame, this method executes a loop throughout missiles array. Every missile individually calculates its own and target coordinates. LookRotation understands the angle at which to rotate each missile. As a result, even if the target shifts to the side, all missiles synchronously adjust their course in flight.
Top comments (0)