Jump to content

Array length, Splice and problem with FOR


Phempt
 Share

Recommended Posts

Hi guys,

 

I'm trying to optimize my game removing unused array objects.

 

This code  decrease the "Y" position of each array's objects, if y is minor than "-150", it removes the element.

for (var a=0; a < testArray.length; a++) {                 if(testArray[a] != 'unload'){                 if(testArray[a].position.y > '-150' ){                    bonuSpeed = 130 + (5 * timerSpeed);                    speedRandom = Math.floor(Math.random() * 280) + bonuSpeed;                    testArray[a].position.y -= speedRandom * game.system.delta; // move sprite using delta time                 } else {                    //alert(testArray.length);	            testArray[a].remove();                    testArray[a] = 'unload';                 }                 }            }

Unfortunately, "testArray[a].remove();", doesn't work as expected so my first optimization was to change the value of testArray[a] with:

testArray[a] = 'unload';

So I can check if the element is equal to "unload" and skip the y variation.

 

This is quite good, but when the array length is major than 500 some graphic problem arrives (like fps drop).

So I tried to remove the unused testArray[a] with a function:

function removeByIndex(arr, index) {                 //alert(testArray.length);                 arr.splice(index, 1);                 //alert(testArray.length);}                             for (var a=0; a < testArray.length; a++) {                 if(testArray[a] != 'unload'){                 if(testArray[a].position.y > '-150' ){                    bonuSpeed = 130 + (5 * timerSpeed);                    speedRandom = Math.floor(Math.random() * 280) + bonuSpeed;                    testArray[a].position.y -= speedRandom * game.system.delta; // move sprite using delta time                 } else {                    //alert(testArray.length);                    	            testArray[a].remove();                    removeByIndex(testArray, a);                                     }                 }            }

and partially works, the testArray length decreases but the game freezes.

 

I think the problem is that the "For" checks the testArray's length, and I change this length during the cycle.

 

Can anyone help me with this problem? :)

 

Thank you ^^

Link to comment
Share on other sites

Have you tried to debug with the console? (I notice that you use alert() to get feedback about your code).

 

Run the code in Chrome, hit F12 and select the console tab. You will probably see an error.

You also can add breakpoints in the code tab and follow your code line by line with F10.

 

Is there an error visible in the console?

Link to comment
Share on other sites

unortunately I have little to no experience with either. I made a small testing script that runs fine over here and is able to remove a sprite from the array entirely. Perhaps it is any help to you a bit:

game.module(    'game.main').body(function() {	game.addAsset('panda.png');		game.createScene('Main', {	    backgroundColor: 0xb9bec7,		    init: function() {						var arr=[];						for(var i=0; i<5; i++){				var sprite = new game.Sprite('panda.png', 30+i*100,100);				this.stage.addChild(sprite);				arr.push(sprite);			}						//Now remove an entry from the array			//(You can ajust the number you want to remove from the array)			var num=1;			arr[num].remove(); //Removes the sprite from the visualDisplayContainer game.scene.stage		    arr.splice(num, 1); //remove the last refference to the sprite so now it will be dealt with by the automatic javascript garbage disposal  		    console.log(arr.length);// 4 	    }	});});

If you want you could try this code snippet in the panda fiddler (http://vermeire.home.xs4all.nl/panda/index.html). Just open a random example and copy this code in the editor. I thing it would be wise to find a way to debug your code on your own system because it will make your live a lot easier. :)

Link to comment
Share on other sites

Why replace slow running code with slower code? (a note about the 2nd version of your code: if you remove the a-th element of the array using splice() then you need to test the new a-th element in the next pass through the loop not the (a+1)-th element - this does not fix the bug you have noted but rather one you haven't noted yet)

How does something like the following run?

var speedRandom=0;for (var i=testArray.length-1; i>=0; --i) {  if (testArray[i]!==null) {    if (testArray[i].position.y > -150 /*should NOT be a string literal*/ ) {      speedRandom = (Math.random() * 280)|0 + 130 + 5*timerSpeed;      testArray[i].position.y -= speedRandom * game.system.delta; // move sprite using delta time    }    if (testArray[i].position.y <= -150 /*should NOT be a string literal*/ ) {      testArray[i].remove();      testArray[i]=null;    }  }}
Edit: And I agree with Stephan that you should profile/debugger before trying to optimise/debug further. Not knowing how to do this using the tools you have chosen to use isn't a great excuse :(

note: Should you find that sprite creation/garbage collection is slowing you down, you might want to avoid doing anything but calling remove() on the sprite and subclass sprite to have an alive property or use a separate array to track this, so that when you need to use the sprite again you can just change it's properties and set it to alive again

Link to comment
Share on other sites

I copied my www folder to a local webserver, I tried to run the game and still freeze, without errors.

 

I noticed that in both case (Xcode / Webserver) timeout functions continue to work instead of animation.

 

 

 

--- Edit ---

The game that I'm trying to optimize, is my first panda.js project and, of course, has a lot of errors. I created this game on XCode cause I'll publish it on the AppStore, and when I start to develop all is went pretty good, it's not an excuse as you said, it's simply a n00b error.
 
Fortunately, my 2 new projects are developed on a local web server, this will probably help me with this kind of problem
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...