unity 使用LineRenderer實(shí)現(xiàn)飄帶飛舞的效果
2018年02月11日 12:08:36?劉峰1011?閱讀數(shù):1693
核心就是控制飄帶上的每一個(gè)點(diǎn),計(jì)算出相應(yīng)的位置,然后使用LineRenderer把這些點(diǎn)連成線。
首先創(chuàng)建一個(gè)物體作為飄帶的父物體,這里我使用了一個(gè)簡單的Sphere。
然后給父物體添加Line Render腳本:
賦予Line Render一個(gè)材質(zhì)球,否怎Line Render會(huì)顯示為洋紅色,調(diào)整Line Render的一些屬性,這里我把width屬性改為0.3,原來的1會(huì)讓我們的線看起來不那么苗條。
然后創(chuàng)建我們的腳本,首先創(chuàng)建一個(gè)飄帶中的控制點(diǎn)的腳本,它只是簡單的用來讓控制點(diǎn)能夠跟隨自己前面的物體:
usingSystem.Collections;
usingSystem.Collections.Generic;
usingUnityEngine;
publicclassFloatLinePoint:MonoBehaviour{
publicGameObject parentObj;
constfloatspeed =0.7f;
// Use this for initialization
voidStart(){
}
// Update is called once per frame
voidUpdate(){
? ? ? ? transform.position = transform.position +
((parentObj.transform.position +newVector3(FloatLineManager.pointdis,0,0)) -? transform.position) * speed;
}
}
然后創(chuàng)建飄帶的控制腳本
usingSystem.Collections;
usingSystem.Collections.Generic;
usingUnityEngine;
publicclassFloatLineManager:MonoBehaviour{
? ? LineRenderer lr;
List objList =newList();
//頂點(diǎn)數(shù)量
[SerializeField,Range(1,100)]publicintpointcount =20;
//頂點(diǎn)距離
[SerializeField, Range(0.01f, 1f)]publicstaticfloatpointdis =0.3f;
// Use this for initialization
voidStart(){
? ? ? ? lr = gameObject.GetComponent<LineRenderer>();
? ? ? ? lr.positionCount = pointcount;
//生成頂點(diǎn)
for(inti =0; i < pointcount; i++)
? ? ? ? {
GameObject obj =newGameObject(i+"");
obj.transform.position =newVector3(transform.position.x + (float)i * pointdis,transform.position.y,0);
? ? ? ? ? ? objList.Add(obj);
? ? ? ? ? ? FloatLinePoint point = obj.AddComponent<FloatLinePoint>();
if(i ==0){
? ? ? ? ? ? ? ? point.parentObj = gameObject;
}else{
point.parentObj = objList[i -1];
? ? ? ? ? ? }
? ? ? ? }
}
// Update is called once per frame
voidUpdate(){
Vector3[] vs =newVector3[objList.Count];
for(inti =0; i < objList.Count; i ++){
? ? ? ? ? ? vs[i] = objList[i].transform.position;
? ? ? ? }
? ? ? ? lr.SetPositions(vs);
}
}
Start中我們根據(jù)聲明的pointcount變量的值來創(chuàng)建相應(yīng)的控制點(diǎn),然后在Update中獲取控制點(diǎn)的坐標(biāo),并實(shí)時(shí)賦予Line Render,這樣我們就可以得到一個(gè)基礎(chǔ)的飄帶效果,我們可以通過調(diào)節(jié)FloatLinePoint中的speed參數(shù)來修改飄帶的幅度:
但是現(xiàn)在看起來飄的不是很明顯,而且我想要的是有風(fēng)吹動(dòng)的效果,所以還需要繼續(xù)修改我們的代碼: