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

Author Topic: Rotate sprite to the mouse calculation  (Read 12529 times)

0 Members and 1 Guest are viewing this topic.

GroundZero

  • Jr. Member
  • **
  • Posts: 69
    • View Profile
Rotate sprite to the mouse calculation
« on: August 26, 2012, 02:49:14 pm »
Dear reader,

I am trying to let my sprite face the position of my mouse, it works almost, but it has some bugs.
It seems like the angle is not exactly right, and when I turn right, my sprite turns left, and vice versa.

Can someone tell me whats I did wrong? I think the problem is in my math calculations, since I have no
knowledge on math and stuff to be honest lol.

I checked on this forum, and found code which was almost like mine, and for them its working so no clue why it is not for me lol.

void character::lookAtMouse(sf::RenderWindow &win){
    sf::Vector2f curPos = sprite.getPosition();
    sf::Vector2i position = sf::Mouse::getPosition(win);

    // now we have both the sprite position and the cursor
    // position lets do the calculation so our sprite will
    // face the position of the mouse
    const float PI = 3.14159265;

    float dx = curPos.x - position.x;
    float dy = curPos.y - position.y;

    float rotation = (atan2(dy, dx)) * 180 / PI;

    sprite.setRotation(rotation);
}

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32504
    • View Profile
    • SFML's website
    • Email
Re: Rotate sprite to the mouse calculation
« Reply #1 on: August 26, 2012, 02:58:34 pm »
Try rotation + 180.
Laurent Gomila - SFML developer

GroundZero

  • Jr. Member
  • **
  • Posts: 69
    • View Profile
Re: Rotate sprite to the mouse calculation
« Reply #2 on: August 26, 2012, 03:22:34 pm »
Hi Laurent,

thank you for your suggestion. Ill add a bit more or less, but then it should be fine indeed.
is there anything else in the code that I can improve?
« Last Edit: August 26, 2012, 03:29:18 pm by GroundZero »

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32504
    • View Profile
    • SFML's website
    • Email
Re: Rotate sprite to the mouse calculation
« Reply #3 on: August 26, 2012, 05:41:40 pm »
Your code is ok. In case you use a custom view in the future, don't forget to first convert the mouse coordinates to world coordinates (win.convertCoords(position)).

Quote
Ill add a bit more or less, but then it should be fine indeed
It should be exactly 180.
Laurent Gomila - SFML developer

 

anything