Unity3D基礎案例-見縫插針

引言:人生無處不代碼,無代碼處不人生。小生作爲U3D學習之旅中的一員,將基礎案例主要開發流程記錄下來,與共同興趣的你分享。

開發版本:unity 5.3.5f

適合人羣:初學Unity者

源文件鏈接請見文末!

開啓學習之旅吧!

 

01 場景搭建

創建2D工程StickPin,並創建新場景MainScene,導入素材,完成初始場景搭建

注意工程路徑最好不要有中文

在Circle身上掛載腳本RotateSelf.cs,控制圓圈順時針旋轉

public class RotateSelf : MonoBehaviour {

    public int speed = 90;

    private void Update()
    {
        //方法一:
        transform.Rotate(-Vector3.forward,speed*Time.deltaTime);
        //方法二:
        //transform.Rotate(-new Vector3(0, 0, speed * Time.deltaTime));
        //方法三:
        //transform.Rotate(0, 0, -speed * Time.deltaTime);
    }
}

02 開發針

製作針,並設爲預製體Pin

PinHead設爲Pin的子物體,並設置標籤PinHead

爲針頭添加Rigidbody 2D,Circle Collider 2D組件,並設置Gravity Scale爲0,勾選Is Trigger

注意,collider需要加上Rigidbody才能完成觸發檢測

創建兩個空對象,StartPoint作爲發射針的位置,SpawnPoint作爲生成針的位置

在Pin身上掛載腳本Pin.cs

新建方法PinMove

需要注意目標圓的位置targetCirclePos要加一個偏差值,防止針被圓擋住

在Start()方法中完成初始化

 private void Start()
    {
        //GameObject.FindWithTag()需要給對象設置相應標籤
        targetTf = GameObject.FindWithTag("StartPoint").transform;
        circle = GameObject.FindWithTag("Circle").transform;
        //偏差值可以根據實際情況調節
        targetCirclePos = circle.position - new Vector3(0, 1.47f, 0);
    }

在Update()方法中調用PinMove()方法

private void Update()
    {
        PinMove();
    }

 private void PinMove()
    {
      //isFly判斷是否從準備位置StartPoint發射
        if (isFly == false)
        {
            //isReach判斷是否從生成位置SpawnPoint移動至發射位置
            if (isReach == false)
            {
                //Vector3.MoveTowards()方法將物體從當前位置直線移動到目標位置
                transform.position = Vector3.MoveTowards(transform.position, targetTf.position, speed * Time.deltaTime);
            }
            //Vector3.Distance()判斷兩點之間的距離
            //如果針的當前位置距離發射位置小於0.05,則停止運動
            if (Vector3.Distance(transform.position, targetTf.position) < 0.05f)
            {
                transform.position = targetTf.position;
                isReach = true;
            }
        }
        else
        {
            //如果處於發射狀態,則針向圓方向移動
            transform.position = Vector3.MoveTowards(transform.position, targetCirclePos, speed * Time.deltaTime);
            if (Vector3.Distance(transform.position, targetCirclePos) < 0.05f)
            {
                //保證針到達圓的目標位置是統一的
                transform.position = targetCirclePos;
                //當前發射針的父對象設置爲圓,爲了讓針跟隨圓旋轉
                transform.SetParent(circle);
                isFly = false;
            }
        }
    }

新建公共方法StartFly()

//用於外部調用,設置針的發射狀態

    public void StartFly()
    {
        isFly = true;
        isReach = true;
    }

在PinHead上掛載腳本PinHead.cs

public class PinHead : MonoBehaviour
{
    //OnTriggerEnter2D在is Trigger勾選下才能起作用,用於2D觸發檢測
    private void OnTriggerEnter2D(Collider2D collision)
    {
        //如果碰撞物體的tag標籤爲PinHead,說明碰到其他的針頭了
        if (collision.CompareTag("PinHead"))
        {
            // GameObject.Find()根據物體名稱,找到GameManager物體
            //GetComponent獲取對象身上GameManager組件,調用GameOver方法
            GameObject.Find("GameManager").GetComponent<GameManager>().GameOver();
        }
    }
}

03 GameManeger遊戲管理

新建空對象GameManager,掛載腳本GameManager.cs

