I am trying to make a shape bounce from the top of the window to the bottom and back, over and over
i can not get the height correct, so i guessed at 800
any ideas
thanks
------------------------------------------------------------------
#include <SFML/Graphics.hpp>
#include <iostream>
int main()
{
bool bShouldObjGoDown = true;
sf::RenderWindow window(sf::VideoMode(800, 800), "SFML Application");
// ,sf::Style::Fullscreen
window.setFramerateLimit(60);
sf::CircleShape shape;
shape.setRadius(40.f);
shape.setPosition(1, 1);
shape.setFillColor(sf::Color::Cyan);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(shape);
window.display();
if(bShouldObjGoDown == true)
{
shape.move(0,5);
}
if(bShouldObjGoDown == false)
{
shape.move(0,-5);
}
std::cout << shape.getPosition().y << std::endl;
if(shape.getPosition().y < 1)
{
bShouldObjGoDown = true;
}
if(shape.getPosition().y > 800)
{
bShouldObjGoDown = false;
}
}
}
end
on the part
if(shape.getPosition().y > 800)
i want the 800 to be the botton of the window
i want the ball to bounce off the boarders
please help this is driving me crazy
thank you
By default, the shape's position is its left-top coordinates. You can solve the problem either by changing the origin of the coordinates (for example, to be at the bottom of the shape when checking against the bottom border collision), or by adding the height of the shape to its vertical position when checking if it bounces off the bottom of the window.
For example:
if(shape.getPosition().y + height > 800)
{
bShouldObjGoDown = false;
}
// height is the circle's radius X 2; you can also retrieve it by calling shape.getGlobalBounds().height
I'm assuming that the reason why you need to guess the height is because you want the window to be resizable? Anyway, you can always retrieve the window's size by using its getSize() method.
For example, to get the height of the window you would call:
auto height = window.getSize().y;