Creating our player behaviour

Now that we have the basic world created, let's add in the ability for our plane to actually move and interact with our world. To start off with, let's make it actually move:

  1. From the Hierarchy tab, select the Plane object. Then, add a Rigid Body 2D component to it by selecting Component | Physics 2D | Rigidbody 2D.
  2. We want the object to always check for collision, so from the Inspector tab, change the Collision Detection property to Continuous.

    Now the plane will fall but it falls directly off screen. We want it to react to being hit on the ground, so let's add collision data to it. Generally, we want to use whatever collider is simple enough to get the job done without adding complexity, but in this case, I really want to get realistic looking colliders, so we will add in the most detailed collider for 2D, the Polygon Collider 2D.

  3. Next, add a Polygon Collider 2D component by selecting Component | Physics 2D | Polygon Collider 2D:
    Creating our player behaviour

    You may note the light green lines around the object. These are the parts of the object that will collide with other objects (if they have collision data as well).

  4. With that in mind, select the two groundGrass objects and add a Polygon Collider 2D to it as well:
    Creating our player behaviour

    The plane will now react and stop falling once it hits the ground. Now of course the plane still moves at this point, which we'll fix later on, but for right now, we will add in the ability for the plane to "jump."

  5. Now go to the Project tab and open up the Assets/Scripts folder and create a new C# Script to PlayerBehaviour.
  6. Double-click on the newly created script and use the following code for it:
    using UnityEngine;
    
    [RequireComponent(typeof(Rigidbody2D))]
    public class PlayerBehaviour : MonoBehaviour
    {
    
        [Tooltip("The force which is added when the player jumps")]
        public Vector2 jumpForce = new Vector2(0, 300);
    
        /// <summary>
        /// If we've been hit, we can no longer jump
        /// </summary>
        private bool beenHit;
    
        private Rigidbody2D rigidbody2D;
    
        // Use this for initialization
        void Start ()
        {
            beenHit = false;
            rigidbody2D = GetComponent<Rigidbody2D>();
        }
        
        // Will be called after all of the Update functions
        void LateUpdate ()
        {
            // Check if we should jump as long as we haven't been hit yet
            if ((Input.GetKeyUp("space") || Input.GetMouseButtonDown(0)) 
               && !beenHit)
            {
                // Reset velocity and then jump up
                rigidbody2D.velocity = Vector2.zero;
                rigidbody2D.AddForce(jumpForce);
            }
        }
    
        /// <summary>
        /// If we collide with any of the polygon colliders 
        /// then we crash
        /// </summary>
        /// <param name="other">Who we collided with</param>
        void OnCollisionEnter2D(Collision2D other)
        {
            // We have now been hit
            beenHit = true;
    
            // The animation should no longer play, so we can
            // set the speed to 0 or destroy it
            GetComponent<Animator>().speed = 0.0f;
        }
    }
  7. Save the script and go back to the Editor. Then, attach the PlayerBehaviour component to the Plane object:
    Creating our player behaviour

Stopping the game

Our plane will now jump up into the air, and upon hitting the ground, the plane will no longer animate. However, it would be better for the game to stop once we hit the ground, so let's add that in next. By using mouse input for jumping, this will also work by tapping on the phone:

  1. Flappy Bird also has its objects falling at a faster rate than normal gravity. To change this, we can go to Edit | Project Settings | Physics 2D and then from there, change the Gravity property's Y value to -20. The higher the number the faster the plane will fall. However, note that this will also affect the player's jump force. Tweak these values until you get something that feels right for you.
  2. Create a new C# Script named GameController. In it, use the following code:
    using UnityEngine;
    
    public class GameController : MonoBehaviour {
    
        [HideInInspector] // Hides var below
        /// <summary>
        /// Affects how fast objects with the
        /// RepeatingBackground script move.
        /// </summary>
        public static float speedModifier;
    
        // Use this for initialization
        void Start ()
        {
            speedModifier = 1.0f;
        }
    
    }
  3. Save the script and return to the Unity Editor. Create a new empty game object in the Hierarchy by selecting GameObject | Create Empty. Then, name it GameController and attach the GameController component to it. Finally, to make it easy to reference, drag the object to the top of the Hierarchy tab.
  4. Next, open up the PlayerBehaviour script and add the following bolded line of code to the OnCollisionEnter2D function:
        void OnCollisionEnter2D(Collision2D other)
        {
            // We have now been hit
            beenHit = true;
            GameController.speedModifier = 0;
    
    // The animation should no longer play, so we can set the speed        // to 0 or destroy it
            GetComponent<Animator>().speed = 0.0f;
        }
  5. Save that script and now open up the RepeatingBackground script, and from the FixedUpdate function, add the following change in bold:
    // Move the object a certain amount to the left (negative in the
    // x axis)
       pos.x -= scrollSpeed * Time.deltaTime *
                GameController.speedModifier;
    
  6. Save that script and return to the Unity editor; save your project and play the game:
    Stopping the game

At this point, whenever we fall, the game will now stop the background objects! Perfect.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset