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;
}