生活随笔
收集整理的這篇文章主要介紹了
                                
unity画线之模拟小球抛物线运动轨迹
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
 
                                
                            
                            
                            模擬小球的拋物線運動,如圖所示: 
  
 這里有點像打臺球游戲,模擬在發(fā)射之前模擬其軌跡。 
 劃線用的是LineRenderer,不清楚的童鞋可以自行查閱咯。其實也很簡單就是掛個LineRenderer腳本,設(shè)置它的坐標(biāo)點就行了,關(guān)鍵是這坐標(biāo)點如何計算的問題了。 
 高中物理知識,科普一波 首先位移公式,S = V0t+1/2at^2。此次位移的分解,物體在Y軸方向做加速度為重力加速度g的加速運動,在X軸方向勻速運動。則物體在X軸的位移為:Sx=Vxt ,Y軸位移Sy = Vyt+1/2gt^2。 
 知道公式之后,我們就可以按時間點計算物體的位移了,而unity中都是用坐標(biāo)表示那么這種公式轉(zhuǎn)換為代碼的邏輯就更加簡單了:
 
int posCount = 
50;
List<Vector3> posList = 
new List<Vector3>();
for (
int i = 
1; i < posCount ; i++){
float x = Vec0.x * deltaTime*i;
float y = 
1f / 
2f * Physics.gravity.y * Mathf.Pow(deltaTime, 
2) + Vec0.y * deltaTime*i;posList.Add(oldPos + 
new Vector2(x, y));} 
這樣就計算了出來了50個點,將這50個點全部賦值給LineRenderer就基本模擬完成了。
 
 public void SetPoint(List<Vector2> posList){lineRenderer.positionCount = posList.Count;
for (
int i = 
0; i < posList.Count; i++){lineRenderer.SetPosition(i, posList[i]);}} 
為什么要說基本完成呢,這種模擬只是模擬球的最開始的軌跡,在游戲中球會發(fā)生碰撞,碰撞之后會反彈,那么這種反彈的軌跡如何實現(xiàn)呢?如圖: 
  
 首先要知道球在什么時候發(fā)生碰撞,碰撞的面法向量是啥?如果知道面的法向量,入射角那么就可以求出線的反射角了。如何知道在什么時候發(fā)生碰撞呢? 
 這里我用的方法是計算每一段時間球的位移,將這一段時間的位移看作是直線,然后利用unity提供的射線來檢測是否碰撞,這種方法由于每一段是直線所以檢測出來碰撞值也是近似值,當(dāng)然也沒有考慮球碰撞時的摩擦力對球的影響,總之算是一個粗略的解決方法,如果大家有什么更好的方法,希望評論告知,在下感激不盡,首先拋磚迎玉,實現(xiàn)的具體代碼如下:
 
  public List<Vector2> CalculateTrajectory(Vector2 startVel){List<Vector2> posList = new List<Vector2>()Vector2 curPos = Vector2
.zeroVector2 changePos = Vector2
.zerofloat detlaTime =
0.01fVector2 vel0 = startVelVector2 nextPos = Vector2
.zeroint timeCount = 
0Vector2 direction = startVel
.normalizedfor (int i = 
0{//總的時間float time = detlaTime * timeCountfloat 
x = vel0
.x * timefloat 
y = 
1f / 
2f * Physics
.gravity.y * Mathf
.Pow(time, 
2) + vel0
.y * timenextPos = changePos + new Vector2(
x, 
y)// Ray ray = new Ray(curPos + (Vector2)OriginalPos, curSpeedVec)direction = new Vector2(vel0
.x, Physics
.gravity.y * time + vel0
.y)
.normalizedRaycastHit hitif (Physics
.SphereCast(curPos + (Vector2)OriginalPos, ballCollider
.radius, direction, 
out hit, Vector2
.Distance(curPos, nextPos), ~LayerMask
.GetMask(
"Ball"))){Vector2 N = hit
.normalchangePos = nextPosvel0 = new Vector2(vel0
.x, Physics
.gravity.y * time + vel0
.y)vel0 = vel0 - 
2 * (Vector2
.Dot(vel0, N)) * NtimeCount = 
0}timeCount++posList
.Add(curPos + (Vector2)OriginalPos)curPos = nextPos}return posList}
                            
總結(jié)
                            
                                以上是生活随笔為你收集整理的unity画线之模拟小球抛物线运动轨迹的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                            
                                如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。