johnfn / ts2gd

💥 Compile TypeScript to GDScript for Godot
200 stars 14 forks source link

Unable to pass values in constructor #101

Open QuentinWidlocher opened 1 year ago

QuentinWidlocher commented 1 year ago

Hi, maybe there's something I don't quite get but I cannot pass values in constructor when instancing new classes.

I've got a Player class and an abstract State class (a state machine).

// player.ts

import { State } from "src/player/state"

export class Player extends KinematicBody2D {
    private state: State = new State(this);

    protected _process(delta: float): void {
        this.state = this.state.execute(delta);
    }
}
// state.ts

import { Player } from "src/player/player";

export class State {
    protected readonly player: Player;

    constructor(player: Player) {
        this.player = player;
    }

    public execute(delta: float): State {
        return this;
    }
}

As you can see, in player.ts I'm creating an instance of IdleState (which is just an empty class extending State) and I pass the Player instance to it.

Shorthand property declaration does not work (constructor(protected readonly player: Player){}) but that's not a real problem

The generated code looks like this

# player.gd

extends KinematicBody2D
class_name Player

var State = load("res://compiled/player/state.gd")

var _Gravity: int = 500

var state = State.new(self)
func _process(delta: float):
  self.state = self.state.execute(delta)
# state.gd

class_name State

var player
func _ready(): 
  self.player = player
func execute(_delta: float):
   pass

As you can see, there is no new method and no parameters passed for player.

Is there something I missed ? Is it possible to do such thing with ts2gd ?