【UNET自學日誌】Part10 摧毀玩家

上一個部分做了玩家的射擊造成的傷害,但是玩家生命值爲負的時候玩家還在遊戲場景上,這個部分我們將要把生命值爲0以下的玩家摧毀掉

主要的思路就是當玩家的生命值小於或等於0的時候,將玩家的控制和渲染都設置爲不可用即可

將Player_Health腳本做下修改

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.UI;

public class Player_Health : NetworkBehaviour {

    //玩家的生命值,當生命值的數值發生變化時調用OnHealthChanged函數
    [SyncVar(hook="OnHealthChanged")]private int health = 100;

    //右下角顯示生命值的Text
    private Text healthText;

    //判斷玩家是否死亡的兩個bool變量
    private bool shouldDie = false;
    public bool isDead = false;


    public delegate void DieDelegate();
    public event DieDelegate EventDie;

	void Start ()
    {
        healthText = GameObject.Find("Health Text").GetComponent<Text>();
        SetHealthText();
	}
	
	void Update () 
    {
        CheckCondition();
	}

    //檢查條件
    void CheckCondition()
    {
        if (health <= 0 && !shouldDie&&!isDead)
        {
            shouldDie = true;
        }

        if (health <= 0 && shouldDie)
        {
            if (EventDie != null)
            {
                EventDie();
            }

            shouldDie = false;
        }
    }

    //設置生命值Text的內容
    void SetHealthText()
    {
        if (isLocalPlayer)
        {
            healthText.text = "Health " + health.ToString();
        }
    }

    //生命值減少
    public void DeductHealth(int dmg)
    {
        health -= dmg;
    }

    //生命值改變
    void OnHealthChanged(int hlth)
    {
        health = hlth;
        SetHealthText();
    }
}


另新建一個腳本Player_Death

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.UI;

public class Player_Death : NetworkBehaviour {

    private Player_Health healthScript;
    //畫面中心的小紅點
    private Image crossHairImage;


	void Start () 
    {
        crossHairImage = GameObject.Find("crossHairImage").GetComponent<Image>();
        healthScript = GetComponent<Player_Health>();
        healthScript.EventDie += DisablePlayer;
	}

    void OnDisable()
    {
        healthScript.EventDie -= DisablePlayer;
    }
	
    //將Player的相關控制和渲染設置成不可用狀態,以代表摧毀Player
    void DisablePlayer()
    {       
        GetComponent<CharacterController>().enabled=false;       
        GetComponent<Player_Shoot>().enabled = false;
        GetComponent<BoxCollider>().enabled = false;

        Renderer[] renderers = GetComponentsInChildren<Renderer>();
        foreach (Renderer ren in renderers)
        {
            ren.enabled = false;
        }

        healthScript.isDead = true;

        if (isLocalPlayer)
        {
            GetComponent<UnityStandardAssets.Characters.FirstPerson.FirstPersonController>().enabled = false;
            crossHairImage.enabled = false;
            //Respawan button 預留重生按鈕,下個部分做
        }
    }
}

其中用到了一個委託的方法,因爲對委託不是很熟悉,也就不多說些誤人子弟的話了。

按着某人的建議寫了點註釋= =爲什麼感覺那麼雞肋呢。。。

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