这一讲主要是讲人物如何掉血,是为了下一节掉血同步做铺垫的,这节先讲仅在服务器端的掉血,客户端不同步!重要的事情讲3遍:服务器端,服务器端,服务器端!!!
首先是用Slider制作血条,制作方法网上资料很多就不讲了。
几个注意的地方:血条是世界坐标,所以Canvas要改成world space,还有就是相机要永远看到血条的正面(不会变成一个片),因此加上了Lookatcamera的脚本,如下图:
脚本的具体代码如下:把这个脚本绑定到canvas上就可以了。
using UnityEngine; using System.Collections; public class Lookatcamera : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Camera.main!=null) this.gameObject.transform.LookAt(Camera.main.transform); } }
然后就看人物了,人物既然要血条显示掉血,那必然有对应的代码来实现,代码如下:
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.Networking; public class health : NetworkBehaviour { public const int maxhealth = 100; public int currenthealth = maxhealth; public Slider healthslider; public void Takedamage(int damage) { if (isServer == false) { return; } currenthealth -= damage; if (currenthealth<=0) { currenthealth = 0; } healthslider.value = currenthealth / (float)maxhealth; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
只要将该代码绑定到主角身上,然后把对应的slider这个血条拖上去就OK。如图:
然后再看子弹,因为子弹要打到人物才会使人掉血,所以子弹上必须有一个检测撞击到人的脚本,如下:
using UnityEngine; using System.Collections; public class knock : MonoBehaviour { /// <summary> /// 子弹碰撞人物时调用人物身上的掉血方法 /// </summary> /// <param name="collision"></param> void OnCollisionEnter(Collision collision) { Debug.Log("hit"); GameObject hit = collision.gameObject; health healths= hit.GetComponent<health>(); if (healths != null) { healths.Takedamage(10); } Destroy(this.gameObject); } }
就这么简单,完成了!
然后就可以测试了,仅在服务器端有掉血效果,客户端不同步。效果如下: