» » How to quickly write an Android game with Unity

How to quickly write an Android game with Unity

At the present time, anyone can become a successful mobile game or application developer without making a titanic effort. An example of such a case is Dong Nguyen, who developed Flappy Bird. The game did not have any complex mechanics or graphics, but this did not prevent it from becoming popular and bringing its creator fifty thousand dollars a day. However, there was nothing remarkable about the game. All it took to be successful was to be in the right place at the right time and a little bit of luck. Similar things can happen today, you just need the right idea.

To demonstrate how easy it is to write something like this, today we will write our own Flappy Bird using Unity in just 10 minutes.

How to quickly write an Android game with Unity

game character
First create a new project and make sure the 2D option is selected.

How to quickly write an Android game with Unity

Load your bird sprite into the scene. Don't forget to turn on your imagination!

Then adjust the size of the sprite to your liking by dragging it around the corner in the direction you want. The sprite should be visible in the hierarchy window ( hierarchy) on the left. All objects in the scene are visible in it, and at the moment there should be only two of them: a camera and a bird.

Drag the camera to the bird and release. The camera should be under the bird, which means that the camera is now the "child" of the bird. Now the camera position will be fixed relative to the bird. If the bird moves forward, then the camera does the same.



Select the bird again in the scene or in the hierarchy window. You will see a list of options and attributes on the right side of the window called Inspector. Here you can manage various variables associated with a particular object.

Now click on Add Component. Select Physics2D > Rigidbody2Dis a ready-made set of instructions for applying gravity to our character. Click on Constraintsin this panel and then select freeze rotation Z. This will prevent the bird from rotating around with the camera.

In the same way, add a Polygon Collider, which tells Unity where the character's bounds are. Click Playand see how the sprite, along with the camera, endlessly falls down.



So far everything is going well!

Now it's time to start flying the character, since it will not be difficult.

First you need to create a C# script. Create a folder for it (right click somewhere in assetsand create a "Scripts" folder), right click and select Create > C# Script.

Let's call it "Character". Double click on it to open it in your IDE, be it MonoDevelop or Visual Studio. Then add the following code:

public class Character : MonoBehaviour {

    public Rigidbody2D rb;
    public float moveSpeed;
    public float flapHeight;

    // Это нужно для инициализации
    void Start () {
        rb = GetComponent();
    }
      

    // Update called once per frame
    void Update () {
        rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
        if (Input.GetMouseButtonDown(0))
        {
            rb.velocity = new Vector2(rb.velocity.x, flapHeight);
        }

        if (transform.position.y > 18 || transform.position.y < -19)
        {
            Death();
        }

    }

    public void Death()
    {
        rb.velocity = Vector3.zero;
        transform.position = new Vector2(0, 0);
    }

}


This code does two things. It makes the character move forward at a speed that we define in the inspector and gives the impression of a bird in flight. The method Update()is called repeatedly throughout the game, so whatever you put here will run continuously. In this case, we are adding some speed to our object. The variable rbis a script RigidBody2Dthat we applied to our object earlier, so when we write rb.velocity, we are referring to the speed of the object.

A tap on the screen is interpreted by Unity as a mouse click if you are using a mobile device. After pressing, we force the character to rise up a little.

The variable moveSpeedwill be responsible for the speed of movement, and the variable will be responsible for flapHeightincreasing the height of the bird's flight after each press. Since these variables are declared as public, we can change them outside of the script.

The method Death()is also declared as public, which means that other objects and scripts can call it. This method simply returns the position of the character to the start. It will also be used every time the character flies too high or low. You will soon understand why it is declared as public. The line rb.velocity = Vector3.zero;is needed to remove the momentum - we don’t want the character to fall faster and faster after each death, right?

