Bläddra i källkod

✨ Add methods to game objects to free them from memory

- Add free public method to remove object from tree and destroy its children.
Pedro Schneider 3 år sedan
förälder
incheckning
0d1c7bbfb1

+ 32 - 0
pandora/game_objects/GameObject.js

@@ -31,6 +31,7 @@ class GameObject
         this.parented = false;
         this.parent = null;
         this.isOnTree = false;
+        this.isRoot = false;
 
         this.signals = [];
         this.initSignals();
@@ -105,6 +106,37 @@ class GameObject
         if (this.isOnTree) child.setup();
     }
 
+    removeChildById(id)
+    {
+        for (let i = 0; i < this.children.length; i++)
+        {
+            if (this.children[i].id == id)
+            {
+                this.children.splice(i, 1);
+                return;
+            }
+        }
+    }
+
+    free()
+    {
+        if (this.parented)
+            this.getParent().removeChildById(this.id);
+        else if (this.isRoot)
+            GameHandler.removeRootObjectById(this.id);
+
+        this.destroy();
+    }
+
+    destroy()
+    {
+        for (let i = 0; i < this.children.length; i++)
+            this.children[i].destroy();
+
+        for (var prop in this)
+            this[prop] = null;
+    }
+
     initSignals()
     {
         this._initSignals();

+ 13 - 1
pandora/game_objects/ui_objects/UIObject.js

@@ -149,8 +149,20 @@ class UIObject extends GameObject
         child.P5Element.parent(this.P5Element);
     }
 
+    destroy()
+    {
+        for (let i = 0; i < this.children.length; i++)
+            this.children[i].destroy();
+
+        if (this.P5Element)
+            this.P5Element.remove();
+
+        for (var prop in this)
+            this[prop] = null;
+    }
+
     // Callbacks
-    
+
 
     _onMousePressed()
     {

+ 10 - 0
pandora/handlers/GameHandler.js

@@ -92,9 +92,19 @@ const GameHandler = {
     addRootObject: function(obj)
     {
         this.rootObjects.push(obj);
+        obj.isRoot = true;
         obj.setup();
     },
 
+    removeRootObjectById: function(id)
+    {
+        for (let i = 0; i < this.rootObjects.length; i++)
+        {
+            if (this.rootObjects[i].id == id)
+                this.rootObjects.splice(i, 1);
+        }
+    },
+
     upframecount: 0,
     upframenum: 20,
     update: function()

+ 0 - 5
src/sketch.js

@@ -49,11 +49,6 @@ class TestButton extends Button
         this.setPosition(100, 200);
         this.setSize(150, 50);
     }
-
-    _onMousePressed()
-    {
-        this.emitSignal("buttonPressed", 1, 2, 3, 4);
-    }
 }
 
 function preload()