In Flappy Bird, the player taps on the screen to force the bird to flap. This flapping motion applies an upward force to the bird. The player uses this game mechanic to avoid obstacles. In this blog post, I will talk about how we can achieve this effect in Unity3D.
To start off, I created a player game object that will contain the necessary components. In this game, the player need to have the following functionality:
- Drawn onto the screen.
- Perform a jump when the user taps
- Animate i.e. Flapping
- Collision Detection
Displaying the bird is very simple. As part of the native 2D functionality, Unity has provided a component called Sprite Renderer. This component allow us to determine the current sprite that is being drawn as well as the layer that our bird will be drawn on. Layering will be discussed later and will be important once we add a background and UI. The Sprite Renderer contains a Sprite property which contains a null reference. Simply drag the bird sprite in the project onto this field and the player game object should display the bird.
To perform a jump when the user taps, I decided to use Unity's PhysX system to drive the bird's motion. To do this I add a Rigid Body Component onto the player. Then I created a PlayerController.cs script. The code to tap is the following:
To make the game values easier to tweak, I decided to add a gravity and tapForce variable that is visible in the inspector. This gives me better control on how high the bird should jump and how powerful gravity will be. The Rigidbody variable is to simply cache off the component so we can be more efficient. The tapDir variable defines the direction the bird will move when we tap. Lastly, through playtesting, I found out I needed a tapped variable that disabled gravity for the one frame that the player tapped. Line 33 through 39 shows the code necessary to detect a mouse click and then apply a force afterwards. You'll notice on line 35 that the rigidbody is reset when the user taps and before we apply a force to the bird. This is because at that point in time, forces from a previous frame such as the previous tap or gravity is still affecting the rigidbody and is making the rigidbody move in some direction. Therefore, to give a consistent jump effect, I need to clear the velocity prior to adding a force. When I do apply a force, I apply it in ForceMode.Impulse which simulates an instantaneous force. Along with setting the gravity to zero on that frame, it helps give a nice jump quick jump effect..
You may have noticed that I am simply using a Rigidbody as opposed to a Rigidbody2d which is included in Unity's new native 2D API. I initially tried using that component but found its option lacking. The main issue was that the Rigidbody2d provided no way of applying an Impulse type force. This made the jump effect feel slow as it expected a force to be applied over time.
I will talk about Animation in the next blog.
No comments:
Post a Comment