views:

289

answers:

1

how can i reference a display object's coordinates according to it's parent object or stage from within the class that creates the object?

essentially when i create a new sprite object from a custom class and add it to the display list, i'd like to include code within the custom class that limits the drag coordinates to the stage, or a section of the stage.

//Frame Script
import Swatch;

var test:Sprite = new Swatch();
addChild(test);

___________________

//Custom Class
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;

public class Swatch extends Sprite
    {
    public function Swatch()
        {
        init();
        }

    private function init():void
        {
        var swatchObject:Sprite = new Sprite();

        swatchObject.graphics.beginFill(0x0000FF, 1);
        swatchObject.graphics.drawRect(100, 100, 150, 150);
        swatchObject.graphics.endFill();

        swatchObject.addEventListener(MouseEvent.MOUSE_DOWN, onDrag, false, 0, true);
        swatchObject.addEventListener(MouseEvent.MOUSE_UP, onDrop, false, 0, true);

        this.addChild(swatchObject);
        }

    private function onDrag(evt:MouseEvent):void
        {
        evt.target.startDrag();
        //how to limit it's dragability to the Stage?

        }

    private function onDrop(evt:MouseEvent):void
        {
        evt.target.stopDrag();
        }
    }
}
+1  A: 

Hi there,

There is some native support for what you want to do. startDrag() accepts a rectangle as a parameter which restricts the region in which the drag can take place.

function startDrag(lockCenter:Boolean  = false, bounds:Rectangle  = null):void

Hope that helps,

Tyler.

Tyler Egeto
ok, so the second parameter of startDrag is what i'm looking for. how do i reference the stage from my object? i tried including flash.display.Stage, and then trace(this.parent.stage.stageWidth) but it gave an error.
TheDarkInI1978
as long as you are on the display list, you can just say "stage.stageWidth", you don't need to import it
Tyler Egeto
ok i figured it out. i had to create an event listener for ADDED_TO_STAGE in my constructor targeting the init() function, otherwise stage was null when i tried referencing it. forgot about that pitfall.
TheDarkInI1978