Part 4 – Create the pigs and the collision detection
Introduction
Here the 4th tutorial to learn how to create a physic based game like Angry Birds in Flash.
You can download the complete sources here: How_to_create_a_game_like_angry_birds_part4.zip
If you missed the first tutorial you can find it here: https://benoitfreslon.com/fr/tutorial-how-to-create-a-game-like-angry-birds-with-box2d-world-construction-kit-flash-part-1
In this tutorial we will create the the ennemies: the Pigs. We will detect the collision to destroy it.
[swf:https://benoitfreslon.com/wp-content/uploads/2013/04/main2.swf 800 400]
Create the Pig character
Create the Pig MovieClip:
- Insert > New Symbol
- Name: Pig
- Type: MovieClip
- Check export for ActionScript
- Class: Pig
- OK
Draw a beautiful green pig like this with this dimensions: 30×30
Or get my sprite:
The Pig class
Create the Pig class.
- New > File > ActionSript 3.0 class
- Class name: Pig
Copy and paste this code:
package { import flash.events.Event; import flash.utils.*; import flash.geom.*; import Box2DAS.*; import Box2DAS.Collision.*; import Box2DAS.Collision.Shapes.*; import Box2DAS.Common.*; import Box2DAS.Dynamics.*; import Box2DAS.Dynamics.Contacts.*; import Box2DAS.Dynamics.Joints.*; import cmodule.Box2D.*; import wck.*; import shapes.*; import misc.*; import extras.*; public class Pig extends Circle { /** Constructor method, called when the bird instance is created */ public function Pig() { // constructor code super(); } /** Called when the pig is added to stage by box2d */ override public function create():void { trace("pig created"); // Physic properties density = 10; friction = 1; type = "Dynamic"; reportBeginContact = true; reportEndContact = true; reportPostSolve = true; reportPreSolve = true; allowDragging = false; super.create(); // Start the collision detection in 1000ms. // Sometimes the collision is detected at start so I delayed the collection detection setTimeout(initCollision, 1000); } private function initCollision():void { // Init the collision handler listenWhileVisible(this, ContactEvent.POST_SOLVE, postSolveContactHandler, false, 0, true); } /** Set the physic shapes and the size */ override public function shapes():void { // 15 px of raduis circle(15); } /** Method called when this physic object collides */ private function postSolveContactHandler(e:ContactEvent):void { // Get the impulse the contact var impulse:b2ContactImpulse = e.impulses // Get the normal lenght of the contact var normalLength:Number = Math.sqrt((impulse.normalImpulse1 * impulse.normalImpulse1) + (impulse.normalImpulse2 * impulse.normalImpulse2)); trace("normalLength", normalLength); // Check if the contact is strong if (normalLength > 1) { // Remove the pig remove(); return; } } } }
Finally add pigs in the World MovieClip like this:
And test your level.
The tutorial is over. If you want more features and more tutorials about the Angry birds engine please post a comment :).
Have fun !