Reputation: 99
The code below rotates a rectangle around the origin to -90 degrees when R
is pressed and to 40 degrees when A
is pressed.
However, I want it to rotate gradually to -90 or 40 degrees, i.e. each time I press R
it moves gradually to -90 degrees where it stops, and if I press A
it will move gradually in the opposite direction to 40 degrees where it stops.
Right now it's working, but when I press R
, the rectangle jumps directly to the -90 degrees position, and when I press A
the rectangle jumps directly to the 40 degrees position.
How can I change this behaviour?
#include <SFML/Graphics.hpp>
int main(){
sf::RenderWindow window(sf::VideoMode(640, 480), "Use 'q','w','a','s','z' & 'X' to move the are");
sf::RectangleShape rect(sf::Vector2f(100,10));
rect.setFillColor(sf::Color::Green);
rect.setPosition(200, 300);
rect.setOrigin(20, 20);
rect.setSize(sf::Vector2f(160, 40));
while (window.isOpen()){
sf::Event event;
while (window.pollEvent(event)){
if (event.type == sf::Event::Closed)
window.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::R)){
rect.setRotation(-90);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)){
rect.setRotation(40);
}
window.clear();
window.draw(rect);
window.display();
}
}
Upvotes: 0
Views: 154
Reputation: 1624
First, you need a variable to determine the speed of rotation; you said you wanted it to be ~1.0. We can make use of the setRotation
, rotate
, and getRotation
functions to make the rest very easy:
float velocity = 1.0;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::R))
{
if (rect.getRotation() > -90)
rect.rotate(-velocity);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
if (rect.getRotation() < 40)
rect.rotate(velocity);
}
}
window.clear();
window.draw(rect);
window.display();
}
As you can see the rotate
function rotates the rectangle the number of degrees you specify. setRotation
however sets the rectangle's rotation to immediately be the specified angle instead of rotating the rectangle frame by frame.
Upvotes: 1