sfml rotate

Hi, I would like to learn how to rotate a shape or sprite according to where the mouse is(point towards mouse).

I know how to rotate:
shape.setRotation(degree);
Origin:
shape.setOrigin(middle of shape);

But I don't know how to detect which direction the mouse is from the shape.
Last edited on
Given an initial point p0 = (x0, y0) and a final point p1 = (x1, y1), atan2(y1 - y0, x1 - x0) gives the angle from p0 to p1, expressed in radians in the interval (-pi, pi].
atan2(0, 0) is indeterminate.
Thanks a lot! How do you get where your mouse is?
sf::Mouse::getPosition(); http://sfml-dev.org/documentation/2.1/classsf_1_1Mouse.php

When in doubt you can always check the references. Being resourceful will help you out in the long run.
Sorry, that didn't work for me.
I found one of my old programs that can detect the mouse position. :)
if(GetCursorPos(&mousepos)){}
Because, why bother trying to figure out why something doesn't work when you can just move to a worse solution, right?
Thanks everyone!
guy.setRotation(atan2(mousepos.y-guypos.y,mousepos.x-guypos.x)*180/pi);works!
Sorry, I still have a problem.
I can't use guy.move because it will just unlimitedly move it, I can't use guy.SetPosition because it can only move up,down,left,right. What should I use?
Umm..what exactly are you trying to do and what exactly did you do? Also, please show us the code.
I'm trying to make it rotate to point towards the mouse, and when I press up, it moves towards the mouse.
atan2 will give you the angle, which you can use to set the rotation of your guy. The angle is of little/no use to you apart from that.


For movement, you'll want to get an orientation. You can get this by simply subtracting the current position from the goal position. This will give you the direction which you need to move, and how far in that direction you need to move in order to reach the goal.

You can scale down that orientation so that it has a length of 1 (ie: make it a "unit vector"). You can then multiply that unit vector by the guy's speed to get your movement vector. You then add that movement vector to your position to move.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// get our orientation
sf::Vector2f orientation = mouse_pos - current_pos;

// Use pythagorean theorum to find out the length of the orientation vector
auto length = sqrt( orientation.x*orientation.x + orientation.y*orientation.y );

// use the length to scale down the vector to make it have a length of 1
orientation /= length;

// now we can get our movement vector by applying our speed.  Higher numbers = the
//   guy moves faster
sf::Vector2f movement = orientation * speed;

// now that we have the movement vector, we can move by adding it to our position
current_pos += movement;
Topic archived. No new replies allowed.