Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Rotate after the cursor  (Read 1681 times)

0 Members and 1 Guest are viewing this topic.

domcsidd

  • Newbie
  • *
  • Posts: 9
    • View Profile
Rotate after the cursor
« on: May 04, 2013, 05:30:13 pm »
I would like to make a space shooting games , with spaceships. But i don't know , how can i rotate my Spaceship , after the cursor. I saw the c++ "atan2 ", but it not works, perfectly .here's my rotate code :
if(xMouseWindowX/2) xMouse=xMouse-WindowX/2;
if(yMouseWindowY/2) yMouse=yMouse-WindowY/2;
Rotation =std::atan2(yMouse,xMouse);
Spaceship.setRotation(Rotation*57.29);
 
How can I do it ?  :)

AlexAUT

  • Sr. Member
  • ****
  • Posts: 396
    • View Profile
Re: Rotate after the cursor
« Reply #1 on: May 04, 2013, 08:56:24 pm »
Fortunately, two days ago I made an example for an reallife friend about the exact same topic  :)

Heres the Code, I hope it can help you.

#include <iostream>
#include <cmath>

#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/System/Vector2.hpp>

const float PI = 3.14159265359f;

float ComputeAngle(sf::Vector2f point1, sf::Vector2f point2)
{
    return std::atan2((point2.x - point1.x), (point2.y - point1.y)) * (180/PI);
    // std::atan2() returns RAD but you need DEG for SFML so *(180/PI) to convert it.
}


int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600), "Atan2 Test");
    window.setVerticalSyncEnabled(true);

    sf::RectangleShape rect; // Your spacehip
    rect.setSize(sf::Vector2f(50,20));
    rect.setFillColor(sf::Color::Green);
    rect.setOrigin(rect.getLocalBounds().width / 2.f, rect.getLocalBounds().height / 2.f); // Its important that the origin is in the middle of the sprite
    rect.setPosition(400,300);





    while(window.isOpen())
    {
        sf::Event event;
        while(window.pollEvent(event))
        {
            if(event.type == sf::Event::Closed)
            {
                window.close();
            }
        }

        float rotAngle = ComputeAngle(rect.getPosition(), static_cast<sf::Vector2f>(sf::Mouse::getPosition(window)));
       // std::cout << rotAngle << std::endl;
        rect.setRotation(90-rotAngle); // "90-" Depends on how your Spaceshape is rotated by default



        window.clear(sf::Color(0,0,173));

        window.draw(rect);

        window.display();

    }

    return 0;
}

 


AlexAUT

domcsidd

  • Newbie
  • *
  • Posts: 9
    • View Profile
Re: Rotate after the cursor
« Reply #2 on: May 05, 2013, 09:38:07 am »
Thank you very much :D