Question

Hi I'm noticing that the following code is producing a noticeable chunk of lag when it is incorporated.

    public function impassable_collisions():void { //prevent player from moving through impassable mcs

        for each(var mc:MovieClip in impassable) {

        var bitmap = createBitmapClone(mc); //return clone of bitmap of mc, accounting for transformations

        var bounds:Rectangle = player.getRect(bitmap);
        var playerCenterX:Number = bounds.left + bounds.width * .5;
        var playerCenterY:Number = bounds.top + bounds.height * .5;

        //Test for a pixel perfect collision against a shape based on a point and radius, 
        //returns the angle of the hit or NaN if no hit.
        var hitAngle:Number = hitTestPointAngle(bitmap, playerCenterX, playerCenterY, player.height/2);

        if(!isNaN(hitAngle)){
            // move player away from object
            player.x -= int(Math.cos(hitAngle) * player.speed*timeDiff);
            player.y -= int(Math.sin(hitAngle) * player.speed*timeDiff);
        }
    }
}

So this function is called from another function which is called from an enterFrame listener. I'm looping through an array containing perhaps between 5-30 movieclips at any given time, the given mc will then be cloned to a bitmap and that bitmap will be used to test for collisions between itself and another bitmap (the "player"). I'm assuming that something rather inefficient is taking place and thus producing lag - more choppy-like movements when the "player" is moved. Does anyone have an idea what the problem is/solutions to it?

Sorry for the rather vague question title

thanks

Was it helpful?

Solution

Pixel Perfect collision detection is expensive. I can't say that is the only problem, but I can tell you it's expensive in terms of processing.

Creating a new bitmap each iteration in this loop is also expensive.

One thing you can try is to eliminate objects before doing the more intensive checking. For example a very quick distance check can eliminate the need to test for an object if they aren't within a certain distance.

if (distance <= threshold)
{
    // create the bitmap for the check
    // do the expensive pixel perfect collision check
}

Your goal is to eliminate objects that are obviously not close enough to collide.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top