Create an Angry Birds style game in 5 minutes with Unity!
In order to create this type of game, we will need to implement 2D physics…something that Unity excels at.
- SpriteRenderer
- Collider2D
- RigidBody2D
- SpringJoint2D
- Script
The best way to start this project is to create one using Unity’s 2D template:
Otherwise, you may have to import the 2D sprite package from Unity’s package manager:
In order to simulate the touchscreen, we can import the device simulator via the preview package in advanced settings:
In order to simulate the mouse click as a finger press, we’ll need to do that through Window > Analysis > Input Debugger > Options > Simulate Touch Input From Mouse or Pen:
With the basics out of the way, let’s create our Player. We’ll use a simple circle sprite to represent our player:
In order to use physics, we’ll need a collider and a rigidbody (both will be the 2D versions):
Next, let’s add a rectangle for the ground. Scale it so that it covers the width of the screen. We also need to add a box collider 2D to the ground as well. While we are at it, let’s change the colors of both the player and the ground:
If we play the game now, we notice that the player falls to the ground with no bounce:
We can make this more realistic looking by creating a physics material 2D, changing the “bounciness” and adding the newly created material to the material slots:
In order to give the player the slingshot momentum, we can add a spring joint 2D component. We also need to add something to attach the spring joint to. Create a second 2D sprite, add a rigidbody and make sure it is set to “static”:
It’s time for some scripting. Create a new script called “Player” and attach it to the player. Let’s start by getting references to our components including the Main Camera and the Input System:
In order to drag the player, we can access that with Unity’s TouchScreen class. Let’s create a method for this that will be called in Update called DetectTouch. This will set the rigidbody to kinematic (allowing us to drag it) and it will convert the screen position in pixels to world space:
At this point, we can drag the player around the screen. In order to get the “elastic” reaction, we need to set the rigidbody back to dynamic after we release the player. That will be done from our LaunchBall() method:
We also need to disable the “Auto Configure Distance” in our SpringJoint:
At this point, we can drag the player, release and watch it bounce back and forth:
We just need to release the player once it’s position reaches the pivot position by comparing the horizontal values:
All that is left is to add some blocks to knock over! Just make sure to add the Box Collider 2D and Rigidbody 2D:
To expand on this, you can add a line renderer and attach 3 points; 1 to the pivot infront of the player, the middle point to the player and the 3rd point to the pivot behind the player. Then just set the middle point to the position of the pivot once the ball is released.