天天看點

unity自學筆記--變色跑酷一、項目描述二、項目制作

Unity自學筆記–變色跑酷

一、項目描述

根據B站上的額皮皮關做遊戲老師的視訊一步步做下來的,同學們也可以去搜尋哦。

這是一款最近比較火的變色跑酷遊戲:

1.玩家直線前進,遇到障礙需要跳起躲避,支援二級彈跳;

2.遇到不同顔色的物體需要改變不同的顔色,顔色與将要落下來的物體顔色不同則遊戲失敗;

3.灰色物體不可碰到,碰到則遊戲失敗;

4.鍵盤up控制彈跳,space控制變色(紅綠顔色切換)

二、項目制作

1.資源下載下傳,大家可以到B站視訊下方找到資源連接配接(免費

百度網盤:https://pan.baidu.com/s/1t2llUGDCzGboXK6mZ8Cz1g

提取碼:abnt

下載下傳好資源包後,可在unity工具欄選擇Assets-ImportPackage-CustomPackage…選擇下載下傳的資源包打開;

或者直接将資源包解壓好拖到unity中的project裡:

unity自學筆記--變色跑酷一、項目描述二、項目制作

2.子產品搭建

可以使用cube調整尺寸搭乘項目中的樣子,這裡直接從資源包裡拖拽:(注意将模型拖到Hierarchy中而不是直接放到scene中,這樣模型的位置友善調節)

unity自學筆記--變色跑酷一、項目描述二、項目制作

不同顔色的cube設定為不同的tag用于碰撞時的檢測:

unity自學筆記--變色跑酷一、項目描述二、項目制作

(若無Red、Green、Undefine标簽,可選擇New tag,然後添加标簽)

unity自學筆記--變色跑酷一、項目描述二、項目制作

添加player:

首先在Hierarch中添加一個空物體:Create Empty,将其命名為Player。

在project中找到PlayerModel模型,拖拽到我們見的Play下方。

将其調整到合适位置。

unity自學筆記--變色跑酷一、項目描述二、項目制作
unity自學筆記--變色跑酷一、項目描述二、項目制作

3. 添加實體屬性

3.1 為Player添加BoxCollider與Rigidbody元件,勾選X方向移動限制,X、Y、Z反向上的旋轉限制(我們主要的移動為向前與上跳,是以限制其他自由度)

unity自學筆記--變色跑酷一、項目描述二、項目制作

3.2在Assets中右擊建立實體材質Physic Material命名為PM_player,并設定摩擦力與彈力為最小:

unity自學筆記--變色跑酷一、項目描述二、項目制作

3.3 将建立的PM_player實體材質添加給Player的boxcollider:

unity自學筆記--變色跑酷一、項目描述二、項目制作

4. 人物動作代碼:

建立C#script,命名為PlayerCharacter:

代碼如下:

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

public class PlayerCharacter : MonoBehaviour {
   /*定義顔色改變的枚舉*/
    public enum TransColor
    { 
    Red,
        Green,
        Undefine,
    }
    /*需要使用到的屬性*/
    TransColor colorCurrent;     //定義目前顔色
    Rigidbody rigid;                       //定義剛體
    Renderer render;                   //定義Render屬性
    Animator animator;                //需要使用動畫播放
    Collision collisionRet;            //碰撞狀态

    public float speed;                  //前進速度
    public  float jumpForce;         //跳躍
    public float doubleJumpForce;//二次跳躍

    public AudioSource music;           //添加音樂播放元件
    public AudioClip jump;                   //添加jump音效
    public AudioClip cchangerColor;//添加顔色改變時的音效
    public AudioClip die;                        //添加死亡時的音效
  
    
    int jumpCount = 0;                              //存儲跳躍次數

    bool onGround;                                    //檢測是否落回地面

    public bool isAlive;                             //檢測player狀态

    public  ParticleSystem dieParticle;//添加死亡是的粒子特效
   /*初始化*/
    public void Awake()
    {
        rigid = GetComponent<Rigidbody>();
        render = GetComponentInChildren<Renderer>();//由于renderer挂在了子cube上,是以這裡使用了GetComponentInChildren
        animator = GetComponentInChildren<Animator>();
        isAlive = true;                                                              //初始player狀态為true
        render.material.color = Color.red;                           //初始設定顔色為紅色
        colorCurrent = TransColor.Red;                               //對應的将顔色狀态對應為枚舉的red
        dieParticle.Stop();                                                      //不播放死亡特效
    }
    /*檢查是否落地*/
    public bool GroundCheck()
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, 0.5f);   //檢測碰撞球範圍内的物體
        for (int i = 0; i < colliders.Length; i++)
        {
            if (colliders[i].gameObject !=gameObject)                                                 
            {
                return true;
            }
            
        }
        return false;
    }
    /*物體的移動*/
    public void Move()
    {
        if (!isAlive)                                                               //若是活着才會執行
        {
            return;
        }
        var ve1 = rigid.velocity;                                           //var為弱變量,當不确定值類型時,可用var
        ve1.z = (Vector3.forward * speed).z;                     //隻定義Z方向上的運動
        rigid.velocity = ve1;

    }
    public void Jump()
    {
        if (!isAlive)
        {
            return;
        }
        if (jumpCount<2)                               //我們具有兩次彈跳功能
        {
            if (jumpCount==0)
            {
                rigid.velocity = new Vector3(rigid.velocity.y, 0, rigid.velocity.z);
                rigid.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
                music.clip = jump;
                music.Play();
            }
            else if (jumpCount==1)
            {
                rigid.velocity = new Vector3(rigid.velocity.y, 0, rigid.velocity.z);
                rigid.AddForce(Vector3.up * doubleJumpForce, ForceMode.Impulse);
                music.clip = jump;
                music.Play();
            }
            jumpCount++;                                //彈跳計數
        }
    }
    public void Die()
    {
        isAlive = false;
        render.enabled = false;
        rigid.velocity = Vector3.zero;

        Invoke("ReStart", 1);
        dieParticle.Play();
        music.clip = die;
        music.Play();
    }

    /*當玩家死亡或者遊戲結束時重新打開場景*/
    public void ReStart()
    {
        UnityEngine.SceneManagement.SceneManager.LoadScene("變色龍0609");//更新場景

    }
    public void ChangeColor()
    {
        if (!isAlive)
        {
            return;
        }

        if (colorCurrent==TransColor.Red)
        {
            colorCurrent = TransColor.Green;              //顔色狀态改變記錄
            render.material.color = Color.green;          //顔色改變
        }
else if (colorCurrent == TransColor.Green)
        {
            colorCurrent = TransColor.Red;
            render.material.color = Color.red;
        }
        animator.SetTrigger("ChangeColor");          //播放名字為“ChangeColor”的動畫
        music.clip =cchangerColor;                           //改變顔色的音效
        music.Play();                                                        //音效播放
    }

    /*碰撞檢測*/
    private void OnCollisionEnter(Collision collision)
    {
        jumpCount = 0;                          //将跳躍計數設定為0
        collisionRet = collision;           //碰撞狀态為碰撞
    }
    private void OnCollisionStay(Collision collision)//碰撞停留時
    {
        collisionRet = collision;
    }
    private void OnCollisionExit(Collision collision)//碰撞離開時
    {
        collisionRet = null;                                              // 将碰撞資訊設定為空:null
    }
	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void FixedUpdate ()
    {
        if (!isAlive)
        {
            return;
        }

        if (collisionRet!=null)                                                     //未碰撞時才會執行
        {
            if (collisionRet.gameObject.CompareTag("Red"))//檢測碰撞到的物體标簽,若是Red則執行
            {
                if (colorCurrent!=TransColor.Red)
                {
                    Die();
                }
            }
            else if (collisionRet.gameObject.CompareTag("Green"))
            {
                if (colorCurrent != TransColor.Green)
                {
                    Die();
                }
            }
            else                                                                                 //若碰撞檢測到标簽不是Red、Green則執行Die
            {
                Die();
            }
        }
        onGround = GroundCheck();                                      //檢測是否在地面     
         animator.SetBool("OnGround", onGround);           //将上句檢測到的bool值賦給動畫中的“OnGround”
	}
}

           
  1. 添加前進以及跳躍的動畫

    建立檔案夾命名為Animation

    并在右側Assets中右擊建立Animation Controller命名為AC_animation,完成後輕按兩下打開:

    unity自學筆記--變色跑酷一、項目描述二、項目制作
    找到Prefab中的PlayerModel模型,點選動畫的三角圖示,然後找到jump,run另外随便加個動畫(改名字為ColorChange),将三個動畫拖到AnimationController界面中:
    unity自學筆記--變色跑酷一、項目描述二、項目制作
    在入口Enter上右擊選擇Make Transition到Run(遊戲開始便run)然後如圖建立連接配接
    unity自學筆記--變色跑酷一、項目描述二、項目制作
    unity自學筆記--變色跑酷一、項目描述二、項目制作

    Run動畫與Jump動畫之間的切換我們使用檢測玩家是否在地面進行切換,當OnGround為true的時候run,false狀态執行Jump

    動畫機界面左側選擇Parameters界面,點選“+”号,選擇bool條件,将彈出的條件名稱改為“Onground”;

    unity自學筆記--變色跑酷一、項目描述二、項目制作
    選擇Run到Jump的切換路線将右側屬性内的條件設定為False,Jump至Run則改為true:
    unity自學筆記--變色跑酷一、項目描述二、項目制作

    改變顔色的動畫為space按下才會執行,是以切換的方式為Trigger;

    按類似上步的方法點選“+”号選擇"Trigger"彈出的條件命名為“ChangeColor”,并将此條件添加到Any State到ColorChange動畫路線上,另外兩個路線不必添加;

  2. 錄影機跟随

    使用經典的保留位置差跟随移動代碼:

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

