[SOLVED] sfml gravity clipping shapes through floor

Issue

This Content is from Stack Overflow. Question asked by boomafett

I tried to make a cube that moves side to side and bounces off the floor.
It bounced a couple times and then fell through the floor.
I tried making the floor higher.
I tried adding extra vertical velocity.
I have tried everything i can think of.
I would like to get the cube to not fall through the floor.
how do I do that?

#include <SFML/Graphics.hpp> <iostream>

int main(){
    sf::RenderWindow window(sf::VideoMode(1000, 700), "project");
    window.setFramerateLimit(60);

    sf::RectangleShape rect;

    int w = 100;
    int h = 100;
    rect.setSize(sf::Vector2f(w, h));

    sf::Vector2f rectangle_position(500 - (w/2), 300 - (h/2));
    rect.setPosition(rectangle_position);

    float x_velocity = 3;
    float y_velocity = 3;

   while (window.isOpen()) {

           sf::Event event;
           while (window.pollEvent(event)) {


               if (event.type == sf::Event::Closed) window.close();

               if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) window.close();
           }

           if (rectangle_position.x > 1000 - w) {
               x_velocity = x_velocity * -1;
           }

           if (rectangle_position.x < 1 ) {
               x_velocity = x_velocity * -1;
           }

           if (rectangle_position.y > 700 - h) {
               y_velocity = y_velocity * -1;
           }

           if (rectangle_position.y < 50) {
               y_velocity = y_velocity * -1;
           }

               y_velocity = y_velocity + 3;

           rectangle_position.x = rectangle_position.x + x_velocity;
           rectangle_position.y = rectangle_position.y + y_velocity;
           rect.setPosition(rectangle_position);

           window.clear();
           window.draw(rect);

           window.display();
    }

}



Solution

In your implementation, once the bottom of the rectangle goes below the ground, you just reverse the velocity but never update the position of the rectangle. This causes the rectangle to sink below the ground.

You should make sure that the bottom of the rectangle never goes below the ground. This can be done by adding the following condition:

if (rectangle_position.y > 700 - h) {
    // make sure that rectangle never goes below the ground
    rectangle_position.y -= 3;
    y_velocity = y_velocity * -1;
}

And the result is:

enter image description here

Hope it helps.


This Question was asked in StackOverflow by boomafett and Answered by Aamir It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?