Tuesday, July 5, 2011

Collision detection in flash

Collision detection is an essential part in games. It ensures that the game physics are relatively realistic, so that an object does not cut through other objects or hovers when it should fall. How well a game can detect collisions is an integral part of the believability and enjoyment of the game.

Here is a simple concept in flash to test the collision detection.

  • Create two objects in flash, here for demo say two rectangles with red and blue color.
  • Right click both objects and convert them to symbol giving them names red and blue.
  • If properties panel is off, go to window menu and turn it on.
  • Select the respect objects and under properties panel give the instance names to both, say red and blue (these are the names we will be using to identify the them in action scripts).
  • Right click red and actions, expert mode.
  • Type in the following scripts.

onClipEvent(enterFrame)
{
if(Key.isDown(Key.UP)){
_y=_y-5;
}
if(Key.isDown(Key.DOWN)){
_y=_y+5;
}
if(Key.isDown(Key.RIGHT)){
_x=_x+5;
}
if(Key.isDown(Key.LEFT)){
_x=_x-5;
}
if(_root.blue.hitTest(_root.red)){
_x=20;
_y=20;
}
}

The lines 15-18 of the above script is used to check if the blue block hits or collides red blocks and if the result is true, the red block changes its position to (20,20).

The source code is available at

No comments:

Post a Comment