Greenfoot. I’ve talked about it before and here I am again. This time it isn’t just a review, it is about coding.
The Challenge
My challenge today was to make some actors draggable. In other words, make them move with the mouse while the mouse is pressed down over them. Greenfoot has some documentation about the mouse. There is little explanation about the class though and it’s not what I call intuitive since it isn’t statically accessible. So wading through unclear documentation and traveling with a tutorial, I figured it out.
The Puzzle Pieces
It’s really simple once you know the methods Greenfoot exposes to you and how to use them. In the Greenfoot class, there is a static method called mouseDragged
. This method is true when the mouse is dragging the passed in Actor. This is handy because it tells you two things. It tells you first that something is being dragged and second, it tells you that the this actor is being dragged. So this is one piece of the puzzle.
The next piece of the puzzle is the mysterious MouseInfo
class. I call it mysterious because it not static-based, it cannot be initialized by you and it certainly should have those Greenfoot.mouse*
methods attached to it. Anyway, MouseInfo allows you to get a reference to the actor that is being dragged but also the current coordinates of the mouse pointer. I mentioned that you cannot initialize your own MouseInfo object and that’s true. So how do you get one? You can call Greenfoot.getMouseInfo
to get one. So that’s the last puzzle piece. Let’s put them together now.
The Bigger Picture
So putting together Greenfoot.mouseDragged
and MouseInfo
we can write some code.
// this act method is an actor, the rest of the code is omitted for brevity. public void act() { if ( Greenfoot.mouseDragged(this) ) { MouseInfo mouse = Greenfoot.getMouseInfo(); this.setLocation(mouse.getX(), mouse.getY()); } }
So what does that do? That literally tests to see if this object is being dragged and if it is, get a mouse object and set the current object’s location to the location of the mouse. This simulates dragging.
So that’s how you make