首页 > 解决方案 > 无法让球从屏幕边缘反弹

问题描述

我正在尝试制作乒乓球游戏。我有代码可以检测球何时到达屏幕边缘并改变方向,但是一旦它不符合 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);

标签: c++pong

解决方案


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


推荐阅读