Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java game development - Look and shoot at mouse coordinates

Tags:

java

mouse

angle

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

like image 865
Alexander Sandberg Avatar asked Nov 05 '22 21:11

Alexander Sandberg


2 Answers

double angle = Math.atan2(yMouse-yChar, xMouse-xChar);
like image 75
Maurice Perry Avatar answered Nov 15 '22 03:11

Maurice Perry


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

like image 26
ratchet freak Avatar answered Nov 15 '22 05:11

ratchet freak