This site requires JavaScript, please enable it in your browser!
Greenfoot back

Report as inappropriate.

Skintkingle
Skintkingle presents ...

2008/7/14

PointToMouse

This is suppost to make the crocs point
at any given point (i.e. the mouse)
but they don't turn all the time..
only some of the time..
Im not too sure why.
please have a look at the code, then get
back to me!
Thanks alot..

5269 views / 18 in the last 7 days

Tags: mouse demo with-source

open in greenfoot
Your browser does not support the canvas tag.
mjrb4mjrb4

2008/7/14

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!
mjrb4mjrb4

2008/7/14

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 :)
mikmik

2008/7/14

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.
SkintkingleSkintkingle

2008/7/14

Thank you both for your help.. i just google searched inverse tan for Java.. may i ask what atan2 does, as apposed to atan?
mjrb4mjrb4

2008/7/14

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.
SkintkingleSkintkingle

2008/7/14

ah, i understand. thanks alot. :)
mjrb4mjrb4

2008/7/14

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!
SkintkingleSkintkingle

2008/7/14

/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....
JL235JL235

2008/7/28

I like the crocodile images, they are really nice.
annekm21annekm21

2010/9/17

effective use of math function

See all comments

Want to leave a comment? You must first log in.

Who likes this?

No votes yet.