Unity3D-制作人物血量条

方法一、使用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 frame
	void 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
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值