Search code examples
c++sfml

SFML trying to get a sprite to track mouse


the below code doesn't seem to work I get a very strange sprite that sometimes tracks the mouse but almost gets bored and gives up. If this is the wrong place and need to go to maths exchange.

It seems to do something the sprite wiggles but doesn't follow the mouse and seems based on angle. The /2 is because the sprites position is in centre of screen and m_Resolution is the screen size and I've tried removing it. I didn't know if something was overflowing.

float angle = (atan2(mousePosition.y - m_Resolution.y/2,
    mousePosition.x - m_Resolution.x/2)
    * 180.)/ 3.14159;
m_Sprite.setRotation(angle);

I've tried for a while I've seen similar questions but my answer seems to match so unsure.


Solution

  • If was writing your code, I did it like this:

    float dX = mousePosition.x - sprite.x;//vector, collinear straight line whicn crosses sprite an cursor on X axis;
    float dY = mousePosition.y - sprite.y;//same, but to Y axis;
    
    float angle = (atan2(dY, dX)*180)/3.14159;//CALCULATING ANGLE
    sprite.setRotation(angle + 90);