How do I detect collision detection in flash AS3?

2019-05-15 07:18发布

问题:

I wanted to create a maze in flash AS3, with the user guiding the character. I tried using this (below) but this will require me to make all the maze walls individual and setting collision detection to each one. Is there an easier way of accomplishing the same thing?

monkey.addEventListener( Event.ENTER_FRAME, handleCollision)

function handleCollision( e:Event ):void
{
    if(monkey.hitTestObject(wall))
       {
           trace("HIT");
       }
       else
       {
           trace("MISS");
       }
}

回答1:

You can use the Collision Detection Kit : https://code.google.com/p/collisiondetectionkit/



回答2:

One way you could do this, is to use hitTestPoint() method to test if any of the corners have hit your wall.

hitTestPoint() tests only a single location to see if that point collides with an object. This is how you could test the top left corner of your monkey to see if it's touching the wall :

// I am assuming that x,y is the top left corner of your monkey

if (wall.hitTestPoint(monkey.x, monkey.y, true))
{
   // top left collided with wall
{

So you could do the same for all corners, or if you want, you can determine any collision points you want to check for the monkey.

Depending on your level of precision, this method might work just fine for your needs. But if you want pixel perfect collision, you can check out this link :

http://www.freeactionscript.com/2011/08/as3-pixel-perfect-collision-detection/



回答3:

Why would it mean individual walls?? Have you tried drawing your maze shape/walls and selecting them all at once, right-click to convert selection to a movieclip giving preferred name. Then also give it instance name "wall". Now try to run it and your handleCollision function should work.

Or try changing from hitTestObject to hitTestPoint in your collision check...

function handleCollision(e:Event):void
{ 
 if (wall.hitTestPoint (monkey.x, monkey.y, false)) 
    { trace("HIT"); } 
else 
    { trace("MISS"); } 
}

Also check this article for more clarification..
http://www.actionscriptmoron.com/AS3Tutorials/hittest-hittestpoint/