But that goes to the mouse position. I'd like make it so the length of the bullet path won't stop at the cursor but keep going until it exits the screen or hits something. How would I change that?
Much of the code in your Move() function doesn't belong there.
The calculation of the velocity components is something to be done once when the bullet is fired, not continually while the bullet is moving. I believe this was pointed out in an earlier thread of yours on this, but perhaps it wasn't clear.
While the bullet is in motion you just need to increment the position using the already calculated values for the velocity.
Here's an idea of what's involved. I'm assuming a fire() function, which would be called when the firing event occurs only (a press of the space bar or the click of a mouse button, whatever your event trigger is).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void Bullet::Fire(float targetX, float targetY)
{
// just use local variables to help with the calculations. These dont need to be data members
float distX = targetX - x0;// x0, y0 are coordinates the bullet is fired from
float distY = targetY - y0;// you may need to pass these to the function as well
float distance = sqrt(distX*distX + distY*distY);
// velocity.x and .y and speed should be data members of the bullet class
velocity.x = distX *speed/distance;// these will be used in the Move()
velocity.y = distY *speed/distance;
// position.x and .y may be useful as members too
position.x = x0;
position.y = y0;
sprite.SetPosition(x0, y0);
}
The Move() function would be called repeatedly while the bullet is in travel. You just need to update the bullet and sprite positions using the velocity.x and .y found in the Fire() function.
1 2 3 4 5 6 7 8
void Bullet::Move()// what is the sf::RenderWindow object needed for?
{
position.x += velocity.x;// update the bullet position
position.y += velocity.y;
sprite.SetPosition(position.x, position.y);
}
Do not recalculate the velocity every update. Calculate the velocity once, when the bullet is first fired. Then record that velocity (probably as a member of the Bullet class) and apply it every update.
EDIT: ninja'd by a much more detailed response. lol
But for some reason now I'm getting an error code every time the program ends - Unhandled exception at 0x770015de in Practice SFML.exe: 0xC0000005: Access violation reading location 0xfeeefef6. Any idea why?