5

I'm going to make a game where you run around with a character, seen from above. But the problem is how do I make the character look at the mouse all the time? And how do I calculate the angle so that I can shoot towards the mouse(where I'm currently looking). I guess you have to play around with trigonometry and stuff like that to get angles, but I really don't know how.

I'm pretty good at math, so I might figure it out if you guys give me some help.

And sorry for my eventually bad english, I'm swedish :)

Thanks, Alexandberg

1
  • I think you answered your own question...use trig
    – gshauger
    Jun 1, 2011 at 23:23

2 Answers 2

1
double angle = Math.atan2(yMouse-yChar, xMouse-xChar);
3
  • That didn't work very well I think. I just got numbers from -3 to 3, but I don't know what to do with them. I thought the angles would be more like 0-360. Jun 2, 2011 at 0:24
  • 1
    It's -pi to pi actually because it's in radians. To convert it to degrees, call Math.toDegrees() Jun 2, 2011 at 1:54
  • Thanks, the angles are working now (except for the angles are between -180 and 180, but I can fix that). The problem is, how do I draw a line that goes from the player through the mouse (it continues after it hits the mouse location). Right now I got the distance between the player and the mouse point and the angle. Jun 2, 2011 at 10:15
1

as you said a big hint can be found in trig

Point pl = getCharacterLox();
Point mouse = getMouseLoc();
double cos = (mouse.getX()-pl.getX());
double sin = (mouse.getY()-pl.getY());
cos/=Math.hypot(cos,sin);//normalize 
double angle = Math.copySign(Math.acos(cos),sin);

I used a little trick here in the last line: acos is between 0 and PI but if sin is negative it should be negated, if sin is 0 it will evaluate to +0.0 and angle will be 0 or PI regardless

1
  • Thanks alot, I think I got it now. Edit: When I try to print the angle to check if it works it's just between 0-3 (aprox). How do I get the angle out of that? Because I don't see how I'm going to use the angle right now to do anything. Jun 1, 2011 at 23:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.