Using unityengine;using system.collections;///<summary>///script function: NGUI blood bar realization//Knowledge points: ngui,3d coordinates to 2D coordinate conversion// Created: June 29, 2015///Add object: Added to player///</summary>public class hp_2:monobehaviour{//player transform player;// The uipublic of the blood bar Transform the hp_ui;//character (used to fix the position of the blood bar, this empty object is the child of the character) Transform head;//the distance between the main camera and the blood bar float distance;// The Blood bar UI is visible (not visible when the character moves to the outside of the screen) bool Uiiscansee = true;//When the object that mounts the script can be seen in the scene, void Onbecamevisible () {Uiiscansee = true;} void Onbecameinvisible () {Uiiscansee = False when the object on which the script is mounted is not visible in the scene) void Start () {//Gets the player that mounts this script transformplayer = gameobject.transform.getcomponent<transform> ();// Locate the empty object head of the player's head = Player.find ("target"), or calculate the distance between the overhead object and the main camera Distance = Vector3.distance (Head.position, Camera.main.transform.position);} void Update () {///If the player is in sight of the camera, the Blood Bar if (uiiscansee) {Hp_UI.gameObject.SetActive (true) is displayed;} else {Hp_ UI.gameObject.SetActive (false);} Calculates the scale of float newdistance = distance/vector3.distance (head.position, Camera.main.transform.position);//Blood Bar UIcoordinates, which are converted from the coordinates of an empty object above the person's head hp_ui.position = Worldpointtouipoint (head.position);//The scale of the blood bar UI Hp_ui.localscale = Vector3.one * Newdistance;if (Input.getkey (KEYCODE.W)) {gameObject.transform.Translate (vector3.forward);} if (Input.getkey (Keycode.a)) {gameObject.transform.Translate (vector3.left);} if (Input.getkey (KEYCODE.S)) {gameObject.transform.Translate (vector3.back);} if (Input.getkey (KEYCODE.D)) {gameObject.transform.Translate (vector3.right);}} The 3D coordinate of the object in the main camera---the 3D coordinate of the >ui camera public static Vector3 Worldpointtouipoint (Vector3 point) {// The 3D coordinate of the object in the main camera is converted to the 2D coordinate of the main camera Vector3 main_point_2d = Camera.main.WorldToScreenPoint (point);// The 2D coordinates of the object in the main camera are converted to the 3D coordinates of the UI camera Vector3 ui_point_3d = UICamera.mainCamera.ScreenToWorldPoint (main_point_2d);// Object coordinates on the UI do not involve Z-axes, so set to 0ui_point_3d.z = 0;return ui_point_3d;}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Ngui Blood Bar making, when the character does not remove the screen after the actual blood bar, optimize the code