JakeP
JakeP

Reputation: 327

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. 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. (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. 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.

Upvotes: 0

Views: 77

Answers (1)

JS1
JS1

Reputation: 4767

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;

Upvotes: 1

Related Questions