Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
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;
		}
	}


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.
Posted
Updated 27-Mar-17 1:35am

1 solution

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.
 
Share this answer
 
Comments
Member 12491145 27-Mar-17 12:09pm    
Thank for that,
It helped me a lot. But why should we used delta time and what is delta time.
Please explain this also.
Thanks in advance.
CPallini 27-Mar-17 12:23pm    
delta time is the time interval elapsed between current_position and new_position. In other words, if
current_position = position(t0)
new_position = position(t1)
then
delta_time = t1-t0

We use it, because, in order to create the movement we have to update the position while time flows.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900