简体   繁体   English

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

[英]What's wrong with my projectile update function?

Here is all the relevant code. 这是所有相关代码。

This gets run when the projectile is initialized: 当弹丸初始化时,它将运行:

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

And this gets run every update which happens every gameloop: 这将在每个游戏循环中发生的每个更新中运行:

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

XTarget and yTarget are where the projectile should go and xPos and yPos are where the projectile currently is. XTarget和yTarget是射弹的目标位置,xPos和yPos是射弹的当前位置。 Speed is 1 for now so just ignore it and t is the number of ticks (ms) that have gone by since the last update. 速度目前为1,所以请忽略它,t是自上次更新以来经过的滴答声(ms)数。 (usually 0-2 on my computer) It all works fine except that the bullet speed seems to be dependent on (xTarget - xPos)' distance to 0, the projectile speeding up the closer it is. (通常在我的计算机上为0-2),除了子弹速度似乎取决于(xTarget-xPos)到0的距离(射弹的速度越接近),一切工作都很好。 I'll try to explain it visually. 我将尝试以视觉方式进行解释。 If I shoot to the right or left of my character the bullet moves at the desired speed. 如果我向角色的右侧或左侧射击,则子弹会以所需的速度移动。 However, if I shoot above or below the character, it shoots extremely quickly. 但是,如果我在角色上方或下方射击,则射击速度非常快。 Can someone tell me a way to fix this or a better way to code this whole thing? 有人可以告诉我一种解决方法,还是一种更好的方法来编写整件事? Thanks. 谢谢。

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

Later: 后来:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM