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
double angle = Math.atan2(yMouse-yChar, xMouse-xChar);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With