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.
本文介绍了一款使用cocos2d库开发的iPhone游戏中热寻导弹的实现方法。通过简单的三角函数调整导弹的角度来使其更加逼真地追踪目标。文章详细解释了如何计算导弹朝向角度并平滑调整其飞行方向。

4万+

被折叠的 条评论
为什么被折叠?



