We’re working on an iPhone game using the excellent cocos2d library. The game has a heat-seeking missile that attempts to collide with a game object. The initial implementation was one that just tracks the object and adjusts its velocity vector to intercept it. Unfortunately, this approach allowed the missile to “turn on a dime” which looked completely unrealistic. We’ve tried several attempts to correct it but they all had various issues.
The best workable solution we could identify involved some simple trigonometry. The missile has an angle (in radians) and a speed. Each game tick, the missile position (stored as floats) is updated with the following code:
missilePosX += cosf(missileAngle) * missileSpeed * timeSinceLastTick;
missilePosY += sinf(missileAngle) * missileSpeed * timeSinceLastTick;
To determine the missile’s angle at any given game tick, you need the target position and the missile position:
float angleToTarget = atan2f(targetPosition.y - missilePosition.y, targetPosition.x - missilePosition.x);
if (missileAngle > angleToTarget) {
missileAngle -= 0.05;
} else {
missileAngle += 0.05;
}
Finally, the rotation of the sprite (in degrees) is adjusted so that it matches the missile’s heading:
sprite.rotation = (-missileAngle*(180/3.142));
The end result is a missile that tracks the object but moves in a much more realistic manner than one that always adjusts directly to an intercept vector. While this quick implementation required additional changes to improve its realism, this proved to be a reasonable the starting point.