chesnutcase
chesnutcase

Reputation: 522

AS3 - Get reference of instance who called a function

I have two classes, "player" and "Stickman", "player" extends "Stickman". The class "Stickman" contains functions that all characters will have in the game such as moving and handling animations (all use the same animations) while the "player" class contains player-exclusive actions. When I call an action from a player instance that is inherited from the "Stickman" base class, how do I correctly point (from the stickman base class) to that player instance that called the function?

For example, to handle running animations

Trigger code in player.as:

moveType("running");

moveType function in Stickman.as:

public function moveType(type:String):void{
    this.gotoAndPlay("running");
    trace("testing");
}

To start playing frame with frame label "running" inside the player object (which is an extend of Stickman). I know this doesn't work, so I would like to replace this with something that would point to the caller of the function (i.e. the player object).The trace statement still runs so there (should) be no problem with the linkage. Is there a way to do this without passing the childId of the player object?

Upvotes: 0

Views: 374

Answers (1)

Andrey Popov
Andrey Popov

Reputation: 7510

It's all about so called inheritance. Player IS actually a Stickman. So when you call moveType you are calling it ON Player object. If you don't have such function inside it, it looks up in the inheritance chain, and finds it inside Stickman.

Inheritance is one-directional. Which means that Player knows all methods of Stickman, but the opposite is not true - Stickman works only by itself and does not know who extended it and who not.

That said - you must use the Player class as a starting point and decide what to do from there on.

Long story short - you need to override the function from Stickman into Player and then decide what to do and what not. Example:

Stickman:

public function move(type:String):void {
    this.gotoAndPlay(type); // regular workflow for reach Stickman
}

Player:

override public function move(type:String):void {
    if (type == 'player_specific') {
        this.gotoAndPlay('frameAvailableOnlyForPlayerClip');
        // maybe something else, player specific, like play sound or smth else
    } else {
        super.move(type); // calls whatever is inside Stickman::move
    }
}

Remember - this is always the very same object that you are calling the function for. But you can decide if you want something specific (player case) or you want the very usual flow. super.move will call what's in the parent class.

Inheritance is very important and I cheer you for deciding to use it! With a little more practice you will master it!

Upvotes: 2

Related Questions