Getting direction / angle to move something towards the mouse?

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

Previous topic - Next topic

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:

public float velX = 0;
public float velY = 0;

public void move(float mX, float mY){

//mX and mY represents the Mouse.getX() and Mouse.getY();

float x = this.getPosX();
float y = this.getPosY();

//Then, I try to get the angle.

float angle = Math.atan2 ( y - mY, x - mX ) * 57.2957795f; //57... is 180/pi

float scaleX = (float)Math.cos(angle);
float scaleY = (float)Math.sin(angle);

velX = scaleX * speed;            //speed is already defined
velY = scaleY * speed;


//That's it, I created velX and velY

}


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

public void loop(){

posX += velX;
posY += 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

float angle = Math.atan2 ( y - mY, x - mX ) * 57.2957795f; //57... is 180/pi

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:
float angle = (float)Math.atan2 ( mY - y, mX - x );

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 ;D


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:
Math.atan2((screenHeight - mY) - y, mX - x);
Programmers will, one day, rule the world... and the world won't notice until its too late.Just testing the marquee option ;D

Glyder

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