Now you can exit the IDE and add the script as a component to the character. To do this, select our bird and press Add Component > Scripts > Character. Now we can also define moveSpeedit flapHeightin the inspector (that's publicwhat -variables are for). Let's assign the values ​​3 and 5 to the variables, respectively.

And one more thing: in the inspector, you need to add a tag to the character. To do this, click where it says Tag: Untaggedand then select Playerfrom the drop-down list.

Obstacles

Now let's add obstacles: pipes. Someone finds mushrooms in the pipes, and someone finds his own death.

Drag the pipe sprite into the scene to where you want the first obstacle to be and name it pipe_up.

Now let's create a new script called Pipe:


public class Pipe : MonoBehaviour {

    private Character character;

    // start
    void Start () {
        character = FindObjectOfType();
    }

      
    // Update
    void Update () {
        if (character.transform.position.x - transform.position.x > 30)
        {

        }
    }

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "Player")
        {
            character.Death();  
        }
    }

}


Add this script to the pipe sprite in the same way as before. Thus, the pipe will return to the screen after leaving its left border. We haven't done anything here yet, but we'll get back to it.

The method OnCollisionEnter2D()is called every time the pipe interacts with the character. After that, the method created earlier is called Death(), returning the player to the starting point.

So, we have one pipe that will disappear from time to time and reappear at the other end of the screen. Hit her, you die.

inverted pipes
Right now we only have one pipe sprite. Let's add one more. To do this, right-click in the hierarchy window, click New 2D Object > Spriteand then select the sprite you want to use. It's even easier to just drag the file into the scene again.

Name this sprite pipe_down. In the Inspector, under Sprite Renderer, select the option Flip Yto flip the pipe upside down. Add the same RigidBody2D.



Now let's write a new C# script called PipeD. It will have similar code:

public class PipeD : MonoBehaviour {

    private Character character;

    // This is required for initialization.
    void Start()
    {
        character = FindObjectOfType();
    }

    // Update is called once per frame
    void Update()
    {
        if (character.transform.position.x - transform.position.x > 30)
        {
        }

    }

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "Player")
        {
            character.Death();
        }

    }

}


Prefaby

So, this code is enough for us to make the whole game. We could move the pipes to the right side of the screen every time they disappear, or copy and paste as many pipes as we'd like throughout the game.

If you go the first way, then making sure that the pipes are right after random generation, and it would be difficult to maintain a fair course of things. After the death of the character, they could appear in kilometers from the first pipe!

If you go the second way, then everything will end up with excessive memory consumption, with the resulting slowdown in the game, and limited replay value, because. everything stays in the same place every time.

Instead, let's use prefabs. In simple terms, we will turn our pipes into templates that we can then use to effectively create more pipes as desired. If there are programmers here, then consider the script as a Pipeclass, and the pipes as instances of this object.



To do this, create a new "Prefabs" folder. Then drag pipe_upand pipe_downfrom the hierarchy window to the folder.

Every time you drag an object from this folder into the scene, it will have the same properties, so you don't have to constantly add components. What's more, if you resize a component in a folder, it will affect all pipes in the game, and you won't have to resize each one individually.

As you can imagine, this will greatly save our resources. It also means that we can interact with objects from code. We can instantiate our pipes.

First, add this code to the conditional in Update() the script method Pipethat we left blank:


void Update () {
        if (character.transform.position.x - transform.position.x > 30)
        {

            float xRan = Random.Range(0, 10);
            float yRan = Random.Range(-5, 5);

            Instantiate(gameObject, new Vector2(character.transform.position.x + 15 + xRan, -10 + yRan), transform.rotation);
            Destroy(gameObject);

        }

    }


This is needed to instantiate our gameObject. The result is a new identical copy. In Unity, whenever you use the word gameObject, it refers to the object that the script is currently bound to - in our case, a pipe.

We re-generate our pipes in random variations to make it more fun.



But instead of doing the same in a script PipeD , we generate both objects in the same place. Thus, we can easily set the position of the second pipe relative to the first. It also means that we need less code for PipeD.

Create public gameObject with the name pipeDown. Then update the code like this:

