Game Development Reference
In-Depth Information
Figure 3-2.
Display object rollover effect and cursor change
Drag and Drop
EaselJS does not come with built-in functionality for dragging and dropping display objects but you can easily
set this up with a combination of a few mouse events. Take a look at the code in Listing 3-2, which accomplishes
drag-and-drop functionality.
Listing 3-2.
Creating Drag-and-Drop Functionality
circle.addEventListener('mousedown',function(e){
stage.addEventListener('stagemousemove',function(e){
circle.x = stage.mouseX;
circle.y = stage.mouseY;
});
stage.addEventListener('stagemouseup',function(e){
e.target.removeAllEventListeners();
});
});
First, you register for a
mousedown
event on your circle. This differs from the
click
event as it is fired as soon as
you click down, where the
click
event will fire only after quickly releasing your mouse button over the object. Once
you press down on the circle, you immediately listen for every update of the mouse position by setting a listener for
stagemousemove
, directly on the stage.
In the
stagemousemove
handler, you change the position of your circle to match that of the mouse, which will
give you the illusion of grabbing and dragging that item. In addition to registering for these mouse updates, you also
want to listen for when you let go of your circle (i.e., drop it). The
stagemouseup
will work nicely for this, as it will be
triggered as soon as you let go of the mouse button.
Once you do this, you can easily remove both the
mousemove
and
mouseup
event listeners on your stage by calling
its
removeAllEventListeners
. Since you are no longer registered for mouse move events, the circle ceases to follow
your mouse and is dropped when you let go.
With this drag-and-drop approach with display objects, let's put together a full example that puts this into action,
and then add a little bit of game logic to determine if you are dropping your shapes in the appropriate, predetermined
locations.