Game Development Reference
In-Depth Information
Where is the Mouse?
Often we would like to know the exact position of where the mouse was clicked.
Luckily, you don't have to look far; the MouseEvent object that is passed into the
callback carries this information for you. Further, it carries two sets of x and y. The
first set is called local coordinates and the other the global or the stage coordinates.
Yes, you guessed it right—local x and y is with respect to the sprite's coordinates and
the stage x and y is relative to the stage coordinates.
private function onMouseClick(e:MouseEvent):void {
trace("onMouseClick ID: " + m_id);
trace("Local Location X: " + e.localX + " Y: " + e.localY);
trace("Stage Location X: " + e.stageX + " Y: " + e.stageY);
}
Drag-and-drop
Not all games need drag-and-drop, but it is a useful trick to keep under your hat.
Let's see how easy it is to drag a sprite around on the stage with the mouse.
As you are now already proficient in handling mouse events, there are just two
methods that you need to know about:
startDrag()
stopDrag()
These two methods are defined in the Sprite class. When you call startDrag() on
the sprite, the Flash runtime will move the sprite with the mouse position.
The stopDrag() will make the Flash runtime let go of the sprite that is being
dragged. It will also let go if startDrag() is called on another sprite.
StartDrag() takes two parameters: lockCenter , if true ( false by default) locks
the center of the sprite to the mouse cursor; the second parameter, called the bounds,
specifies a rectangular area that the sprite is not allowed to move out of. Note that
the bounds must be expressed relative to the sprite's parent coordinates.
So, what is a good place to call startDrag and stopDrag ? Since we can detect the
mouse down and mouse up events on a given sprite, we can simply add it there.
A full listing of the example is as follows. The first example uses default values
during the startDrag and the second one will constrain the dragging to
specified bounds.
 
Search WWH ::




Custom Search