开发者

Slowndown stays after using and removing a lot of objects

开发者 https://www.devze.com 2023-03-21 03:32 出处:网络
I\'m stuck on this one. I\'m working on a game. I use this piece of code to create some eyecandy of debree falling. When an object is destroyed i spawn some rubble and let is fly over the screen. But.

I'm stuck on this one. I'm working on a game. I use this piece of code to create some eyecandy of debree falling. When an object is destroyed i spawn some rubble and let is fly over the screen. But... when i use this a lot, slowdown is there and even when all the objects are gone the开发者_JS百科 slowdown stays. The good old 50fps won't come back anymore :( Is there some kind of memoryleak in here i'm missing? Or is there a better way to do this?

public function destroyBlock(xPos,yPos,nrObjects) {

        for (var debree = 0; debree < nrObjects; debree++) {

            debreeObject = new mc_ground();
                debreeObject.x = xPos;
                debreeObject.y = yPos;
                debreeObject.scaleX = Math.random() * 0.3 + 0.1;
                debreeObject.scaleY = debreeObject.scaleX;
                debreeObject.speedX = Math.random()* 5 - 2.5;
                debreeObject.speedY = -Math.random() * 10 - 5;
            stageObject.addChild(debreeObject);

            debreeObject.addEventListener(Event.ENTER_FRAME, moveDebree);

        }

    }

    public function moveDebree(e:Event) {

        e.target.x += e.target.speedX;

        e.target.y += e.target.speedY;
        e.target.speedY += gravity;

        if (e.target.y > stageHeight) {

            e.target.removeEventListener(Event.ENTER_FRAME, moveDebree);
            e.target.parent.removeChild(e.target);
        }

    }


I tested your code and I can't see any performance loss. Are you sure this is not due to another part of your game?

Your code only on wonderfl


I'd recommend implementing an Object Pool for this type of activity. Because creating new mc_ground() objects will slow things down, especially in loops. Memory allocation and deallocation can be slow; and with garbage collection you could end up with a lot of things in memory at any given time.

Once your pool is created, then you can do something like debreeObject = myDebreePool.getFromPool() which will give you an object from the pool. Then after you call removeChild on that object, return it to the pool with something like myDebreePool.returnToPool(oldDebreeObject).

Depending on your needs, you may need the object pool to reset the state of the object when you return it. Otherwise it might remember old data that is no longer needed. However, given your sample code, I don't think that will be necessary.

If you correctly implement your object pool, you should see a significant performance gain in this type of scenario.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号