PDA

View Full Version : Collision against multiple move clips in an array - advice needed!



Tennoken
February 16th, 2009, 11:56 PM
Hi everyone!

This is my first post to the boards, so be gentle :)

I'm writing a small game that involves a projectile move clip checking for collision against multiple target movie clips using an array. The scene is set to 800 x 600 @ 30 fps.

My issue is my fps dropping rapidly if there are multiple projectiles in flight: there are currently anywhere from 250 - 750 target MCs (20 x 20 pixels) and 3 to 6 projectile MCs (10 x 10 pixels) in action at any given time.

The target MCs are all part of class that .push into an array onLoad:


function onLoad()
{
_root.targetArray.push(this);
_root.DEBUG_potentialTargets++; // tracking total number of targets
}

And have one function:



function destroyMe()
{

for(var i in _root.terrainArray)
{
if(_root.terrainArray[i] == this)
{
_root.terrainArray.splice(i,1);
_root.DEBUG_potentialTargets--;
}
}
this.removeMovieClip();
}


The projectile MC is checking every frame for a collision with anything in the root.targetArray with:



function onEnterFrame()
{

// CHECK the targetArray for collision
for(var i in _root.targetArray)
{
if(this.hitTest(_root.target[i]))
{
_root.targetArray[i].destroyMe();
// and tell the target to remove itself
}
}
}


I'm very much an amateur coder - is there any way to optimize collision detection against such a large number of potential targets and still keep a decent framerate?

justkevin
February 17th, 2009, 01:29 AM
First, your destroy function is inefficient. Have it mark the target as destroyed by setting an "isDead" boolean variable. When you iterate over the array with your onEnterFrame, check if the object.isDead at this point, and if so, splice it out.

Also, you would benefit greatly by adding some broad-phase collision detection:

One way to tackle this problem is by partitioning the environment into smaller areas or nodes. A simple and effective way to do this is divide your world into a grid of squares. If your world is limited to the 800x600 view, then you might make your grid a 40x30 grid of 20x20 squares. Each square contains an array of objects currently touching it. Each object contains an array of squares it touches. Every time an object moves, it needs to recalculate the nodes it touches, tell the nodes it left that it's no longer in them, and the nodes it enters to add it to their object list.

This adds an extra layer of complexity and overhead to your game, but the payoff is your collision detection only needs to check a very small number of objects for a collision.