血条制作(中山大学3D游戏第八次作业)
题目要求
血条(Health Bar)的预制设计。
具体要求如下:
●分别使用IMGUI和UGUI实现
● 使用UGUI,血条是游戏对象的一个子元素,任何时候需要面对主摄像机
● 分析两种实现的优缺点
● 给出预制的使用方法
代码仓库:https://gitee.com/lin-fengnian/3dgame/tree/master/bloodbar
视频链接:https://www.bilibili.com/video/BV1X84y1s7fT/
一、IMGUI血条制作
我们先通过GameObject菜单,在游戏场景中创建空游戏对象,将其命名为bloodBar_IMGUI。
然后我们通过编写脚本IMGUI,将其挂载到刚刚创建的游戏对象上,调用GUI.HorizontalScrollbar制作血条,设置血条为11格,初始化血条为6格,每次点击按钮增加或扣除一格血。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IMGUI : MonoBehaviour {
private Rect bloodBar;
private Rect buttonAdd;
private Rect buttonSub;
private int flag = 0;
public float curBlood = 6f;
private float targetBlood = 6f;
void Start () {
buttonAdd = new Rect(Screen.width/2 - 160,Screen.height/2 - 30, 30, 25);
buttonSub = new Rect(Screen.width/2 + 150,Screen.height/2 - 30, 30, 25);
bloodBar = new Rect(Screen.width / 2 - 150, Screen.height / 2, 300, 50);
}
private void OnGUI()
{
GUIStyle style1 = new GUIStyle();
style1.fontSize = 25;
style1.normal.textColor = Color.red;
GUIStyle style2 = new GUIStyle();
style2.fontSize = 25;
style2.normal.textColor = Color.green;
if (GUI.Button(buttonAdd, " + ", style2)) flag = 1;
if (GUI.Button(buttonSub, " - ", style1)) flag = -1;
if (flag == 1)
{
add();
flag = 0;
}
else if (flag == -1)
{
sub();
flag = 0;
}
curBlood = Mathf.Lerp(curBlood, targetBlood, 0.1f);
GUI.HorizontalScrollbar(bloodBar, 0f, curBlood, 0f, 11f);
}
public void sub()
{
targetBlood = targetBlood - 1 < 0f ? 0f : targetBlood - 1;
}
public void add() {
targetBlood = targetBlood + 1 > 11f? 11f : targetBlood + 1;
}
}
效果图:
二、UGUI血条制作
● 首先创建一个plane平面,并初始化其参数,作为地板。并通过材质给其添加颜色。
● 创建预制bloodBar_UGUI,并对其参数进行调整,将其设置为预制体,然后我们将其拖入场景中,场景命名为:UGUIScenes。
● 对camera的参数进行调整,使其能够正对游戏对象血条。
● 我们通过canvas来创建画布,如下图:
我们设置MaxValue等于1, Navigation等于None。
● 此后,我们通过使用Slider,并给其添加响应的参数,通过给滑条设置颜色(设为红色)使之成为血条。
● 最后,我们通过把脚本UGUI挂载在canvas上面,就可以实现血条了!
using UnityEngine;
public class UGUI : MonoBehaviour {
void Update () {
this.transform.rotation = Quaternion.LookRotation(new Vector3(0, 0, 1));
}
}
三. UGUI和IMGUI优缺点比较
UGUI:
优点:
● 可以直接使用设计工具(WYSIWYG),设计师也可以直接参与游戏开发
● 能够支持多摄像机、多模式的渲染。
● UI 元素可以和游戏场景直接进行交互。
● 面向对象编程
缺点:
● 效率较差
● 不符合一般游戏编程的习惯
IMGUI
优点:
● 符合一般游戏编程的习惯。
● 如果需要对模型进行修改、渲染,在经典循环游戏编程模式中绘制 UI 界面在渲染之后,具有优越性,方便程序员对UI进行控制。
● 执行效率占优。
缺点:
● 代码通过动态生成,通常不用于玩家可交互的界面,每次调试都不得不开启游戏,比较麻烦。
四. 预制使用方法
IMGUI制作的预制可以直接拉拽使用。
UGUI使用任务预制。
五. 引用
https://blog.csdn.net/weixin_50223388/article/details/122178171
https://blog.csdn.net/weixin_43977005/article/details/111184154
https://blog.csdn.net/m0_61777011/article/details/124385724