replit / kaboom

💥 JavaScript game library
https://kaboomjs.com
MIT License
2.66k stars 227 forks source link

Scene graph? #54

Closed oaklandgit closed 2 years ago

oaklandgit commented 3 years ago

Exciting framework! Is there a way to accomplish a scene graph: ie creating parent/child relationships between sprites? (For example, a rotating turret that is a child of a parent tank.)

slmjkdbtl commented 3 years ago

Right now there's none, game objects are stored in a flat array, but I'm also thinking about scene graph (a lot of design decisions to be made for that).

Right now you can keep a reference to "parent" objects, so like

const tank = add([...]);

for (let i = 0; i < 3; i++) {
    add([
        sprite(),
        "turret",
        {
            parent: tank,
        },
    ]);
};

action("turret", (t) => {
    if (t.parent.exists()) {
        // calculate position every frame
    }
});
oaklandgit commented 3 years ago

Thanks for the above suggestion.

Yes, I think frameworks like pixi.js do scene graphs well, so it might be worth looking at the APIs for that. (Or even building Kaboom atop Pixi?)

I think Kaboom's component approach beats anything else I've seen, and could maintain it's simplicity even if it had such nesting and grouping capability.

Perhaps it could be implemented as a component:

const tank = add([
   …
   children([turret, treads]),
  …
]);
slmjkdbtl commented 3 years ago

Scene graphs can actually be introduced without breaking change, but it's tempting to discard the concept of "scene" (scene()) and make them just a regular object with children, but then there's the problem that most kaboom functions are scene-scoped like add(), action(), keyPress(), etc. and where do we put those. We can put all of these under every object, but needs some testing to see if it'll actually be good, if anyone has any design suggestion welcome to post under. I'll try scene graph without discarding "scene" first and see how it goes

Thanks for the API suggestion that looks really clean!

triptych commented 3 years ago

Godot does away with the idea of a scene and an object. They are one in the same. So perhaps if you call an add() inside an object it makes it a child object with that scene graph capability you mentioned.

oaklandgit commented 3 years ago

I like that approach as well @triptych. In fact, I had tried that first hoping it would work!

oaklandgit commented 3 years ago

I took a stab at writing a component: https://replit.com/@LarryStone/KaboomParentChild (in scenes/main.js)

but it's only a partial solution, as it's unable to rotate or move the child relative to the parent. I thought I'd share here if anyone else is working on this problem.

slmjkdbtl commented 2 years ago

410

triptych commented 2 years ago

happy dance