我有2个物体和1个目标。我将在鼠标键关闭时拖动一个对象,当鼠标键向上时将其拖放,并且对象位于目标之一上。当o2在目标中并将o1拖到目标时,o2会到达其位置,而o1不会到达目标。
有人可以帮助我吗?
var t1:int=0; //target is empty
o1.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
o1.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
function startDragging(evt:MouseEvent):void
{
o1.startDrag();
if (o1.x == tar1.x && o1.y == tar1.y)
{
t1 = 0;
}
}
function stopDragging(evt:MouseEvent ):void
{
if (tar1.hitTestObject(o1) && t1 == 0)
{
o1.x = tar1.x;
o1.y = tar1.y;
o1.stopDrag();
t1 = 1; //target is full
}
else
{
o1.x = 250;
o1.y = 200;
o1.stopDrag();
}
}
o2.addEventListener(MouseEvent.MOUSE_DOWN, startDragging2);
o2.addEventListener(MouseEvent.MOUSE_UP, stopDragging2);
function startDragging2(evt:MouseEvent):void
{
o2.startDrag();
if (o2.x == tar1.x && o2.y == tar1.y)
{
t1 = 0;
}
}
function stopDragging2(evt:MouseEvent ):void
{
if (tar1.hitTestObject(o2) && t1 == 0)
{
o2.x = tar1.x;
o2.y = tar1.y;
o2.stopDrag();
t1 = 1;}
else
{
o2.x = 250;
o2.y = 140;
o2.stopDrag();
}
}
答案 0 :(得分:1)
诀窍是,当您拖动o2
时,您的MouseEvent.ROLL_OVER
对象会收到第一个o1
事件,然后会收到MOUSE_UP
个事件以及o1
。然后,两个事件侦听器分别触发。第一个监听器stopDragging
激活,检查t1
“全局”变量,发现它为0 - 确定,o1
设置为target
,然后stopDragging2
触发,bam,t1
非零,因此else
分支触发器和o2
被替换回起始位置。通常的解决方案是从您的对象添加和删除侦听器,并通过事件的target
属性寻址对象,如下所示:
o1.addEventListener(MouseEvent.MOUSE_DOWN,startDragging);
o2.addEventListener(MouseEvent.MOUSE_DOWN,startDragging);
// note that listeners are not separate functions! We will
// be using event.target to check which object is being dragged
function startDragging(e:MouseEvent):void {
e.target.removeEventListener(MouseEvent.MOUSE_DOWN,startDragging);
// surprise! This object will not be moved via MOUSE_DOWN,
// because it's already being moved
e.target.addEventListener(
e.target.startDrag(); // drag
} // no alteration to t1, as we don't really care if we're dragging
// our object off target - yet
function stopDraggging(e:MouseEvent):void {
e.target.stopDrag(); // stop dragging anyway
e.target.removeEventListener(MouseEvent.MOUSE_UP,stopDragging);
// and stop listening for mouse-ups
if (e.target.hitTestObject(tar1)&& (t1==0)) {
e.target.x=tar1.x;
e.target.y=tar1.y;
t1=1; // target is full
return; // emergency exit. We don't need to do more
}
// should you add more targets, you can put hitTest code here
// if we reached this point, we don't hit any targets
// so we should put our objects back into their positions.
// The best way would be storing their base coordinates on
// objects themselves, so we don't have to run elsewhere for them
e.target.x=e.target.startingX; // make sure these are filled
e.target.y=e.target.startingY;
e.target.addEventListener(MouseEvent.MOUSE_DOWN,startDragging);
// and enable this object to be dragged again.
}