Reputation: 59
I'm trying to make a pong game. I have code which detects when the ball reaches the edge of the screen and will change direction, however as soon as it does not meet the if statement it continues in the previous direction it was travelling. This leaves the ball to get stuck on the edge and continue travelling on the x-axis. I cannot think of a way to make the direction change permanent. How would I go about doing this?
//grab the position of the ball
float x_pos = ball->xPos();
float y_pos = ball->yPos();
//move the bal in x and y direction
x_pos += 250 * (game_time.delta.count() / 1000.f);
y_pos += 400 * (game_time.delta.count() / 1000.f);
std::cout << "The Y co-ord is " << y_pos << std::endl;
float angle = y_pos / x_pos;
std::cout << "The angle it hits is " << angle << std::endl;
//change direction when ball hits edge
if (y_pos >= (game_height - 32) || y_pos <= 0)
{
y_pos += -400 * (game_time.delta.count() / 1000.f);
}
// update the position of the ball
ball->xPos(x_pos);
ball->yPos(y_pos);
Upvotes: 0
Views: 587
Reputation: 75854
Knowing just the position of the ball is not enough. You don't know if the ball is(should be) going towards the wall or away from it. So you need to store the position and the velocity vector.
Upvotes: 3
Reputation: 123149
Just use a variable for the velocity:
// before the loop
x_velocity = 250;
y_velocity = 400;
// then inside the loop
if ( bounce ) y_velocity = -y_velocity;
x_pos += x_velocity * (game_time.delta.count() / 1000.f);
y_pos += y_velocity * (game_time.delta.count() / 1000.f);
In addition, consider what this answer states. To determine if the ball bounces you need to also check the velocity not only the position. What if you already bounced in the last iteration, but the ball is still close to the wall on the next iteration. Only bounce it when it is close to the wall and its current direction is away from the screen.
Upvotes: 0