How to make enemies follow your hero (seeking missiles)

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.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值