Box2D loosing object speed C++

Hello,

I am trying for a long time to finish a clone of the game brick breaker.
I am having trouble with the speed of my ball, I searched all over the internet and could not get the desirable solution.
All I want is to make the ball move in constant velocity for all over the time without any changes.

When the ball is colliding with the paddle:

Vec2 vel = ballBody->getVelocity();
vel.x = (ball_center - paddle_center) * 7.5;
vel.y = -vel.y;
ballBody->setVelocity(vel);

When the ball is colliding with brick:

Vec2 vel = ballBody->getVelocity();
vel.x = vel.x;
vel.y = -vel.y;
ballBody->setVelocity(vel);

I tried almot everything.

Thanks for help!

In order to maintain a constant speed the length of your velocity vector just stay constant.

In your paddle collision you’re scaling speed by the distance the ball is from the paddle centre. This is not constant. If you are wanting this effect then you need to lose some vertical speed.

This code will ensure the speed stays constant

Vec2 vel = ballBody->getVelocity();
float speed = vel.getLength();
vel.x = (ball_center - paddle_center) * 7.5;
vel.y = -vel.y;
ballBody->setVelocity(vel.getNormalized() * speed);

However a classic breakout game will simply reverse vertical speed on collision, like you’re doing with the brick:

Vec2 vel = ballBody->getVelocity();
vel.x = vel.x;
vel.y = -vel.y;
ballBody->setVelocity(vel);

If you inspect the length of ‘vel’ after Y as been reversed it’ll be the same, therefore the speed will remain constant.

1 Like

It’s true that my scaling of the speed is not constant, What I meant by constant is for the ball to move in the range of the distance between him and the paddle. The problem was that the ball is somehow loosing speed after a few moments in the game.

Anyways, It seems that your solution is working fine, although I am not so sure only the time will tell.

Thanks very much for help!