Unity血量条制作 以上经验都为百度所得

方法一、使用NGUI

Step0:导入NGUI包.创建一个UIRoot(2D)和一个Cube;

Step1:

Step2:设置参数

Step3:将下面代码挂到Cube上:

[csharp]  view plain  copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class Enemy : MonoBehaviour {  
  5.     public GameObject mSlider;//将前面创建的Slider拖到此处;  
  6.     private GameObject uiRoot;  
  7.     void Start () {  
  8.         uiRoot = GameObject.FindGameObjectWithTag ("UIRoot");  
  9.     }  
  10.   
  11.     void Update () {  
  12.         Vector3 pos0 = transform.position;  
  13.         Vector3 pos1 = Camera.main.WorldToScreenPoint (pos0);  
  14.                 //将屏幕坐标转换为NGUI相机的世界坐标。  
  15.                 mSlider.transform.position = UICamera.currentCamera.ScreenToWorldPoint (pos1)  + new Vector3 (-0.4f, 0.3f, 0);  
  16.   
  17.                 //改变血量  
  18.         if (Input.GetKeyDown(KeyCode.A)) {  
  19.             mSlider.GetComponent<UISlider>().value += 0.1f;  
  20.         }  
  21.           
  22.         if (Input.GetKeyDown(KeyCode.D)) {  
  23.             mSlider.GetComponent<UISlider>().value -= 0.1f;  
  24.         }  
  25.     }  
  26. }  

Step4:点击键盘A和D查看运行结果如图:


方法二、使用GUITexture

GUITexture是二维GUI中的纹理图片,在Scene视图中不能显示Texture的样子,它的样子只能在摄像机中看到。

你需要将下面代码挂到Cube上,再拖上对应的PNG图片。

[csharp]  view plain  copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class Enemy : MonoBehaviour {  
  5.     public GUITexture HPTexture;//下图红色部分  
  6.     public GUITexture backgroundOfHPTexture;//下图白色部分  
  7.     public GUITexture charactorTexture;//下图太空人  
  8.     public float percentOfHP = 0.3f;//血量百分比  
  9.   
  10.     // Update is called once per frame  
  11.     void Update ()    
  12.     {     
  13.         Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);  
  14.   
  15.                 //GUITexture的位置是相对于摄像机屏幕的位置,左下角是(0,0,0)右上角(1,1,0)忽略Z坐标。  
  16.         backgroundOfHPTexture.transform.position = new Vector3 (pos.x-0.15f, pos.y+0.15f, 0);  
  17.                 //设置相对于自身的坐标和大小。  
  18.                 backgroundOfHPTexture.pixelInset = new Rect(0,0,200f,10f);  
  19.   
  20.         HPTexture.transform.position = new Vector3 (pos.x-0.15f, pos.y+0.15f, 1);  
  21.         HPTexture.pixelInset = new Rect(0,0,200f * percentOfHP,10f);  
  22.   
  23.         charactorTexture.transform.position = new Vector3 (pos.x-0.15f, pos.y-0.1f, 1);  
  24.         charactorTexture.pixelInset = new Rect (0, 0, 128, 58);  
  25.   
  26.         transform.Translate (new Vector3 (1f * Time.deltaTime,0,0 * Time.deltaTime ));  
  27.     }  
  28. }  

最终效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值