Yann Pellegrini
Yann Pellegrini

Reputation: 853

Haxe : Override `Dynamic` class attribute type

I'm using Haxe targeting javascript using the phaser game framework.

This framework has a Sprite class that can benefit of two different physics engines (but not both), either Arcade or P2.

I am extending it like this :

class Player extends Sprite {

    public function new() {
        super(/* ... */);
        game.physics.enable(this, Physics.ARCADE); // choose the engine to use on this sprite
        body.velocity.x = 500; // use the physics engine through the body attribute
    }

Because it's a javascript framework, the body attribute will either become a Arcade.Body or P2.Body depending on which physics engine you bind to the sprite.

So body is typed as Dynamic in the Sprite class definition and I would like to specify in my Player class whether it is a Arcade.Body or P2.Body so I can benefit of auto-completion and type safety.

My research so far :

Thanks in advance !

Upvotes: 1

Views: 138

Answers (1)

Yann Pellegrini
Yann Pellegrini

Reputation: 853

I worked around the issue using a class attribute that is a reference to body, but using cast.

var arcadeBody: Arcade.Body;

public function new() {
   //...
   this.arcadeBody = cast(this.body, Arcade.Body);
}

As @D-side pointed out, it is also possible to subclass Sprite from an ArcadeSprite class that is given a casted body attribute.

Upvotes: 1

Related Questions