c++ - 无法让球从屏幕边缘反弹
问题描述
我正在尝试制作乒乓球游戏。我有代码可以检测球何时到达屏幕边缘并改变方向,但是一旦它不符合 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);
解决方案
仅仅知道球的位置是不够的。你不知道球是(应该)朝向墙壁还是远离墙壁。所以你需要存储位置和速度矢量。
推荐阅读
- android - 我的查询中的条件没有正确过滤记录
- python - IndexError:python上的列表索引超出范围错误
- powershell - Powershell取消设置访问.mdb密码 - 密码已知
- javascript - 正则表达式匹配第一个字符一次,然后重复匹配直到结束
- swiper - 这个 SwiperJS 效果背后的逻辑?
- java - 当 jpanel 的背景被设置时,它的组件不会被显示出来
- android - 从系统发送不受保护的广播 action.ROAM_INFO_CHANGED
- firebase - React Native 通知图像未在 IOS 上显示
- phpstorm - 如何强制 PhpStorm 突出显示 *.php 文件中的 HTML 代码
- swift - 将 NSSet 转换为数组