《杜增強講Unity之Tanks坦克大戰》7-坦克血條


7 坦克血條

點擊菜單GameObject->UI->Slider創建Slider

 

選中EventSystem,設置Horizontal Axis為HorzontalUI,Vertical Axis為VerticalUI

 
image

選中Canvas,設置Render Mode為World Space, Reference Pixels Per Unit為1

 
image

將Canvas拖到Tank中,使其成為Tank的子對象,相關參數設置如下

 
image

將Slider改名為HealthSlider,取消選擇Interactable,設置Transition為None,Max Value改為100

 
image

在Hierarchy里面,按住Alt鍵點擊HealthSlider前面的三角箭頭

 
image

然后刪除Handle Slide Area

同時選中HealthSlider,Background,FillArea,Fill, 點擊Rect Transform里面的Sketch,按着Alt鍵選中右下角的水平垂直拉伸.

 
image

選中Background,設置Source Image為Health Wheel,Color為紅色,Alpha為80

 
image
 
image

選中Fill,設置Source Image為Health Wheel,Color為綠色,Alpha為150,Image Type為Filled,Fill Method為Radial 360,Fill Origin為Left,取消選擇Clockwise.

[圖片上傳中...(image-d0dada-1539997823498-3)]

新建Health.cs,聲明float變量currentBlood為當前血值.

public float currentBlood = 100; // 當前血值

添加healthSlider顯示當前血值

public Slider slider; // 血槽

為Health.cs添加TakeDamage方法

public void TakeDamage (float damage) { // 受到傷害,開始掉血

    currentBlood -= damage; // 掉血 slider.value = currentBlood; // 更新血槽顯示 } 

當坦克收到傷害,血值不斷減少到小於等於0的時候,坦克播放爆炸效果和爆炸音效.

從Prefabs里面找到TankExplosion坦克爆炸效果添加到坦克上面

 
image

private ParticleSystem ps; // 爆炸效果

private AudioSource audioSource; // 聲源 

還需要添加一個爆炸音效

public AudioClip explosionAudio; // 爆炸音效

[圖片上傳中...(image-a2ce6e-1539997823498-1)]

在Start里面獲取ps和audioSource

ps = GetComponentInChildren <ParticleSystem> (); // 獲取子對象的ParticleSystem

    audioSource = GetComponent<AudioSource> (); // 獲取音源 

然后在血值減為0時播放爆炸效果

if( currentBlood <= 0){

        ps.transform.parent = null; // 將爆炸效果從Shell里面移出 ps.Play (); // 播放爆炸效果 audioSource.Play (); // 播放爆炸音效 Destroy (ps.gameObject, ps.duration); // 爆炸效果播放完畢之后移出爆炸效果的gameObject Destroy (gameObject); // 移出Shell的gameObject } 

最終代碼

[圖片上傳中...(image-fcf493-1539997823497-0)]

Health.cs

using UnityEngine;

using UnityEngine.UI;

using System.Collections;

public class Health : MonoBehaviour {

public Slider slider; // 血槽 public float currentBlood = 100; // 當前血值 private ParticleSystem ps; // 爆炸效果 private AudioSource audioSource; // 聲源 public AudioClip explosionAudio; // 爆炸音效 // Use this for initialization void Start () { ps = GetComponentInChildren <ParticleSystem> (); // 獲取子對象的ParticleSystem audioSource = GetComponent<AudioSource> (); // 獲取音源 } public void TakeDamage (float damage) { // 受到傷害,開始掉血 currentBlood -= damage; // 掉血 slider.value = currentBlood; // 更新血槽顯示 if( currentBlood <= 0){ ps.transform.parent = null; // 將爆炸效果從Shell里面移出 ps.Play (); // 播放爆炸效果 audioSource.Play (); // 播放爆炸音效 Destroy (ps.gameObject, ps.duration); // 爆炸效果播放完畢之后移出爆炸效果的gameObject Destroy (gameObject); // 移出Shell的gameObject } } 

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM