Wednesday, February 19, 2014

Flappy Bird Game Algorithm Part 1 - Gravity and flying



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)
the algorithms could be performed easily with few lines of codes without Box2D.

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
     }   

}

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

4 comments:

  1. Thanks for the tutorial. It would be nice if you enlarged a little bit the code font size.

    ReplyDelete
    Replies
    1. Hi, thanks for your interest. As requested, the font size of the code has been enlarged (but the comments are still small, so that it won't mess up with the codes).

      Delete
  2. "bloon" should be "objFlying"
    set gravity as int and give it 0.5 of value won't work. Should be Number.

    ReplyDelete
    Replies
    1. nice catch! It is a typo (i renamed those things when writing this post). Now I have edited it. Thanks.

      Delete