这段代码做了什么(SFML C ++游戏)? [英] What does this piece of code does(SFML C++ game)?
问题描述
大家好,
我正在尝试用SFML做一个简单的乒乓球游戏。
我被困在一块我从互联网上拿出的代码,我无法理解详细的工作,所以请大家解释一下。
下面的代码是移动一个球随机方向,当它击中边界或划桨时使其反弹
Hello guys,
I am trying to make a simple ping pong game using SFML.
I am stuck with a piece of code which I took out from internet, I am not able to understand the working in detail so guys please explain.
Below piece of code is to move a ball in a random direction and make it bounce when it hits the boundary or a paddle
<pre lang="c++">
void update(sf::Clock &clock, sf::Time &elapsed) {
const float velocity = std::sqrt(direction.x * direction.x + direction.y * direction.y);
elapsed += clock.restart();
while (elapsed >= update_ms) {
const auto pos = ball.getPosition();
const auto delta = update_ms.asSeconds() * velocity;
sf::Vector2f new_pos(pos.x + direction.x * delta, pos.y + direction.y * delta);
if (new_pos.x - ball_radius < 0) { // left window edge
direction.x *= -1;
new_pos.x = 0 + ball_radius;
}
else if (new_pos.x + ball_radius >= 800) { // right window edge
direction.x *= -1;
new_pos.x = 800 - ball_radius;
}
else if (new_pos.y - ball_radius < 0) { // top of window
direction.y *= -1;
new_pos.y = 0 + ball_radius;
}
else if (new_pos.y + ball_radius >= 500) { // bottom of window
direction.y *= -1;
new_pos.y = 500 - ball_radius;
}
ball.setPosition(new_pos);
elapsed -= update_ms;
}
}
我编辑了我的愿望。我已经将一个时钟和vector2f方向引用到一个私有变量,这将使球以随机方向射击。
我尝试过:
理解了一下代码,但不详细,所以需要你的帮助。
I have edited to code to my wish a bit. I have given a reference to a clock and vector2f direction to a private variable which will make the ball shoot in a random direction.
What I have tried:
Understood the code a bit, but not in detail so need your help guys.
推荐答案
此类代码使用以下公式更新球的位置:
Such code updates the ball position, using the following formula:
new_position = current_position + current_speed * delta_time
然后检查新位置是否会越过边界,在这种情况下它会使球反弹,恢复速度并更新其位置。
Then it checks if the new position would cross a boundary, in such a case it makes the ball bounce, reverting the speed and updating its position.
这篇关于这段代码做了什么(SFML C ++游戏)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!