startDrag - 停止对角线移动

时间:2010-11-23 00:18:04

标签: actionscript-3

有没有办法让一个带有startDrag的MovieClip,但是只强制水平和垂直(即不是对角线)移动?

4 个答案:

答案 0 :(得分:4)

是肯定的。有几个选择。

A。您可以选择使用startDrag()函数,并为其可拖动对象提供带有边界矩形的第二个参数。类似的东西;

dragSprite.startDrag(false, new Rectangle(0, 0, 20, stage.stageHeight));

B。您可以将可拖动对象设置为侦听鼠标事件,并根据鼠标移动移动鼠标事件。类似的东西:

dragSprite.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownEventHandler);

function mouseDownEventHandler(evt:MouseEvent):void
 {
 stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveEventHandler);
 stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpEventHandler);
 }

function mouseMoveEventHandler(evt:MouseEvent):void
 {
 //only move dragSprite horizontally
 //dragSprite.y = evt.stageY;
 dragSprite.x = evt.stageX;
 }

function mouseUpEventHandler(evt:MouseEvent):void
 {
 stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveEventHandler);
 stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpEventHandler);
 }

答案 1 :(得分:4)

这是我的解决方案。它在点击时跟踪mouseX和mouseY并将其与最后位置进行比较。找出鼠标主要移动的方向然后将对象移动到那里。您可能需要添加一些额外的逻辑来将对象锁定到最接近的第10个单位或任何单位大小,以形成用于游戏或有组织放置对象的捕捉网格。

更新:我继续添加了一个snapNearest函数来帮助控制移动。

import flash.events.MouseEvent;
import flash.events.Event;

dragObj.addEventListener(MouseEvent.MOUSE_DOWN, dragIt);

var curX:Number = 0;
var curY:Number = 0;
var oldX:Number = 0;
var oldY:Number = 0;
var gridUnit:Number = 25;

function dragIt(e:MouseEvent):void
{
    // set x,y on down
    oldX = mouseX;
    oldY = mouseY;

    // add mouse up listener so you know when it is released
    stage.addEventListener(MouseEvent.MOUSE_UP, dropIt);
    stage.addEventListener(Event.ENTER_FRAME, moveIt);

    trace("Start Drag")
}

function moveIt(e:Event):void
{

    // figure out what the main drag direction is and move the object.

    curX = mouseX;
    curY = mouseY;

    // figure out which is the larger number and subtract the smaller to get diff
    var xDiff:Number = curX > oldX ? curX - oldX : oldX - curX;
    var yDiff:Number = curY > oldY ? curY - oldY : oldY - curY;

    if(xDiff > yDiff) {
        dragObj.x = snapNearest(mouseX, gridUnit);
    }else{
        dragObj.y = snapNearest(mouseY, gridUnit);
    }

    oldX = mouseX;
    oldY = mouseY;
}

function dropIt(e:MouseEvent):void
{

    //remove mouse up event
    stage.removeEventListener(MouseEvent.MOUSE_UP, dropIt);
    stage.removeEventListener(Event.ENTER_FRAME, moveIt);

    trace("Stop Drag")

}


// snap to grid
function snapNearest(n:Number, units:Number):Number
{

    var num:Number = n/units ;
    num = Math.round(num);
    num *= units;

    return num;

}

答案 2 :(得分:2)

您可以使用修饰键,例如,正常行为将是水平&按下shift键垂直移动。

    function mouseMoveEventHandler(evt:MouseEvent):void
    {
        if(!evt.shiftKey)
           dragSprite.x = evt.stageX;
        else
           dragSprite.y = evt.stageY;           
    }

答案 3 :(得分:1)

您只能约束到一个轴或另一个轴(使用约束矩形)但是在您建议的方法中可以进行对角移动,除非您还定义了一些其他限制...例如网格。