0

I am a beginner in C++ and know SFML. I have read a lot of articles about Sprite rotation towards Mouse and have been able to calculate proper angle of rotation of Sprite using this code:

void Player::changeAngle(double Mx, double My) { // This is for making Player point towards Mouse
 double dX = x - Mx; // x and y are global Varibales declared outside
 double dY = y - My;
 double magnitude = sqrt((dX*dX) + (dY*dY));
 double normalizedX = dX / magnitude;
 double normalizedY = dY / magnitude; 

 // This part is for Making Player move to Mouse
 Xvelocity = normalizedX * speed; // Xvelocity, Yvelocity and speed are global variables
 Yvelocity = normalizedY * speed;

 // Rotate towards the Mouse
 double angle = ( atan2(dY, dX) ) * 180 / M_PI;
 entity.setRotation(angle); // entity is a sf::RectangleShape
}

And, this bit actually worked and the Sprite was rotating properly only before a few days. Now the Sprite is just frozen on the screen, nothing happens. I had not made any changes in that code but I had added a View from the main.cpp. So here is how I call changeAngle() from the main.cpp :

case Event::MouseMoved : {
                Vector2f worldPos = window.mapPixelToCoords(Mouse::getPosition(window), view);
                double x = worldPos.x;
                double y = worldPos.y;
                player.changeAngle(x, y);
                break;
            }

I tried running the debugger and stepped through the code. I found that the angle is properly calculated and my mouse coordinates are also right. And, to my surprise, the sprite was Rotating now !

I could not understand why, but every time its in debugging mode, the Sprite will rotate. But, it won't rotate while running normally.

Can anyone tell me why and how to fix it so it rotates every time ? Tell me if there is any problem with my code. Thanks !

nvoigt
  • 75,013
  • 26
  • 93
  • 142
Delta_Shadow
  • 13
  • 1
  • 3
  • Nothing seems incorrect in the given code. Try compiling without optimizations (Debug, if you're using a build system) and running it normally, or with optimizations (Release) and running in a debugger. See [this](http://stackoverflow.com/q/1762088/6936976) for more. – ralismark Apr 21 '17 at 10:51
  • 1
    Ok I fixed it, I had only declared my variables x and y, not initialized them. Its done now. – Delta_Shadow Apr 21 '17 at 11:03

0 Answers0