我的弹丸更新功能有什么问题?

What's wrong with my projectile update function?

本文关键字:什么 问题 新功能 更新 我的      更新时间:2023-10-16

以下是所有相关的代码。

当射弹初始化时,它就会运行:

slope = (yTarget - yPos) / (xTarget - xPos);
if (xTarget >= xPos)
    xDir = 1;
else
    xDir = -1;
if (yTarget >= yPos)
    yDir = 1;
else
    yDir = -1;

每次更新都会运行,每次游戏循环都会发生:

xPos += t*speed*xDir;
yPos += t*speed*yDir * abs(slope);

XTarget和yTarget是投射物应该去的地方,xPos和yPos是投射物当前所在的地方。速度目前为1,所以忽略它,t是自上次更新以来经过的节拍数(ms)。(在我的电脑上通常是0-2)一切都很好,只是子弹的速度似乎取决于(xTarget-xPos)离0的距离,炮弹越近就越快。我会试着直观地解释一下。如果我向角色的右侧或左侧射击,子弹会以所需的速度移动。然而,如果我在角色上方或下方拍摄,它的拍摄速度会非常快。有人能告诉我一个解决这个问题的方法,或者一个更好的编码方法吗?谢谢

dx = xTarget - xPos;
dy = yTarget - yPos;
norm = sqrt(dx*dx + dy*dy);
if (norm != 0) {
    dx /= norm;
    dy /= norm;
}

稍后:

xPos += t*speed*dx;
yPos += t*speed*dy;