r/learnprogramming • u/oneLampPost • Oct 26 '26
How to make an object move in one direction without stopping
I have this code here and it almost works perfectly. The issue is the object then bounces back and forth from where the mouse was and where the player is.
void Bullets::Update(sf::Vector2f mousePos, float dt)
{
sf::Vector2f center = bulletpos + sf::Vector2f(radius, radius);
sf::Vector2f toPointer = SetDir(sf::Vector2f(mousePos.x, mousePos.y) - center);
bulletpos += toPointer.normalized() * speed * dt;
}if more code is needed lmk.
6
Upvotes
5
u/rupertavery64 Oct 26 '26
Your toPointer is updating every time based on the mouse position, which is also always changing every frame. You need to set the vector once when the trigger is clicked, then let it update the playerpos with the same vector every frame until it hits something or goes out of bounds.
1
u/MarkoDahl54 Oct 26 '26
Store the direction as a sf::Vector2f when you first fire the bullet, not in Update. Only calculate SetDir once, then always move using that stored direction each frame so it doesn't keep recalculating toward the mouse.
1
u/Dazzling_Music_2411 Oct 26 '26
Get a heading and stick to it.
If you are updating every frame based on the mouse position, of course it will follow the mouse. What did you expect?
0
u/da_Aresinger Oct 26 '26
It is very difficult to figure out how this code is supposed to work in the first place.
I assume
Vector2fis a two dimensional vector of floats.What is
centersupposed to be and why is it offset from the player? Also an offest by (radius,radius) actually offsets by 1.41×radius.I think I can guess that
toPointeris supposed to be the vector representing the "line" between player and target. But what you've calculated kind of creates a triangle between player, target and center.That is not necessarily a bad thing, so long as
centeris the source of the bullet.Finally, why are you updating the playerposition instead of the bullet position?
Now, with all this uncertainty: The likely reason why the bullet changes direction, is because when the bullet goes "behind" the target location for a single frame, your calculation for
toPointerbecomes negative and therefore reverses direction. The same thing will happen once the bullet moves past the player position.You probably need more understanding of linear algebra, but you can scratch by for now if you just set the direction of the bullet once, instead of every time you update the position.