1. 程式人生 > >Unity飄血文字

Unity飄血文字

飄血的文字

這裡寫圖片描述

在Unity場景中新增一個Cube作為怪物,當我們點選滑鼠左鍵的時候產生傷害的文字,然後讓這些文字,慢慢向上移動,然後消失。

using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;

public class ShutHurt : MonoBehaviour {
   //這是一個Text的預製體,在做預製體的時候一定要記得文字居中,否則會有一個偏移量的
    public GameObject prefabs;

    public Vector3 offset;
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"); Vector3 moveDirect = transform.right
* horizontal + transform.forward * vertical; transform.Translate(moveSpeed * moveDirect * Time.deltaTime); if (Input.GetMouseButtonDown(0)) { GameObject temp = GameObject.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); temp.GetComponent<Text>().text = 50.ToString(); temp.transform.SetParent(canvasTransform); } } }

文字移動消失的程式碼

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextController : MonoBehaviour {

    public float speed;

    // Use this for initialization
    void Start () {
        Destroy(this.gameObject, 1f);
    }

    // Update is called once per frame
    void Update () {
        transform.Translate(Vector3.up * Time.deltaTime * speed);
    }
}


下面的圖是在新增Cube移動後的,飄血的文字不會因為物體移動遠了而變小,也不會因為物體移動近了而變大

這裡寫圖片描述