Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

actionscript 3 - AS3 How to startdrag only on x-axis?

I have a red square that I want to drag only on the x-axis. I've worked out a simple script, which theoretically should work, but it's not behaving properly. It's a bit hard to explain..the square keeps starting at the wrong position and the stage position seems to be changing so sometimes you can't drag the square all the way to the right...

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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Glad Marty's solution worked for you, although it is not too efficient (that MouseEvent.MOUSE_MOVE listener is a killer). The problem with your original code was that the rectangle in which you limit the dragging boundaries must be relative to the parent's coordinates. Also, depending on where you have the registration point of your square, you might have to take its width into account, if you don't want any part of it to move out of the stage.

For example, if your red square is directly on the stage, its registration point is located on its centre, and you want to limit the dragging to the whole x-axis of the stage, this will work:

e.currentTarget.startDrag(
       false,
       new Rectangle(
          e.currentTarget.width/2,
          e.currentTarget.y,
          stage.stageWidth-e.currentTarget.width,
          0
       )
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...