I have seen some people looking for ways to create seeking missiles, or have enemies continually go towards the hero even if it is moving. I have seen people give solutions such as using boids (flocking algorithm), but I have a simple solution using vectors.
This code assumes you have a sprite called hero and a sprite called enemy. All of the code will go in the update function. So lets say the enemy knows the position of the hero at all times. We need to find a vector in the direction of the hero from the enemy so we subtract the hero’s position from the enemy position:
CGPoint vecEtoH = ccpSub(hero.position, enemy.position);
Now we need to turn this vector into a unit vector which is a vector in the same direction, but with a magnitude of 1. This way we can multiply it by a velocity number to have it move at a constant speed:
CGPoint uVecEtoH = ccpNormalize(vecEtoH);
int velocity = 2;
CGPoint finalVec = ccpMult(uVecEtoH, velocity);
Now we have our final vector for the enemy’s new position. We will add this to the current position of the enemy and it will follow the hero where ever it goes:
[enemy setPosition:ccpAdd(self.position, finalVec)];
Now we have some code that will cause the enemy sprite to get 2 pixels closer to the hero sprite with every loop through the update function.
The best use for code like this would be to have a separate Enemy class, and put this code in an update function in the Enemy class. This way any time you create a new instance of Enemy they will already be able to follow the hero.
本文介绍了一种使用矢量实现敌人自动追踪英雄角色的简易算法。该算法通过计算英雄与敌人之间的方向矢量,并将其标准化为单位矢量来确定敌人的移动方向。通过不断更新敌人的位置,可以使其始终朝向英雄移动。
3865

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



