Просмотр исходного кода

✨ Add setup callback to GameObjects

- The function is calles whenever the object is inserted into the tree, either via GameHandler or beeing added as child of an object already on the tree.
Pedro Schneider 2 лет назад
Родитель
Сommit
6369c1756e
3 измененных файлов с 32 добавлено и 8 удалено
  1. 18 1
      pandora/game_objects/GameObject.js
  2. 1 0
      pandora/handlers/GameHandler.js
  3. 13 7
      src/sketch.js

+ 18 - 1
pandora/game_objects/GameObject.js

@@ -9,9 +9,9 @@ class GameObject
         this.children = [];
         this.parented = false;
         this.parent = null;
+        this.isOnTree = false;
 
         GameHandler.instanceGameObject(this);
-
     }
 
     // Getters
@@ -46,6 +46,18 @@ class GameObject
         child.parent = this;
         child.parented = true;
         this.children.push(child);
+
+        if (this.isOnTree) child.setup();
+    }
+
+    setup()
+    {
+        this.isOnTree = true;
+        this._setup();
+        for (let i = 0; i < this.children.length; i++)
+        {
+            this.children[i].setup();
+        }
     }
 
     update(delta)
@@ -63,6 +75,11 @@ class GameObject
     }
 
     // Callbacks
+    _setup()
+    {
+
+    }
+
     _update(delta)
     {
 

+ 1 - 0
pandora/handlers/GameHandler.js

@@ -49,6 +49,7 @@ const GameHandler = {
     addRootObject: function(obj)
     {
         this.rootObjects.push(obj);
+        obj.setup();
     },
 
     update: function()

+ 13 - 7
src/sketch.js

@@ -1,6 +1,14 @@
 let test, test2;
 let monke;
 
+class TestObject extends Object2D
+{
+    _setup()
+    {
+        console.log(this.name);
+    }
+}
+
 function preload()
 {
     AssetHandler.loadTexture("monke", "/assets/textures/monke.png");
@@ -15,13 +23,11 @@ function setup()
     GameHandler.init();
     textFont(AssetHandler.getP5FontByName("Lato"));
 
-    monke = AssetHandler.getP5ImageByName("monke");
-    let sf = new SpriteFrames();
-    sf.addAnimation("monke", monke, 4, 4, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 1);
-    test2 = new AnimatedSprite2D("myAnimSprite", null, sf);
-    test2.play();
-    test2.setCurrentFPS(1);
-    GameHandler.addRootObject(test2);
+    test = new TestObject("myTest");
+    test.addChild(new TestObject("myTest2"));
+    GameHandler.addRootObject(test);
+    test.addChild(new TestObject("myTest3"))
+
 }
 
 function draw()