对于从Sprite类继承来的对象,要实现拖放当然是Flash/Flex学习笔记(13):对象拖动(startDrag/stopDrag) 里讲的方法最方便,但是对于不是从Sprite类继承得来的对象,这startDrag/stopDrag是不能用的,这时候只能采用最通常用做法:利用Mouse_Down,Mouse_UP,Mouse_Move事件来处理
注意:对象的Mouse_Move事件,只有当鼠标在对象上时才能被监听,如果用户鼠标移动过快,超出了对象的范围,该事件就不起作用了,所以监听Mouse_Move事件时,应该监听stage对象的Mouse_Move事件,而非对象本身的(详情见下面的代码)
package
{
import
flash.display.Sprite;
import
flash.events.MouseEvent;
import
flash.ui.MouseCursor;
import
flash.ui.Mouse;
public
class
MouseMoveDrag
extends
Sprite {
private
var
offsetX:
Number
;
private
var
offsetY:
Number
;
private
var
arrBalls:
Array
;
private
var
_draggedBall:Ball;
public
function
MouseMoveDrag():
void
{
arrBalls=
new
Array
(
7
);
for
(
var
i:
uint
=
0
; i<arrBalls.length; i++) {
arrBalls[i]=
new
Ball(
20
+Math.random()*
30
,Math.random()*
0xffffff
);
arrBalls[i].x=stage.stageWidth*Math.random();
arrBalls[i].y=stage.stageHeight*Math.random();
arrBalls[i].addEventListener(MouseEvent.MOUSE_DOWN, MouseDownHandler);
arrBalls[i].addEventListener(MouseEvent.MOUSE_UP, MouseUpHandler);
arrBalls[i].addEventListener(MouseEvent.MOUSE_OVER,MouseOverHandler);
arrBalls[i].addEventListener(MouseEvent.MOUSE_OUT,MouseOutHandler);
addChild(arrBalls[i]);
}
}
function
MouseOverHandler(e:MouseEvent):
void
{
Mouse.cursor=MouseCursor.BUTTON;
}
function
MouseOutHandler(e:MouseEvent):
void
{
Mouse.cursor=MouseCursor.AUTO;
}
//开始移动
function
MouseDownHandler(e:MouseEvent):
void
{
offsetX=e.localX;
offsetY=e.localY;
_draggedBall = e.target
as
Ball;
stage.addEventListener(MouseEvent.MOUSE_MOVE, stageMouseMoveHandler);
}
//停止拖动
function
MouseUpHandler(e:MouseEvent):
void
{
_draggedBall =
null
;
//拖动完成后,移除舞台的Mouse_Move监听
stage.removeEventListener(MouseEvent.MOUSE_MOVE, stageMouseMoveHandler);
}
function
stageMouseMoveHandler(e:MouseEvent):
void
{
//trace(e.target);
var
_ball:Ball=e.target
as
Ball;
if
(_ball!=
null
) {
//设置新的坐标
_ball.x=mouseX-offsetX;
_ball.y=mouseY-offsetY;
}
else
{
//trace("您拖得太快了!" + _draggedBall.toString());
if
(_draggedBall!=
null
){
_draggedBall.x=mouseX-offsetX;
_draggedBall.y=mouseY-offsetY;
}
}
}
}
}