AS3如何仅在x轴上启动?

muu*_*ess 6 actionscript-3

我有一个红色正方形,我只想在x轴上拖动.我已经制定了一个简单的脚本,理论上应该可行,但它的行为并不正常.这有点难以解释......广场一直在错误的位置开始,舞台位置似乎在变化,所以有时你不能将广场一直拖到右边......

red.buttonMode = true;
red.addEventListener(MouseEvent.MOUSE_DOWN, dragHandler);

function dragHandler(e:MouseEvent):void {
    var ypos:Number = e.currentTarget.y;
    var xpos:Number = e.currentTarget.x;

    e.currentTarget.startDrag(false,new Rectangle(-xpos,ypos,stage.stageWidth,0));
}


red.addEventListener(MouseEvent.MOUSE_UP, dropHandler);

function dropHandler(e:MouseEvent) {
    //trace("red up");
    e.currentTarget.stopDrag();
}
Run Code Online (Sandbox Code Playgroud)

dan*_*nii 14

很高兴Marty的解决方案适合你,虽然效率不高(MouseEvent.MOUSE_MOVE监听器是一个杀手).原始代码的问题在于,限制拖动边界的矩形必须相对于父坐标.此外,根据您的广场注册点的位置,如果您不希望其任何部分移出舞台,您可能必须考虑其宽度.

例如,如果您的红色方块直接位于舞台上,则其注册点位于其中心,并且您希望将拖动限制为舞台的整个x轴,这将起作用:

e.currentTarget.startDrag(
       false,
       new Rectangle(
          e.currentTarget.width/2,
          e.currentTarget.y,
          stage.stageWidth-e.currentTarget.width,
          0
       )
);
Run Code Online (Sandbox Code Playgroud)


Mar*_*rty 4

您可以尝试采用不同的方法来合并MouseEvent.MOUSE_MOVE,因为使用矩形作为动态边界会很棘手。

// define lock on y-axis
var LOCKY:Number = target.y;

// MouseEvent.MOUSE_MOVE
stage.addEventListener(MouseEvent.MOUSE_MOVE, _mouseMove);
function _mouseMove(e:MouseEvent):void
{
    if(target.y != LOCKY) target.y = LOCKY;
}

// dragging
target.addEventListener(MouseEvent.MOUSE_DOWN, _mouseDown);
function _mouseDown(e:MouseEvent):void
{
    target.startDrag();
    target.addEventListener(MouseEvent.MOUSE_UP, _mouseUp);
}

// dropping
function _mouseUp(e:MouseEvent):void
{
    target.stopDrag();
    target.removeEventListener(MouseEvent.MOUSE_UP, _mouseUp);
}
Run Code Online (Sandbox Code Playgroud)