开发者

How to convert a Shape to MovieClip using ActionScript 3.0 only

import flash.display.Shape;
import flash.display.Graphics;


stage.addEventListener(Event.ENTER_FRAME, startAnim);

function startAnim(e:Event):void
{
    var shape1:Shape = new S开发者_如何学编程hape();
    shape1.graphics.beginFill(0x333333,1);
    shape1.graphics.drawRect(40,50,250,125);
    shape1.graphics.endFill();

    addChild(shape1); // this will add a shape of rectangle to stage

}

This is a very simple function creating a rectangle shape on stage. Ok but the problem is how can I convert this SHAPE to MOVIECLIP using ActionScript only so I can add Events to the same (shape1).


hmmm by using a MovieClip instead of a Shape. a MovieClip also has a Graphics object.

import flash.display.MovieClip ; 
//import flash.display.Graphics;//not needed

//stage.addEventListener(Event.ENTER_FRAME, startAnim); //remove enterframe

//function startAnim(e:Event):void { //no need for a handler
    var shape1:MovieClip = new MovieClip();
    shape1.graphics.beginFill(0x333333,1); 
    shape1.graphics.drawRect(40,50,250,125);     
    shape1.graphics.endFill();

    addChild(shape1); // this will add a MovieClip of rectangle to stage

    shape1.addEventListener(MouseEvent.MOUSE_DOWN, dragShape);

    function dragShape(E:MouseEvent)
    {
        shape1.startDrag()
    }

shape1.addEventListener(MouseEvent.MOUSE_UP, dropShape);

    function dropShape(E:MouseEvent)
    {
        shape1.stopDrag()
    }
//} no need for that either :)

beware that, as such, your function is called on ENTER_FRAME = 25 or more times per second, therefore you'll create and add a clip to stage 25 or more times per second + the reference is created locally, in the function, so you won't be able to access "shape1" from outside, once your object is created.


I don't think you can convert a Shape to a MovieClip. What you can do is to create a MovieClip class, and in the constructor generate the Shape object, and add it to the MovieClip.

public class Car extends MovieClip {
    private var shape1:Shape = new Shape();
    public function Car() {
        shape1.graphics.beginFill(0x333333,1);
        shape1.graphics.drawRect(40,50,250,125);
        shape1.graphics.endFill();
        addChild(shape1); // this will add a shape of rectangle to stage
    }
}

Shape has also events.

  • activate
  • added
  • addedToStage
  • deactivate
  • enterFrame
  • removed
  • removedFromStage
  • render

But since it doesn't extends from InteractiveObject, you can't handle input.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