Hi :)
The problem is in your getRotationToPoint method - it doesn't quite do what you want all the time. There's also a much shorter (and simpler) way of accomplishing it - there's a method in the Math class called atan2, and this returns the rotation based on the distance (in x and y values) from a certain point.
So if you replace the method with something like this:
//Get the distances to the mouse in x and y co-ordinates
int dX = x - getX();
int dY = y - getY();
//Get the value in radians and cast to an int
double rotation = Math.atan2(dY, dX);
//Convert to degrees
rotation = Math.toDegrees(rotation);
//Need to cast the double to an int
return (int)rotation;
..it should work as you want. The above can be condensed into a single line - I usually write it in 2 or 3 lines to avoid confusion, in this instance I've typed and commented the whole thing out fully so you can see what's going on.
My mistake - to avoid confusing people, the comment:
//Get the value in radians and cast to an int
shouldn't have the int cast bit in, that's not done until the last line. Not very awake today!
One other thing (and this is just me being extremely picky) with scenarios like this it makes sense to have the speed at 100% since the faster the speed the smoother the movement. Just a small tip :)
I was just about to post something here, but I see that Michael has beaten me to it. And his solution is slightly better anyway.
What I ended up with was
int deltaX = x - getX();
int deltaY = y - getY();
int angle = (int) (180 * Math.atan2(deltaY, deltaX) / Math.PI);
but Michael's use of the Math.toDegrees method is a little better anyway - then you don't have to do the conversion on foot like I did.
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html#atan2(double,%20double)
That's the documentation if you're after a thorough explanation.
To put it basically, atan just gives you the tan inverse. As for atan 2 - imagine a point on a graph at (x, y) - then draw a line from that point to the origin. atan2 returns the value of the angle of that line with the x axis.
One last point - it's generally risky to divide by a variable that could be any value without checking to see if it could be 0 first.
Computers can do all sorts of wonderful things, but dividing by 0 is alas not one of them :( I only mention it because it's a bug that's caught me out a couple of times in scenarios, and it's not always immediately obvious!
/0..
lots of fun.. i have made this mistake before in another program in C#..
one of my traits of programming, is i nearly always put everything in "try,catch" braces, So /0 has never caught me out.. thanks for the heads up....
2008/7/14
2008/7/14
2008/7/14
2008/7/14
2008/7/14
2008/7/14
2008/7/14
2008/7/14
2008/7/14
2008/7/28
2010/9/17