Unity實(shí)現(xiàn)物體運(yùn)動(dòng)軌跡的繪制
本文實(shí)例為大家分享了unity物體運(yùn)動(dòng)軌跡繪制的具體代碼,供大家參考,具體內(nèi)容如下
① create empty,命名為LineRender
② 在Assects中新建材質(zhì),選擇Shader為Sprites/Default,并設(shè)置軌跡顏色,如下圖:
③ 選擇①中創(chuàng)建的object,添加Line Render屬性,然后將②中新建的材質(zhì)賦給該object,如下圖:
展開Line Render,拖動(dòng)Width可設(shè)置軌跡寬度
④ 創(chuàng)建c#腳本,拖至運(yùn)動(dòng)物體上,代碼如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class draw_orbit : MonoBehaviour { // 繪制軌跡組件 public LineRenderer line; public List<Vector3> points; // 讀取本地txt文件位置信息,改變物體位置 string[] text_buf; int i = 0; // Start is called before the first frame update void Start() { // 物體位置控制方法根據(jù)自己需求來,我這里是從txt文件讀取位置信息然后更新 TextAsset ta = Resources.Load("satellite_orbit") as TextAsset; string text = ta.text; text_buf = text.Split('\n'); } // Update is called once per frame void Update() { try { if (i < text_buf.Length) { // 讀取坐標(biāo)信息 string[] line = text_buf[i].Split(','); float x = Convert.ToSingle(line[0])/1000; float y = Convert.ToSingle(line[1])/1000; float z = Convert.ToSingle(line[2])/1000; // 更新物體位置 transform.position = new Vector3(x, y, z); // 繪制軌跡 AddPoints(); } i++; } catch(Exception ex) { Debug.Log(ex.Message); } } // 繪制軌跡方法 public void AddPoints() { Vector3 pt = transform.position; if (points.Count > 0 && (pt - lastPoint).magnitude < 0.1f) return; if (pt != new Vector3(0, 0, 0)) points.Add(pt); line.positionCount = points.Count; if (points.Count > 0) line.SetPosition(points.Count - 1, lastPoint); } public Vector3 lastPoint { get { if (points == null) return Vector3.zero; return (points[points.Count - 1]); } } }
⑤ 選中運(yùn)動(dòng)物體,可以看到其Script組件中出現(xiàn)Line Render屬性,將①中的object拖進(jìn)去,如下圖:
⑥ 運(yùn)行場景,可以看到如下效果:
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#難點(diǎn)逐個(gè)擊破(9):類型轉(zhuǎn)換
類型之間的轉(zhuǎn)換可以分為隱式轉(zhuǎn)換與顯式轉(zhuǎn)換,如int類型可直接轉(zhuǎn)換為long類型。2010-02-02