if (character.transform.position.x - transform.position.x > 30)
        {

            float xRan = Random.Range(0, 10);
            float yRan = Random.Range(-5, 5);
            float gapRan = Random.Range(0, 3);

            Instantiate(gameObject, new Vector2(character.transform.position.x + 15 + xRan, -11 + yRan), transform.rotation);
            Instantiate(pipeDown, new Vector2(character.transform.position.x + 15 + xRan, 12 + gapRan + yRan), transform.rotation);
            Destroy(gameObject);

        }


We have added a variable gapRanthat allows you to slightly change the distance between the pipes to make it more interesting to play.

We go back to Unity and drag the prefab pipe_downfrom the prefab folder (this is important!) to the place where it says "Pipe Down" (notice how our camel case is replaced by a space) onto the pipe sprite pipe up. If you remember, we defined Pipe Downas public gameObject, which gives us the ability to determine what this object is from anywhere - in this case, through the inspector. By choosing a prefab for this object, we make sure that when the pipe is instantiated, it will include all the attributes and script that we added earlier. We don't just create a sprite, but we recreate an object with a collider that can kill the character.

All we'll add in the same place in the script PipeD is just Destroy(gameObject)to make the pipe self-destruct when it goes beyond the left screen border.

If you start the game now, the screen will advance automatically and you will die if you hit any of the pipes. Fly far enough and those pipes will disappear and reappear ahead.

Unfortunately, there is a large distance between the pipes and the screen looks blank. We could fix this by adding some prefabs to our scene to create a pipeline of constantly spawning pipes. However, it would be better to generate the pipes in a script. This is important, because otherwise, after the death of the character, the pipes at the beginning of the path will be destroyed, and an empty space will again form.

In this way, we can create the first few pipes during each game load and return everything to its place after the death of the character.

Endless flight

Now let's create public-variables in pipe_upthe pipe_downscript as well Character. This will give you the ability to reference the created objects by dragging prefabs onto the character object, just like when we added pipe_downthe Pipe.

We need to add these variables:

public GameObject pipe_up;
public GameObject pipe_down;


Then we'll write a method like this:


public void BuildLevel()
    {
        Instantiate(pipe_down, new Vector3(14, 12), transform.rotation);
        Instantiate(pipe_up, new Vector3(14, -11), transform.rotation);

        Instantiate(pipe_down, new Vector3(26, 14), transform.rotation);
        Instantiate(pipe_up, new Vector3(26, -10), transform.rotation);

        Instantiate(pipe_down, new Vector3(38, 10), transform.rotation);
        Instantiate(pipe_up, new Vector3(38, -14), transform.rotation);

        Instantiate(pipe_down, new Vector3(50, 16), transform.rotation);
        Instantiate(pipe_up, new Vector3(50, -8), transform.rotation);

        Instantiate(pipe_down, new Vector3(61, 11), transform.rotation);
        Instantiate(pipe_up, new Vector3(61, -13), transform.rotation);

    }


We will call it once in the method Update()and once in the Death().

After the start of the game, it is called Update(), and our pipes are placed according to the given configuration. Due to this, the first few obstacles will always be in the same place. After the death of the player, the pipes will return to the same places.

Return to the scene in Unity and delete the two pipes that are now there. Your "game" will just look like a blank screen with a bird. Press Play and the pipes will appear, after the first few, their position will be determined randomly.

Finally

So we made the whole game! Add a score counter, try to make it more original and increase the difficulty of the game as you progress. Also, it will not be superfluous to make a menu. Another good idea is to destroy the pipes on the screen after the death of the character. Once you're done with that, you've got a Play Store-ready game in your pocket! A similar game once made another developer very rich, proving that you don't have to be a programming genius or have a rich publisher behind you to be successful. You just need a good idea and ten minutes!

Related Articles

Add Your Comment

reload, if the code cannot be seen

All comments will be moderated before being published.