我正在写一个简单的塔防御,我被困在我的塔必须射杀敌人的地方。
使用以下代码:
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;
}
}其中方法参数是目标位置和速度。它应该沿着矢量移动子弹,直到它到达目标,但是矢量改变了,因为目标在移动。现在子弹是这样结束的(黑色是塔,蓝色是子弹,红色是敌人)

我知道问题是我的目标是已经移动的东西,所以我的问题是-如何改进这段代码,使其正常工作?我不知道如何理解向量和弹道,所以提前感谢你让它变得简单。
发布于 2013-01-12 23:39:55
我之前见过的这个问题的合理解决方案如下所示:
这样,如果你在数学上足够聪明,它看起来会很好。但除此之外,游戏仍将正常运行。
如果敌人在你向他们开火后有可能改变速度(例如,他们被特殊的地形或效果区域炮塔减速),这种方法也更强大。
发布于 2013-01-12 23:40:09
如果你正在射击一个移动的目标,你需要在子弹到达它的时间内瞄准它所在的位置,那么你有两个已知的位置,所以你知道向量。
发布于 2013-01-13 03:08:17
好吧,我在gamedev论坛上看了一下,我得到了解决方案(我甚至设法理解了)。这一切都是关于正确的计算(正如每个人都说的那样,转换为float是必要的)。下面是lazy的代码:
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;
}https://stackoverflow.com/questions/14294815
复制相似问题