2

I need to move a sprite only vertically on mouse move. How do I implement it with as3?

Thanks

Nava Carmon
  • 4,523
  • 3
  • 40
  • 74

3 Answers3

1
addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(e:MouseEvent):void{
    mySprite.y += amount;
}
danjp
  • 717
  • 1
  • 5
  • 20
1

Flash version

var s:Sprite = new Sprite();
s.x = 20;
s.graphics.beginFill(0xFF0000);
s.graphics.drawRect(0,0,20,20);
addChild(s);

stage.addEventListener(MouseEvent.MOUSE_MOVE,moveSprite);

function moveSprite(e:MouseEvent):void
{
    s.y = e.localY;
}

Flex version

<mx:Canvas width="100" height="100">
            <mx:mouseMove>
                    <![CDATA[
                        s.y = event.localY;
                    ]]>
                </mx:mouseMove>
            <mx:Canvas id="s" backgroundColor="#ff0000" width="20" height="20"/>
        </mx:Canvas>

Each of these you can paste in and will do what you said. it will create a 20x20 red box that is vertically the same as the mouse but fixed horizontally. The flex version your mouse has to be within the containing Canvas.

JD Isaacks
  • 56,088
  • 93
  • 276
  • 422
0

Ok, dragging is a little more complicated. You need to define a rectangle for the bounds of the dragging. If you want to just drag along one axis then you make the rectangle have a width of 0. In this example I've restricted the amount of scrolling and and down to different numbers that you can change below.

import flash.events.MouseEvent;
import flash.geom.Rectangle;

mySprite.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);

function mouseDownHandler(event:MouseEvent):void{
    stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
    var scrollUpAmount:int = 10;
    var scrollDownAmount:int = 200;
    var boundsRect:Rectangle = new Rectangle(mySprite.x,mySprite.y-scrollUpAmount,0,mySprite.y+scrollDownAmount);
    mySprite.startDrag(false, boundsRect);
}

function mouseUpHandler(event:MouseEvent):void{
    stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
    mySprite.stopDrag();
}
danjp
  • 717
  • 1
  • 5
  • 20
  • This example is restricted to vertical dragging only as I explained above. If you want to just drag along one axis (e.g. vertical) then you make the bounds rectangle have a width of 0. – danjp Mar 12 '10 at 09:39