Simplest way to add a function to an object?

So, I’ve always been asking quite complex questions when I come around. The reason being, I come from more complex programming backgrounds, but I’ve began teaching a coding course, and CoSpaces is actually quite a lot more than my expectations. I’m really glad, but I feel kinda dumb that I can’t adapt my programming back to more basic levels.

So currently, I’ve been doing this so that my CoSpaces objects have special methods:

class SpecialDoor {
    doorItem: AnimatedItem;
    open: boolean;
    constructor(doorItem: AnimatedItem) {
        this.doorItem = doorItem;
    }
    public open() {
        this.open = true;
        this.doorItem.animation.play("Open");
    }
    public close() {
        this.open = false;
        this.doorItem.animation.play("Closed");
    }
};

let myDoor = new SpecialDoor(Scene.getItem('tsWJBKWt') as AnimatedItem);

I don’t know about you, but this actually seems a bit overkill for the behaviour I’m looking for. The goal is simply to have a door that tracks when it is open and when it is closed, which can then be grabbed by other code in my Scene. I definitely don’t want to make something too complex for what I want to do.

Anybody have any ideas for a way I can simplify this?

Hi @24dlau,

This is the standard object-orientated approach and is perfectly fine - it gives you the ability to easily turn any door into a special door (although there’s no error-checking here to see if it is a door or has these animations).

A simplified JS approach might be to create a function that toggles the state of door, like:

function toggleDoor( myDoor ){
    if (myDoor.animation.name == 'Open'){
        myDoor.animation.play('Closed');
    } else {
        myDoor.animation.play('Open');
    }
}

toggleDoor(Scene.getItem('tsWJBKWt') as AnimatedItem);

Again, there’s no error-checking in this, but if you know which objects it’s being applied to, then there’s less need.

This is my go-to for best practice when creating in TS:

Hope that helps! Let me know if you have any further questions around this. If this solves your problem, please mark this post as the Solution.

Many thanks,
Geoff @ TechLeap

2 Likes

Well then, I guess I will go ahead with what I have. It can get a little hard to keep track of all my classes and objects: I guess this is just time for me to give those mental muscles a good workout.

Thanks so much for the answer :+1: