Search code examples
actionscript-3flashcollision-detectionmovieclip

As3 collision detection with a movieclip array?


Ok my xChar.character is my character movieclip and xMap the instance of the class building the map.

From the xMap i add movieclip sliced from a image using variable which is inside a function. I do addChild(cell1); for every object displayed on my map which is in a array.

But the only public variable from the xMap class i can use is slicedObject which is a linear array holding all the sliced image from a movieclip (this image contain all my object that i want the character to collide with).

So i tryed to do this:

package as3
{
public class wl_CollisionDetection
{
    var tChar;
    var tMap;
    public var _CheckCollision:Boolean;
    public function wl_CollisionDetection(xChar:wl_Character,xMap:wl_MapBuilder)
    {
        tChar = xChar;
        tMap = xMap;
    }
    public function CheckCollision()
    {
        _CheckCollision = false;
        if (tChar.character.hitTestObject(tMap.sliceObject[70]))
        {
            _CheckCollision = true;
            trace("Collision detected!");
            return;
        }
        else
        {
            _CheckCollision = false;
            trace("No collision");
            return;
        }
        _CheckCollision = false;
    }
}
}

All i get is the no collision trace.

if (tChar.character.hitTestObject(tMap.sliceObject[70]))

What i’m doing wrong ?


Solution

  • Maybe your problem comes from the fact that you're testing collision with only one object from the map.

    Try using a loop:

    package as3
    {
    public class wl_CollisionDetection
    {
        private var tChar:wl_Character;
        private var tMap:wl_MapBuilder;
    
        public function wl_CollisionDetection(xChar:wl_Character,xMap:wl_MapBuilder)
        {
            tChar = xChar;
            tMap = xMap;
        }
    
        public function checkCollision():Boolean
        {
            var numObject:int = tMap.sliceObject.length;
            for (var i:int = 0; i < numObject; i++)
            {
                if (tChar.character.hitTestObject(tMap.sliceObject[i]))
                {
                    trace("Collision detected!");
                    return true;
                }
            }
            trace("No collision");
            return false;
        }
    }
    }