4

I'm writing a simple tower defence and I'm stuck on a bit where my tower has to shoot enemy.

With this code:

void Bullet::move(int x, int y, int speed) 
{

    Punkt delta = {(x + speed) - this->x, (y + speed) - this->y};
    if (abs(delta.x) > 1 && abs(delta.y) > 1)
    {
        this->x += delta.x / this->speed;
        this->y += delta.y / this->speed;
    }
    else
    {
        this->dead = true;
    }
}

Where method arguments are target position and speed. It's supposed to move bullet along vector till it reaches the target but the vector changes because the target is moving. For now the bullet ends up like this (black is the tower, blue is the bullet and red is enemy)

error

And I know the problem is that my bullet is targeting something that already moved so my question is - how to improve this code so it works properly? I don't know how to wrap my head around vectors and balistics so thanks in advance for keeping it simple.

4

3 回答 3

3

我以前见过的这个问题的合理解决方案如下:

  1. 尽力预测子弹和敌人的良好碰撞点在哪里。一种天真的方法是简单地预测当前的敌人位置。
  2. 在预测的位置发射子弹
  3. 当子弹到达预测位置时,让子弹消失,播放伤害动画,并降低敌人的生命值——不管子弹是否真的击中

这样,如果你的数学足够聪明,它看起来会很好。但除此之外,游戏仍然可以正常运行。

如果敌人在你向他们开火后可以改变速度(例如,他们被特殊地形或区域效应炮塔减速),这种方法也会更加稳健。

于 2013-01-12T15:39:54.850 回答
2

如果你正在射击一个移动的目标,你需要在子弹到达它的时间内瞄准它的位置,那么你有两个已知的位置,所以你知道矢量。

于 2013-01-12T15:40:09.010 回答
0

好吧,我在gamedev论坛上看了一些,我得到了解决方案(我什至设法理解)。这一切都是为了正确计算(正如每个人所说,转换为浮动是必要的)。下面是懒人的代码:

float dx = x - this->x;
float dy = y - this->y;
float dx2, dy2;
float distance;
float vx, vy;

distance = sqrt(dx * dx + dy * dy);
dx2 = dx / distance;
dy2 = dy / distance;

vx = dx2 * this->speed;
vy = dy2 * this->speed;

if (distance > 10) // 10 is hitbox size
{
    this->x += vx; // still float, its converted to int when applying to surface
    this->y += vy;
}
else
{
    this->dead = true;
}
于 2013-01-12T19:08:16.817 回答