## Getting direction / angle to move something towards the mouse?

Started by Glyder, November 27, 2012, 19:41:18

#### Glyder

I basically have an object, which has two variables (X and Y)
Whenever I click the mouse, I call a method to move this object towards the Mouse's X and Y.

I don't have my code right now but it's something like this:

Then, in the Entity's loop, It moves itself using the velX and velY.

//END

Everything on the code not-shown is fine, I can move the entity properly if I use set values for the velocities.
But if I try to get velocity from the move() method, it gives weird results.
Basically, it doesnt work, the entity seems to move in a totally different way, instead of going in the direction of the mouse. It really doesnt make any sense.

I'm creating this topic after several tries to achieve this..
If you have any idea of how to do this, please, tell me
I just want to move the Entity in the direction of the mouse.

#### Fool Running

I think this statement has two problems.
1) If the mouse is to the right of the object, you want the location you look for to be positive, but it will currently be negative because the mouse coordinates will be bigger then the objects coordinates.
2) It looks like you are trying to get the angle in degrees when the sin() and cos() function take radians (i.e. what the atan2() method returns).

Thus, I think your code should look like:

Also, since all the Math functions are using doubles anyways, you might make angle a double so you skip the conversion steps.

EDIT: Looking at your image, it looks like your y-axis might be upside down, so you might need to just change the x value (i.e. leave the y calculation as 'y - mY').
Programmers will, one day, rule the world... and the world won't notice until its too late.Just testing the marquee option

#### Glyder

Tried that, didn't work :/

#### Fool Running

I actually decided to try it out. Turns out the mouse coordinates are not what I remembered them being.
The correct algorithm for getting the angle is:
Programmers will, one day, rule the world... and the world won't notice until its too late.Just testing the marquee option

#### Glyder

That worked perfectly, thanks a lot for sharing the code.