In Greenfoot, you can use the MouseInfo
class to find out where the mouse is. I’ve talked about making actors draggable, but sometimes you don’t want to use the Mouse Location in an actor, but possibly inside the world instead.
Take a look at the following code:
public static int MouseX = 0, MouseY = 0; private void getMouse() { MouseInfo mouse = Greenfoot.getMouseInfo(); if ( mouse != null ) { MouseX = mouse.getX(); MouseY = mouse.getY(); } } public void act() { getMouse(); }
This code is inside of a subclass of World. It will update the MouseX
and MouseY
variables anytime the mouse moves. So why would we use this?
Let’s say we wanted to add an actor at the mouse’s location when we press a button? You can use this code to do it. Using the code above, another method and a little update to act
, we can just that.
public void act() { getMouse(); addActor(); } private void addActor() { if ( Greenfoot.isKeyDown("d") ) { addObject(new Thing(), MouseX, MouseY); } }
Looking at our new method, addActor
, you can see we check to see if d is pressed down and then if it is, we add a new Thing at the location of the mouse. It’s really that easy.
Happy Greenfooting.