I am working on a top down 2d shooter. I am trying to make the bullets go at a constant speed (in pixels) in the direction of the mouse. I am having trouble doing this. My bullets fire directly 45 degrees off where the mouse is. I wrote this method which sets all the angles and rate of travel.
travelRate: Bullet speed in pixels per frame

targetX: target X coordinate in pixels

targetY: target Y coordinate in pixels

changeX: how far the bullet should go per frame along the X axis (in pixels)

changeY: how far the bullet should go per frame along the Y axis (in pixels)

ent: The player/npc shooting the Projectile

I do not understand why my bullets are going at a 45 degree offset from the mouse.NOTE: I cut out some of the unimportant code from this method.

void Projectile::init(Entity * ent, int targX, int targY)
travelRate = 4;
targetX = targX;
targetY = targY;
float deltaY = getX()-targX;
float deltaX = getY()-targY;
float dLen = sqrt(deltaX*deltaX + deltaY*deltaY);
if (dLen == 0)
    dLen == 1;
deltaX /= dLen;
deltaY /= dLen;
float deg = rad * 180 / PI;
changeX = deltaX * travelRate;
changeY = -deltaY*travelRate;
float deltaY = getX()-targX;
float deltaX = getY()-targY;

Could it be that you have mixed up deltaX and deltaY here?

  • \$\begingroup\$ Now it fires directly opposite. But, i modified the method to say changeX = -deltaXtravelRate; changeY = -deltaYtravelRate; Now it works. Thanks \$\endgroup\$ – lvl99knight Oct 5 '17 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.