[Unity] 2D game-Angry Birds teaching practice (with source code and implementation steps in super detail)

If you need source code and resource files, please like, follow, and leave a private message in the comment area~~~

Below we will implement a simple version of Angry Birds in Unity3D. The most complicated part of the game is the physics system, but with the help of the Unity3D editor, we don't have to worry too much

1. Effect display

First show the running effect of the program as follows 

Running the program can eject the bird and display the trajectory. Readers can optimize it by themselves.

 

 

2. Program directory structure

The Hierarchy view structure is as follows 

The directory structure of the Assets folder is shown in the figure below

 

The structure of the C# script file stored in Scripts is as follows

 The prefab structure stored in the Prefabs folder is as follows

3. Implementation steps

Because Angry Birds is a 2D game, you need to select a 2D template when creating a new project and then import the resource pack into the project, which contains pictures and other resources as shown in the figure below

 

camera settings

Find the Scenes folder in the Project view and then find the level01.unity folder and double-click to open the background color in the settings

ground setting

Find the ground.png file in the Sprites folder in the Project view, import the settings in the Inspector view, set Pixels Per Unit to 16 and click the apply button

Tips: After that, all the icons are set to 16. This means that 16*16 pixels are a unit in the game world. The reason for choosing 16 is that the size of the bird is 16*16

Now the ground is just the image and not part of the physics world, things don't collide with it and don't stand on top of it, so we need to add a collider to give it physics so things can stand on the ground. In the Inspector view, select Add Component->Physics 2D->Box Collider 2D component to add

boundary setting

Create an empty object named borders and add a collider to it. The operation steps are as described below and check the Is Trigger property and add two colliders to the right and top.

Now you need the functionality to destroy any objects that enter the borders Click on the borders object In the Inspector view select the Add Component New Script command and name the script Borders

cloud settings

Drag cloud.png into the Scenes view and repeat the previous step to place the cloud at your favorite position

Hitting object setting

Next, let’s add some bird hitting objects, such as wood, stone, ice, etc., and drag them into the Scenes view. Set Pixels Per Unit to 16. Also add rigid body properties and select Add Component->Physics 2D-> Rigidbody 2D command.

slingshot setting

Drag the slingshot.png file into the Scenes view and set the Pivot to Top

set bird

Set the physical characteristics of the bird, including motion trajectory collision, etc. It is omitted here

enemy settings

We set the green pig so that the enemy can hit it, and also set the game logic of the enemy

Slingshot rubber setting

We're also going to add rubber to the slingshot so it looks nicer and more realistic

4. Code

Part of the code is as follows. All source code and resource files are required. Please like and follow the collection and leave a private message in the comment area.

1

using UnityEngine;

public class Spawn : MonoBehaviour
{
    // 鸟的预制体
    public GameObject birdPrefab;
    // 鸟是否在触发区域
    bool occupied = false;

    void FixedUpdate()
    {
        // 鸟不在触发区域
        if (!occupied && !sceneMoving())
            spawnNext();
    }
    void spawnNext()
    {
        // 生成一只鸟
        Instantiate(birdPrefab, transform.position, Quaternion.identity);
        occupied = true;
    }

    void OnTriggerExit2D(Collider2D co)
    {
        // 鸟离开触发区域
        occupied = false;
    }

    bool sceneMoving()
    {
        // 找到所有的鸟的刚体,看看是否还有仍然移动的
        Rigidbody2D[] bodies = FindObjectsOfType(typeof(Rigidbody2D)) as Rigidbody2D[];
        foreach (Rigidbody2D rb in bodies)
            if (rb.velocity.sqrMagnitude > 5)
                return true;
        return false;
    }
}

2

using UnityEngine;

public class Rubber : MonoBehaviour
{
    //橡胶预制体
    public Transform leftRubber;
    public Transform rightRubber;

    //调整橡胶旋转和长度
    void adjustRubber(Transform bird, Transform rubber)
    {
        // 橡胶的旋转变化
        Vector2 dir = rubber.position - bird.position;
        float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        rubber.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        // 橡胶的长度变化
        float dist = Vector3.Distance(bird.position, rubber.position);
        dist += bird.GetComponent<Collider2D>().bounds.extents.x;
        rubber.localScale = new Vector2(dist, 1);
    }

    //OnTriggerStay2D函数将通知我们鸟是否还在弹弓上
    void OnTriggerStay2D(Collider2D coll)
    {
        // 弹弓的橡胶拉伸
        adjustRubber(coll.transform, leftRubber);
        adjustRubber(coll.transform, rightRubber);
    }

    //鸟离开时触发事件
    void OnTriggerExit2D(Collider2D coll)
    {
        // 弹弓的橡胶设置为默认值
        leftRubber.localScale = new Vector2(0, 1);
        rightRubber.localScale = new Vector2(0, 1);
    }
}

3

 

using UnityEngine;

public class PullAndRelease : MonoBehaviour
{
    // 鸟的默认位置
    Vector2 startPos;
    // 添加的力
    public float force = 1300;

    void Start()
    {
        startPos = transform.position;
    }

    //监听鼠标抬起事件
    void OnMouseUp()
    {
        // 禁用isKinematic,这样刚体就会再次受到重力和速度的影响
        GetComponent<Rigidbody2D>().isKinematic = false;
        // 添加力
        Vector2 dir = startPos - (Vector2)transform.position;
        GetComponent<Rigidbody2D>().AddForce(dir * force);
        // 销毁当前组件脚本
        Destroy(this);
    }

    //监听鼠标拖拽事件
    void OnMouseDrag()
    {
        //将鼠标位置转换为世界位置
        Vector2 p = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        //设置最大半径
        float radius = 1.8f;
        Vector2 dir = p - startPos;
        if (dir.sqrMagnitude > radius)
            dir = dir.normalized * radius;
        //设置位置
        transform.position = startPos + dir;
    }
}

4

using UnityEngine;

public class Trail : MonoBehaviour
{
    //轨迹的预制体
    public GameObject[] trails;
    //使用一个计时器变量用来记录当前生成的数组下标
    int next = 0;

    void Start()
    {
        //每100毫秒生成一条新路径对象
        InvokeRepeating("spawnTrail", 0.1f, 0.1f);
    }

    void spawnTrail()
    {
        //只要鸟的移动速度够快,才去刷出轨迹
        if (GetComponent<Rigidbody2D>().velocity.sqrMagnitude > 25)
        {
            //实例化trails数组中next下标的对象
            Instantiate(trails[next], transform.position, Quaternion.identity);
            //next+1增加next
            next = next + 1;
            //next等于预制体数组最大值就从0开始
            if (next == trails.Length) next = 0;
        }
    }
}

It's not easy to create and find it helpful, please like, follow and collect~~~

Guess you like

Origin blog.csdn.net/jiebaoshayebuhui/article/details/128647688