Sunday, March 27, 2011

Improved Collision Detection

Improved Collision Detection:

Tutorial written by Leo “130x” Cederwall – leo.cederwall [at] gmail.com and edited by Niklas Mårdby (marten@work).

[ edit: My students are working hard on writing tutorials for the add-ons they have coded to the Spawn Engine. Over the next few weeks these tutorials will appear here. //Niklas ]

As you will have noticed, the Spawn Engine uses the hitTestObject which isn’t completely satisfactory when checking collisions between objects in the game. We need an improved collision detection. Let’s start with importing a necessary library. Write at the top of the package where the other imports are.

import flash.geom.Rectangle;

Lets also define a new variable which is the Collision object we will use when checking collisions.

private var collisiondetection:Collision=new Collision();

As you see we are going to use a Collision class. More about this at the end of the tutorial.

Now we need to change a few things in checkBulletEnemyCollissions and checkPickups. We need to replace hitTestObject and use a new function checkCollision instead.

Change ”if ( player.hitTestObject ( enemies[i ] ) )” to ”if ( checkCollision (player, enemies[i] ) )” and ”if ( player.hitTestObject ( pickups[i ] ) )” to ”if ( checkCollision (player, pickups[i] ) )”.

Last thing is to define the checkCollision function by writing:

function checkCollision(target1_mc:MovieClip, target2_mc:MovieClip):Boolean
{
var collisionRect:Rectangle = collisiondetection.getCollision (target1_mc,target2_mc);
if (collisionRect != null && collisionRect.width > 0 && collisionRect.height > 0)
{
return true;
}
else
{
return false;
}
}

[edit: As you see this function has two parameters and returns a Boolean. The two parameters are two MovieClip objects that we call target1_mc and target2_mc. These two could be a bullet and the player or any two movieclips you want to check if they collide. The first thing we do in the function is to create a Rectangle and to set the size of it we use the Collision class function getCollision. Now if the two movieclips are overlapping then the rectangle will have a width and height. If so, return the value true to checkBulletEnemyCollissions or where you called checkCollision from. //Niklas ]

And then also put the Collision.as file in your flash projects directory. The code for that file is below. Credits to Frederik Humblet och Grant Skinner for their work! [...]

No comments:

Post a Comment