I'm trying to make projectiles that travel outwards from the player in the direction of the mouse until they hit something, but I can't figure out how to do it.
I've tried using some vector physics but it's not working the way I want it to.
You are changing position at fire. Is this called once or at each logic update?
What about adding a velocity (and maybe an acceleration) variable?
Set velocity and start position at time of shoot.
Then update position each logic frame.
Not sure what dx and dy were so left out. You can put back if needed.
The dx and dy were the difference between the coordinates of the player & bullet - i copied most of the code over from an earlier part so it might have been wrong.
Anyway, I adapted the code - the bullet moves now, but for some reason it only goes in one direction regardless of where the mouse is pointed.
[EDIT] changing the filled circle into a bitmap fixed it for some reason
Think about the bullet as a separate object. When the player fires a bullet, a new bullet is created, and is set to be moving in a direction (you should call this velocity).
Later, you update the position of all the bullets that have been created (you'll need to have them in a list).
Notice that the position of the bullet and the position of the player have nothing to do with each other. Except when the bullet is created, more on that below.
With that in place, the question then becomes "how do I set the correct direction/velocity for the bullet when it's created". For that, you'll need to know the "world position" of the mouse relative to the player position. Subtracting the mouse world position from the player position souls give you the direction vector. With that, you normalize it and then multiply by whatever speed you want yhe bullet to travel.
Okay, now creating the bullet is done, I was wondering if I could put these bullets into a vector, then use a for loop to draw and update all the bullets?
Using a vector would be fine.
It all seems to work now, but i'm not sure how to remove the bullet after it leaves the screen
Ideally it would work like this
if (bullet_vector[i].x > WIDTH || bullet_vector[i].x < 0 || bullet_vector[i].y > HEIGHT || bullet_vector[i].y < 0) { //bullet is destroyed here }
The most robust technique is a two step process. Add a boolean flag on the bullet (can_be_destroyed). In your conditional you have set the flag to true.
Later, during "cleanup", simply remove the flagged elements from the vector
for (int i=0; i<bullet_vector.size(); i++) { if (bullet_vector[i].can_be_destroyed) { bullet_vector.erase(bullet_vector.begin() + i); i--; } }
I tried this method but it returns an error that the "vector subscript is out of range"