C++ 无法使球从屏幕边缘反弹

C++ 无法使球从屏幕边缘反弹,c++,pong,C++,Pong,我想做一个乒乓球游戏。我有一个代码,可以检测球何时到达屏幕边缘并改变方向,但是一旦它不符合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 +=

我想做一个乒乓球游戏。我有一个代码,可以检测球何时到达屏幕边缘并改变方向,但是一旦它不符合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);
//抓住球的位置
浮动x_pos=ball->xPos();
浮动y_pos=ball->yPos();
//在x和y方向上移动平衡块
x_pos+=250*(game_time.delta.count()/1000.f);
y_pos+=400*(game_time.delta.count()/1000.f);

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

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

除此之外,还要考虑什么状态。要确定球是否反弹,您还需要检查速度,而不仅仅是位置。如果在上一次迭代中已经反弹,但在下一次迭代中球仍然靠近墙,该怎么办。只有当它靠近墙壁且当前方向远离屏幕时才会反弹。

只需使用一个速度变量:

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

除此之外,还要考虑什么状态。要确定球是否反弹,您还需要检查速度,而不仅仅是位置。如果在上一次迭代中已经反弹,但在下一次迭代中球仍然靠近墙,该怎么办。只有当球靠近墙壁且当前方向远离屏幕时,它才会反弹。

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

仅仅知道球的位置是不够的。你不知道球是(应该)朝向墙还是远离墙。因此,您需要存储位置和速度向量。

您的球还需要
x\u速度
y\u速度
。当球撞到墙上时,这些都需要反转。你的球还需要
x\u速度
y\u速度
。当它撞到墙上时,需要将其倒置。