user2990037 user2990037 - 1 year ago 77
C++ Question

Calculating a future position of a ball that can bounce off the walls

I'm trying to do some future prediction where I want to calculate where the ball should be a particular height (y). The ball is fired upwards and can bounce off the sides of the game. Bounces do not affect movement velocity.

My current config is bottom left is (0,0) and bottom right is (10,0) with no upper height limit.


void getPositionXAtHeight(float height, Vec2 pos, Vec2 vel, float gravityForce = 9.8f, float gameWidth, float& positionX)
float a = gravityForce / 2.0f;
float b = vel.y;
float c = pos.y - height;

float t = (sqrtf((b * b) - (4.0f * a * c)) - b) / (2.0f * a);

positionX = pos.x + (vel.x*t);


Can anyone advise if my code is correct so far and what I should do to handle wall bounces?
Also I feel I should do some error checking but am unsure where abouts I need to?

Answer Source

It's not clear what's the direction of gravity, but suppose that it's along the y-axis. Then, for symmetry, you can just "wrap around" the x values, if they go above 10. E.g. if your equation results in x=11, for symmetry, after the bounce, x=9 (10 - (11 - 10)). Similarly, you can treat "double bounces", etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download