0
\$\begingroup\$

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;
setX(ent->getX());
setY(ent->getY());
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;
}
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$
float deltaY = getX()-targX;
float deltaX = getY()-targY;

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .