2292人加入学习
(1人评价)
愤怒的小鸟-Unity2023-2D游戏开发小白教程

使用Unity2023.1.1 VS2022 制作完成于2023年11月20日

价格 免费

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    public Bird[] birdList;
    private int index = -1;

    private void Awake()
    {
        Instance = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        birdList = FindObjectsByType<Bird>(FindObjectsSortMode.None);

        LoadNextBird();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void LoadNextBird()
    {
        index++;
        birdList[index].GoStage(Slingshot.Instance.getCenterPositon());
    }
}
 

[展开全文]

小鸟移动时相机要跟着移动

1.在相机上挂脚本FollowTarget:

(1)设置目标变量Transform类型target

(2)在Update():因为只要改x轴,所以先获取相机坐标放在变量position中,再修改position.x,不要直接等于target.x,用v3.Lerp();

(3)测试:发现初始视图右侧漏背景外了。所以要限制相机x的范围。用Mathf.Clamp,限定相机x阀内在0-20之间。

(4)为防止小猪滚出边界。在场景后面加一个BgDown,用其碰撞体。在树桩部分,用BgDown做个细长条,不显示,用其碰撞体。

[展开全文]

using System.Collections; using System.Collections.Generic; using UnityEngine; public enum BirdStart { Waiting, BeforeShoot, AfterShoot } public class Bird : MonoBehaviour { public BirdStart state = BirdStart.BeforeShoot; //等待 发射前 发射后 public bool isMouseDown = false; public float maxDistance = 2.4f; public float flySpeed = 5; private Rigidbody2D rgd; // Start is called before the first frame update void Start() { rgd = GetComponent(); rgd.bodyType = RigidbodyType2D.Static; } // Update is called once per frame void Update() { switch (state) { case BirdStart.Waiting: break; case BirdStart.BeforeShoot: MoveControl(); break; case BirdStart.AfterShoot: break; } } //OnMouseDown OnMouseUp private void OnMouseDown() { if(state == BirdStart.BeforeShoot) { isMouseDown = true; Slingshot.Instance.StartDraw(transform); } } private void OnMouseUp() { if (state == BirdStart.BeforeShoot) { isMouseDown = false; Slingshot.Instance.EndDraw(); Fly(); } } private void MoveControl() { if(isMouseDown) { transform.position = GetMousePosition(); } } private Vector3 GetMousePosition() { Vector3 centerPosition = Slingshot.Instance.getCenterPositon(); Vector3 mp = Camera.main.ScreenToWorldPoint(Input.mousePosition); mp.z = 0; Vector3 mouseDir = mp - centerPosition; float distance = mouseDir.magnitude; if (distance > maxDistance) { mp = mouseDir.normalized * maxDistance + centerPosition; } return mp; } private void Fly() { rgd.bodyType = RigidbodyType2D.Dynamic; rgd.velocity = (Slingshot.Instance.getCenterPositon() - transform.position).normalized * flySpeed; state = BirdStart.AfterShoot; } }

[展开全文]

OncollisionEnter2D 可以检测碰撞

 

collison.relativeVelocity.magnitude  碰撞力度

A B 物体相对移动速度

 

 

 

[展开全文]

绘制线段

LineRenderer.SetPosition(0,V3)

LineRenderer.SetPosition(1,v3)

绘制一条线段 从0.v3到1.v3

 

获得鼠标所在位置的坐标

Vector3 v3= Camera.main.ScreenToWorldPoint(Input.mousePosition);

 

[展开全文]