Unity3D-制作人物血量条

来源:互联网 发布:时时彩合买源码 编辑:程序博客网 时间:2024/04/29 01:26

方法一、使用NGUI

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

Step1:

Step2:设置参数

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

using UnityEngine;using System.Collections;public class Enemy : MonoBehaviour {public GameObject mSlider;//将前面创建的Slider拖到此处;private GameObject uiRoot;void Start () {uiRoot = GameObject.FindGameObjectWithTag ("UIRoot");}void Update () {Vector3 pos0 = transform.position;Vector3 pos1 = Camera.main.WorldToScreenPoint (pos0);                //将屏幕坐标转换为NGUI相机的世界坐标。                mSlider.transform.position = UICamera.currentCamera.ScreenToWorldPoint (pos1)  + new Vector3 (-0.4f, 0.3f, 0);                //改变血量if (Input.GetKeyDown(KeyCode.A)) {mSlider.GetComponent<UISlider>().value += 0.1f;}if (Input.GetKeyDown(KeyCode.D)) {mSlider.GetComponent<UISlider>().value -= 0.1f;}}}

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


方法二、使用GUITexture

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

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

using UnityEngine;using System.Collections;public class Enemy : MonoBehaviour {public GUITexture HPTexture;//下图红色部分public GUITexture backgroundOfHPTexture;//下图白色部分public GUITexture charactorTexture;//下图太空人public float percentOfHP = 0.3f;//血量百分比// Update is called once per framevoid Update (){Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);                //GUITexture的位置是相对于摄像机屏幕的位置,左下角是(0,0,0)右上角(1,1,0)忽略Z坐标。backgroundOfHPTexture.transform.position = new Vector3 (pos.x-0.15f, pos.y+0.15f, 0);                //设置相对于自身的坐标和大小。                backgroundOfHPTexture.pixelInset = new Rect(0,0,200f,10f);HPTexture.transform.position = new Vector3 (pos.x-0.15f, pos.y+0.15f, 1);HPTexture.pixelInset = new Rect(0,0,200f * percentOfHP,10f);charactorTexture.transform.position = new Vector3 (pos.x-0.15f, pos.y-0.1f, 1);charactorTexture.pixelInset = new Rect (0, 0, 128, 58);transform.Translate (new Vector3 (1f * Time.deltaTime,0,0 * Time.deltaTime ));}}

最终效果图:







1 0
原创粉丝点击