創建新方法SpawnPin(),用於生成針,並獲得針身上掛載的Pin腳本

 void SpawnPin()
    {
         //GameObject.Instantiate()新生成的對象類型爲Object,所以需要強轉爲GameObject類型
        GameObject pin = GameObject.Instantiate(pinPrefabs, spawnPoint.position, pinPrefabs.transform.rotation) as GameObject;
        //GetComponent用於獲取對象的組件,組件名寫在<>內
        currentPin = pin.GetComponent<Pin>();
    }

新建一個方法GamOver(),用於結束遊戲操作

 public void GameOver()
    {
        //防止兩球碰撞,多次調用GameOver方法
        if (isGameOver) return;
        //enabled設爲false,則組件失效,圓不能再旋轉
        GameObject.FindWithTag("Circle").GetComponent<RotateSelf>().enabled = false;
        isGameOver = true;
    }

在Update()方法類調用SpawnPin方法,鼠標左鍵點擊時,發射當前針,並生成新的針

 private void Update()
    {
        //isGameOVer爲false,則遊戲結束,直接返回,不再執行下面命令
        if (isGameOver) return;
        //Input.GetMouseButtonDown(0)監聽鼠標左鍵點擊事件
        if (Input.GetMouseButtonDown(0))
        {
            //調用針的StartFly方法,設置針發射
            currentPin.StartFly();
            //當前針發射後,再生成針,完成連續發射功能
            SpawnPin();
        }
    }

控制分數顯示,設置兩個全局變量,注意需要引入命名空間using UnityEngine.UI;

public Text scoreText;

public int score;

可以在Inspector面板完成賦值

在Update方法內添加,如下加粗語句,完成分數的增加和顯示

        if (Input.GetMouseButtonDown(0))
        {
           //score自增1
            score++;
            //ToString()將數值score轉爲字符串
            scoreText.text = score.ToString();
            //調用針的StartFly方法,設置針發射
            currentPin.StartFly();
            //當前針發射後,再生成針,完成連續發射功能
            SpawnPin();
        }

使用協程實現場景結束效果

  //IEnumerator(迭代器)
    IEnumerator GameOverAnimation()
    {
        while (true)
        {
            //Lerp線性插值運算,以此實現漸變效果
            mainCamera.backgroundColor = Color.Lerp(mainCamera.backgroundColor, Color.red, speed * Time.deltaTime);
            mainCamera.orthographicSize = Mathf.Lerp(mainCamera.orthographicSize, 4, speed * Time.deltaTime);
            //當到達目標值,則跳出循環
            if (Mathf.Abs(mainCamera.orthographicSize - 4) < 0.01f)
            {
                break;
            }
            //可理解爲每循環一次暫停一幀,下一幀繼續,如果不加這句,漸變效果會瞬間完成 
            yield return 0;
        }
        //完成循環後,等待0.2秒
        yield return new WaitForSeconds(0.2f);
        //重新加載當前場景
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }

需要在GameOver()方法內開啓協程

 public void GameOver()
    {
        if (isGameOver) return;
        GameObject.FindWithTag("Circle").GetComponent<RotateSelf>().enabled = false;
        //開啓協程
        StartCoroutine(GameOverAnimation());
        isGameOver = true;
    }

04 添加音樂音效

在MainCamera上添加組件AudioSource,audioclip設置背景音樂,勾選play on awake,loop選項

Volume控制音量,適量調節

在GameManager.cs中

添加public AudioClip clip,inspector面板中賦值

Update()方法中添加AudioSource.PlayClipAtPoint

if (Input.GetMouseButtonDown(0))
        {
            score++;
            scoreText.text = score.ToString();
            currentPin.StartFly();
            AudioSource.PlayClipAtPoint(clip,Camera.main.transform.position);
            SpawnPin();
        }

05 發佈PC端

File-BuildSettings 點擊Build完成打包,注意打包出的文件要放在同一個文件夾內


至此,見縫插針基礎案例開發完成,爲了督促自己學習,以後會陸續寫一些博客,幫助更多和我一樣喜歡遊戲開發的同學!
 

素材及工程文件百度雲鏈接:鏈接:https://pan.baidu.com/s/1qZqBdYO 密碼:3u1t

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章