如何在轴(x 和 y)中拖动对象而不是在 as3 中沿对角线拖动对象

How to drag objects in axis(both x and y) but not diagonally in as3

如果鼠标沿 x 轴拖动,则对象应沿 x 轴移动 如果鼠标在 y 轴上拖动,则对象应在 y 轴上移动 对象不应沿对角线移动

这是不可能的。当你的鼠标要沿对角线移动时,你会怎么做?另一种可能是这样的,你的物体沿着最快的轴移动:

var oldx:int;
var oldy:int;
var sx:int;
var sy:int;

function run(e:Event):void
{
    sx = Math.abs(mouseX - oldx);
    sy = Math.abs(mouseY - oldy);

    if (sx > sy) {
        c.x = mouseX;
    } else {
        c.y = mouseY;
    }

    oldx = mouseX;
    oldy = mouseY;
}

stage.addEventListener(Event.ENTER_FRAME, run);

其他解决方案

另一种方法是计算鼠标的角度:

var oldx:int;
var oldy:int;
var rd:Number;
var l1:Number = Math.PI / 4;
var l2:Number = 3 * Math.PI / 4;

function run2(e:Event):void
{
    rd = Math.atan2(mouseX - oldx, mouseY - oldy);

    if ((rd > l1 && rd < l2) || (rd < -l1 && rd > -l2)) {
        c.x = mouseX;
    } else {
        c.y = mouseY;
    }

    oldx = mouseX;
    oldy = mouseY;

}
stage.addEventListener(Event.ENTER_FRAME, run2);
import flash.geom.Rectangle;
import flash.events.MouseEvent;
var tempx:Number=0;
var tempy:Number=0;
var count:int=0;
stage.addEventListener(MouseEvent.MOUSE_UP,remov)
bl.addEventListener(MouseEvent.MOUSE_DOWN,func)
function func  (f:MouseEvent)
{
    tempx=Math.abs(stage.mouseX);
    tempy=Math.abs(stage.mouseY);
    stage.addEventListener(MouseEvent.MOUSE_MOVE,mov)
}
function mov(h:MouseEvent)
{
    count+=1;
    if (count==4)
    {
    count=0;
    var Xval:Number=tempx-stage.mouseX;
    var Yval:Number=tempy-stage.mouseY;
    if(Math.abs(Xval)>Math.abs(Yval))
    {
    bl.startDrag(false,new Rectangle(0,bl.y,stage.stageWidth,0))
    trace ("X dragg")
    trace(Xval+""+""+Yval)
    }
    else
    {

        trace ("YY drag")
        trace(Xval+""+""+Yval)
        bl.startDrag(false,new Rectangle(bl.x,0,0,stage.stageHeight))
    }
    stage.removeEventListener(MouseEvent.MOUSE_MOVE,mov)
    }
}
function remov(y:MouseEvent)
{
    bl.stopDrag();
}

bl是mc名字 这对我来说很好用....单独在 x 轴或 y 轴上移动....