Hello everyone!
I just started to learn SFML a few days ago, and I figured I wanted to do a little exercise to test how I'm doing: having a ball that, starting in the middle of a window, bounced around the window, much like the dvd logo on the television.
And everything worked fine except one small issue: The ball started accelarating a lot almost immediately. I really don't understand how.
Could somebody help me, either telling me where the mistake is or giving me any suggestions of how to make the code differently so that this problem disappears?
Thank you very much!
(Also, I know I copied the whole code, which is something one is advised not to do. Yet, as I'm really not sure where the problem is, I decided to copy it all, because it isn't that big)
[/code
#include<SFML/Graphics.hpp>
float x_position(float t, float v) {
float x = v * t;
return x;
}
float y_position(float t, float v) {
float y = v * t;
return y;
}
int main() {
float t = 0;
int vx = 50;
int vy = 50;
//window
sf::RenderWindow window(sf::VideoMode(1000, 600), "SFML");
//ball
sf::Texture ball_texture;
ball_texture.loadFromFile("Basketball.png"); //340x340 pixels
sf::Sprite ball;
ball.setTexture(ball_texture);
ball.setOrigin(170, 170);
ball.scale(0.1f, 0.1f);
ball.setPosition(500, 300);
while (window.isOpen()) {
ball.move(x_position(t,vx), y_position(t,vy));
t += 0.000007;
//boundaries
if (ball.getPosition().x > 983 || ball.getPosition().x < 17) {
vx *= -1;
}
if (ball.getPosition().y > 583 || ball.getPosition().y < 17) {
vy *= -1;
}
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(sf::Color(150,150,150));
window.draw(ball);
window.display();
}
}]
(I know this really isn't the most elegant code, but it is what I came up with)
I didn't read through your code very carefully, but the problem is probably here
ball.move(x_position(t,vx), y_position(t,vy));
t += 0.000007;
The move function (https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Transformable.php#a86b461d6a941ad390c2ad8b6a4a20391) adjusts the sprites position relative to its previous position. So if your ball sprite is at the position (500, 300) and you call ball.move(1,1) then your sprite will now be at position (501, 301).
Though, think about what x_position() and y_position() will return each time through the game loop. Each time through the loop you keep incrementing the variable t such that it keeps getting bigger and bigger. Thus the numbers returned by those functions will keep getting bigger and bigger, and so you will be moving the ball by bigger and bigger amounts. That's acceleration.
You might want to take a step back and ask yourself what the variable t is supposed to be for. This article on timesteps (https://gafferongames.com/post/fix_your_timestep/) might be helpful for you.