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

2012/2/17

location of mouse

tylers tylers

2012/2/17

#
how do you get the location of the mouse
Morran Morran

2012/2/17

#
It says in the Greenfoot API . What you want to do is:
MouseInfo mouse = Greenfoot.getMouseInfo();
//use this to get the x position of the mouse.
mouse.getX();
//use this to get the y position of the mouse.
mouse.getY();
And that's all that there is to it. Wherever you need the mouse's position, just use that code.
Builderboy2005 Builderboy2005

2012/2/17

#
That's not *quite* all there is to it unfortunately. getMouseInfo() will return null if the Mouse hasn't moved since the last frame, and will cause that code to throw an error. The code I like to use looks something like this:
MouseInfo mouse = Greenfoot.getMouseInfo();
if(mouse!=null){
   mx = mouse.getX();
   my = mouse.getY();
}
Where mx and my are integer variables defined to keep track of the mouse position even when it is not moving. Why this is not the default behavior I don't know.
bourne bourne

2012/2/17

#
Or nesting it within the mouse event checks like mouseMoved or mouseDragged.
MouseInfo mouse = Greenfoot.getMouseInfo();  
if(Greenfoot.mouseMoved(null) || Greenfoot.mouseDragged(null)){  
   mx = mouse.getX();  
   my = mouse.getY();  
} 
You need to login to post a reply.