public class CameraFollow : MonoBehaviour {

    Vector3 Dir;
    //要跟随的物體
    public GameObject m_Player;
    // Use this for initialization
    void Start()
    {
        //擷取到錄影機于要跟随物體之間的距離
        Dir = m_Player.transform.position - transform.position;
    }

    // Update is called once per frame
    void LateUpdate()
    {
        //錄影機的位置
        transform.position = m_Player.transform.position - Dir;
    }
}
           
  1. 遊戲運作代碼:

    現在Hierarchy中Create空物體,命名為PlayerController

    建立C#Cript命名為"PlayerConller"并添加到上建立的playerController物體上:

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

public class PlayerController : MonoBehaviour {
    public PlayerCharacter character;
    void Awake()
    {
        character = FindObjectOfType<PlayerCharacter>();//初始化搜尋我們上面寫的PlayerCharacter元件

    }

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        if (!character.isAlive)
        {
            return;
        }

        character.Move();               //移動
        bool jump = Input.GetKeyDown(KeyCode.UpArrow);   //向上箭頭跳躍
        bool changeColor = Input.GetKeyDown(KeyCode.Space);//空格改變顔色
     
        if (jump)                                                                                     //收到跳躍指令便執行
        {
            character.Jump();                                                           
        }
        if (changeColor)                                                                        // //收到改變顔色指令便執行
        {
            character.ChangeColor();
           
        }
	}
}

           
  1. 添加粒子特效與音效:

    死亡粒子特效:在如下檔案夾中選擇自己喜歡的特效,然後拖拽到Hierarchy中的Player下,調整其位置與Player在一起

    unity自學筆記--變色跑酷一、項目描述二、項目制作
    然後将粒子拖到右側屬性PlayerCharacter元件裡:
    unity自學筆記--變色跑酷一、項目描述二、項目制作

    給Player添加AutioSourse元件;

    在Sound檔案夾中選擇合适的音效:(這裡順便将Speed等參數設定好,自己可看效果微調)

    unity自學筆記--變色跑酷一、項目描述二、項目制作

    /////************************************

    最後的最後,build&&run吧

繼續閱讀