Computer Science Canada Java animation help. |
Author: | kingghaffari [ Mon Nov 07, 2011 3:51 pm ] | ||||
Post subject: | Java animation help. | ||||
Hey guys, I am making a simple program that involves having a circle move towards the mouse when the user holds 'w' it's the equivalent of moving "forwards" relative to there the "player" is facing. I have two classes GameFrame.class
and Game.class
It seems to work fine, unless the user moves the mouse constantly as the circle is moving. I don't understand WHY the circle moves so spastic-like, as the formula shouldn't even allow for that kind of movement. And help would be greatly appreciated. Thanks, Sina Ghaffari |
Author: | Zren [ Mon Nov 07, 2011 5:33 pm ] |
Post subject: | RE:Java animation help. |
Java naming conventions are that variables are to use camelcase. It personally annoys me to see capitalized variables or other class members (Eg: functions). Anyways, it looks like you The variable angle seems to be a the angle calculated in degrees. However the parameter for Math.cos(double radians) uses radians. Math.toDegrees(Math.sin( angle )) Converting the result of those trig functions to degrees means nothing as the result is not even an angle. So: You need to pass an angle in radians into trig functions. Solutions: - Have your angle variable be represented in radians (radians are cool!) - Look into Math.toRadians(double angleDegrees) Further: Look into what sine() and cosine() actually do, along with vector math in general. Post here if you'd like us to expand on this subject. |
Author: | kingghaffari [ Mon Nov 07, 2011 6:04 pm ] |
Post subject: | Re: Java animation help. |
YES! You have succeeded where many others have failed! Everything works fine, but for some reason i have to change PX += and PY += to PX -= and PY -=. Works like a charm now! |
Author: | Zren [ Mon Nov 07, 2011 9:53 pm ] |
Post subject: | Re: Java animation help. |
kingghaffari @ Mon Nov 07, 2011 6:04 pm wrote: For some reason i have to change PX += and PY += to PX -= and PY -=. Works like a charm now!
That's because you are calculating displacement incorrectly on this line: angle = Math.toDegrees(Math.atan2((PY - MouseY),(PX - MouseX))); Displacement is as follows: dx = x2 - x1 The logic is that dx will be the distance from x1 to x2. It will be positive if x1 < x2. It will be negative if x1 > x2. It's the displacement from x1 to x2. Basically you had it backwards as your having the displacement from mouse to point. That would make it negative if the mouse was below-right of the point, when the coordinates of the mouse are actually greater than those of the point. So all the while you wanted the displacement of point to mouse. The error there flowed into the calculation for Math.atan2() to get the angle, which flowed down to your vector addition. The same logic can be used for the y-axis. |