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);
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.