Answer the question
In order to leave comments, you need to log in
Why does the ball get stuck in the wall?
The ball sometimes gets stuck in the wall, what should I do?
#include <SFML/Graphics.hpp>
using namespace sf;
float dx = 0.7;
float dy = 0.7;
float x = 0;
float y = 0;
int main() {
Clock clock;
CircleShape shape(32);
RenderWindow window(VideoMode(320,480),"Game");
while(window.isOpen()){
float time = clock.getElapsedTime().asMicroseconds();
clock.restart();
time = time/3000;
Event event;
while(window.pollEvent(event)){
if(event.type == Event::Closed) window.close();
}
shape.setPosition(x,y);
x+=dx*time;
y+=dy*time;
if(x + 64 > 320.0 || x < 0.0)
{
dx = -dx;
//dy = -dy;
}
if(y + 64 > 480.0 || y < 0.0)
{
//dx = -dx;
dy = -dy;
}
window.clear();
window.draw(shape);
window.display();
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
You have a variable frame rate here. If the ball has gone far beyond the wall in a long frame, the short frame will not be able to pull it out and inverts the speed again - the ball is stuck. (I easily replicated this with Windows 10's "Aero Shake" feature.)
In the simplest case - to determine which wall the ball jumped out of, and give it such a speed that it returns to the site. Not just vx=−vx, no matter where that speed is headed.
It is also worth limiting the duration of the frame, and if, for example, it lasted more than 0.2 s, let the game “stumble” in such a situation. Something bad happened, and I don’t want everything to go off the rails from their positions.
Also it is necessary to give float time = clock.restart().asMicroseconds();
Now computers are fast and the error is insignificant, but still.
You can correct not only the velocity vector but also the coordinate. This will save the ball from singularities.
if(x + 64 > 320.0) {
dx = -dx;
x = 320.0;
} else if (x < 0.0) {
dx = -dx;
x = 0.0;
}
if (y ... e.t.c.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question