views:

86

answers:

3

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

Thanks

+1  A: 
addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(e:MouseEvent):void{
    mySprite.y += amount;
}
danjp
sorry, i asked about mouse click, while I need a mouse move actually. Click doesn't track mouse movement.
Nava Carmon
A: 

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
how do i restrict the movement to be vertical only? thanks
Nava Carmon
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
+1  A: 

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.

John Isaacks
Great, thank you!
Nava Carmon