Normally, to create the games involving Physics (eg: gravity), the use of Physics Engine such as Box2D would be a boost for complicated run-time computations. However, in the Flappy Bird game, since the only requirements are to:
- Make the bird fly upwards while touching
- Make the bird fall while not flying (with gravity)
Here, to remind, I am using AS3, Starling Framework and a latest version of Adobe AIR (4.0).
First, I am taking the advantage of Event.ENTER_FRAME to allow the flying object to animate/fly on each frame. In the onEnterFrame function, a gravity is implemented. At the same time, we allow the player to touch any space on the device to activate a jump.
private const UPWARD_SPEED:int = 5;
private const MAX_FLOOR:int = 800; //an indication that it hits the ground
private const GRAVITY:Number = 0.5;
private var objFlying:FlyingObject = new FlyingObject();//and addChild
private var speed:Number = 0;
private var isJump:Boolean = false;
private function onEnterFrame(e:EnterFrameEvent):void
{
if(isJump)
{
speed = -UPWARD_SPEED; //negative relative to the normal gravity
isJump = false; //once a jump is activated, we disable the flag
}
speed += (GRAVITY); //physics ya, the speed is affected by gravity
objFlying.y += speed;
if(objFlying.y > MAX_FLOOR) //if it hits the wall
{
speed = 0;
objFlying.y = MAX_FLOOR;
}
}
private function onTouch(e:TouchEvent):void
{
...
var touch:Touch = e.getTouch(stage);
if(touch.phase == TouchPhase.BEGAN)
{
isJump = true; //a touch enables a slight jump
}
}
private const MAX_FLOOR:int = 800; //an indication that it hits the ground
private const GRAVITY:Number = 0.5;
private var objFlying:FlyingObject = new FlyingObject();//and addChild
private var speed:Number = 0;
private var isJump:Boolean = false;
private function onEnterFrame(e:EnterFrameEvent):void
{
if(isJump)
{
speed = -UPWARD_SPEED; //negative relative to the normal gravity
isJump = false; //once a jump is activated, we disable the flag
}
speed += (GRAVITY); //physics ya, the speed is affected by gravity
objFlying.y += speed;
if(objFlying.y > MAX_FLOOR) //if it hits the wall
{
speed = 0;
objFlying.y = MAX_FLOOR;
}
}
private function onTouch(e:TouchEvent):void
{
...
var touch:Touch = e.getTouch(stage);
if(touch.phase == TouchPhase.BEGAN)
{
isJump = true; //a touch enables a slight jump
}
}
Note that the upward speed, gravity and the floor location are tunable according to your needs. With the Event.ENTER_FRAME, the animation is an easy job.
Next: Flappy Bird Game Algorithm Part 2 - Background Movement