實現簡單的飄血文字,創建一個Cube表示玩家,創建一個Canvas,改成世界模式,放好位置後,將Canvas拖成Cube子物體,創建ShutHurt腳本掛載在Cube身上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ShutHurt : MonoBehaviour
{
//這是一個Text的預製體,在做預製體的時候一定要記得文字居中,否則會有一個偏移量的
public GameObject prefabs;
public Vector3 offset;
//遊戲對象下的子物體Canvas
public Transform canvasTransform;
public float moveSpeed;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
transform.Translate(0, 0, vertical * Time.deltaTime * 5f);
transform.Rotate(0, horizontal * Time.deltaTime * 100f, 0);
if (Input.GetMouseButtonDown(0))
{
GameObject temp = Instantiate(prefabs);
//temp.transform.position = Camera.main.WorldToScreenPoint(this.transform.position) + offset;
//Debug.Log("物體轉化後的屏幕座標" + Camera.main.WorldToScreenPoint(this.transform.position));
//Debug.Log("Text控件的屏幕座標" + temp.transform.position);
//創建一個飄血的UI,設置位置,將canvas拖成cube的子物體
temp.GetComponent<Text>().text = 50.ToString();
temp.transform.SetParent(canvasTransform);
temp.transform.localScale = Vector3.one;
temp.transform.localPosition = Vector3.zero;
}
}
}
先創建一個Text預設體,在Text預設體上添加的腳本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TextController : MonoBehaviour
{
public float speed;
void Start()
{
Destroy(this.gameObject, 1f);
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.up * Time.deltaTime * speed);
}
}