0

I have a custom class that extends MovieClip. The idea is that it allows for storing extra variables and information about the MovieClip.

public class MapObject extends MovieClip
{
    private var cellX:int;
    private var cellY:int;

    public function MapObject()
    {
    }
 }

I have several MovieClips (.swf files) that I load at runtime. The problem is, how can I make these MovieClip objects actually become MapObject objects?

I've tried :

var mapObject:MapObject = myMovieClip as MapObject;

but it gives null

PS. I know you can add variables dynamically to MovieClips, but I don't really want to do that.

1 Answer 1

2

You can't change the class hierarchy without changing the code. You would have to go in each class definitions to change the parent class to MapObject instead of MovieClip.

There is an easy and clean solution which consists in using a decorator:

public class MapObject {

    private var mc:MovieClip;
    private var cellX:int;
    private var cellY:int;

    public class MapObject(mc:MovieClip) {
        this.mc = mc;
    }

    public function get movieClip():MovieClip {
        return mc;
    }
}
...

var wrapper:MapObject = new MapObject(new MyMovieClip());
...

container.addChild(wrapper.movieClip);

It's a wrapper that takes an instance of another class (in your case MovieClip) to add functionality. It's very powerful because you don't have to go and change each of your subclasses any time you change MapObject. This principle is called composition over inheritance.

In your case, all methods and properties of MovieClip are public so you would just write mc.play() instead of this.play().

See the details about the Decorator design pattern.

Sign up to request clarification or add additional context in comments.

2 Comments

However, you can't get a reference to the information in the wrapper by looking at the instance on the stage. So another solution is to have the mc use a base class that implements an interface that has a property pointing to a separate object with the cellX and cellY, or use a dictionary to look up the wrapper based on the movieclip.
Yes, I see your point. There is your solution or storing all wrappers - although it might become inefficient because it sort of duplicates what the display list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.