无法使球从屏幕边缘反弹

Having trouble making a ball bounce off the edge of the screen

我正在尝试制作乒乓球游戏。我有代码可以检测球何时到达屏幕边缘并改变方向,但是一旦它不符合 if 语句,它就会继续沿之前的行进方向前进。这会使球卡在边缘并继续沿 x 轴移动。我想不出一种使方向永久改变的方法。我该怎么做?

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

只需为速度使用一个变量:

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

此外,请考虑 的内容。要确定球是否反弹,您还需要检查速度,而不仅仅是位置。如果您在上一次迭代中已经反弹,但在下一次迭代中球仍然靠近墙壁怎么办?仅在靠近墙壁且当前方向远离屏幕时弹起。

仅仅知道球的位置是不够的。你不知道球是(应该)朝向墙壁还是远离它。所以你需要存储位置和速度向量。