Unity3d 汽车物理系第二篇

  • Post author:
  • Post category:其他



Unity3d物理汽车第二篇


1.第一篇留下的问题,还没有得到解答!我目前的结论就是可以赋值为负值!


2.我自己用了个方块做为车身,然后用四个轮子,把代码套了上去,车子竟然一动不动!


并且出现了以下警告:


MissingComponentException: There is no ‘AudioSource’ attached to the “Cube” game object, but a script is trying to access it.

You probably need to add a AudioSource to the game object “Cube”. Or your script needs to check if the component is attached before using it.

PlayerCar_Script.Update () (at Assets/Scripts/Car Control/PlayerCar_Script.js:48)


我贴出来48行的代码:


audio.pitch = Mathf.Abs(EngineRPM / MaxEngineRPM) + 1.0 ;


就是audio,但是我忘了给物理车添加Audio Source(音频源),导致程序出现警告,导致后面的程序没有执行!


所以,汽车就没有开动了!当大家遇到警告的提示之后,一定要分析原因,检查问题!养成良好的分析问题的习惯,这就是积累经验的时候了!


Audio Source中一个参数pitch是音频源的音调!这里的audio.pitch的最大值是2;


3.现在贴出来车轮与地面碰撞的代码!JS语言写的!


//车轮碰撞器


var CorrespondingCollider : WheelCollider;

//车轮印

var SlipPrefab : GameObject;


//车轮的旋转值

private var RotationValue : float = 0.0;


//更新函数


function Update () {


//光线投射碰撞,用来获取从raycast函数中得到的信息反馈的结构。


var hit : RaycastHit;


//WheelCollider是挂在一个空物体上的Transform上,所以,要用空物体的变换去变换


WheelCollider的中心点(本地坐标的点),这样ColliderCenterPoint就是世界坐标中的点了!


var ColliderCenterPoint : Vector3 = CorrespondingCollider.transform.TransformPoint( CorrespondingCollider.center );


//最主要的部分


//光线投射,从ColliderCenterPoint的位置,向CollesponndingCollider.transform.down方向,发射一条长度为 (车轮悬挂的最大延长距离(suspensionDistance)+车轮碰撞器的半径(radius))的线段!准确的叫线段!返回hit这个信息


if (


Physics.Raycast( ColliderCenterPoint, -CorrespondingCollider.transform.up, hit, CorrespondingCollider.suspensionDistance + CorrespondingCollider.radius ) )


{


//如果这条线段碰撞到了物体!


//设置车轮物体(不是车轮碰撞器)的坐标为碰撞点的坐标+车轮碰撞器的半径

transform.position = hit.point + (CorrespondingCollider.transform.up * CorrespondingCollider.radius);

}else{


//如果没有碰撞,就让车轮物体,不断下落,每帧下落(车轮悬挂的最大延长距离(suspensionDistance))的  距离

transform.position = ColliderCenterPoint – (CorrespondingCollider.transform.up * CorrespondingCollider.suspensionDistance);

}


}


//车轮物体的旋转为 车轮碰撞器所附加的空物体的变换*车轮碰撞器绕x旋转RotationValue,


//绕Y轴旋转steerAngle,绕Z轴旋转0度


WheelCollider.steerAngel返回车轮碰撞器绕自身Y轴旋转的角度


//乘法的顺序很重要,这里的意思,实际中是先后面的旋转,再前面的旋转!


transform.rotation = CorrespondingCollider.transform.rotation * Quaternion.Euler( RotationValue, CorrespondingCollider.steerAngle, 0 );

// 累加RatationValue  每一帧车轮的旋转值为rpm*6*Time.deltaTime

RotationValue += CorrespondingCollider.rpm * ( 360/60 ) * Time.deltaTime;


//WheelHit是有WheelCollider返回的碰撞信息


var CorrespondingGroundHit : WheelHit;


//返回WheelHit

CorrespondingCollider.GetGroundHit( CorrespondingGroundHit );

//WheelCollider.sidewaySlip是侧轮滑动的值,如果这个值大于2.0,则复制一个粒子对象,做为车轮印!

if ( Mathf.Abs( CorrespondingGroundHit.sidewaysSlip ) > 2.0 ) {


if ( SlipPrefab ) {


//复制 , SlipPrefab原物体,WheelCollider.point车轮其它物体碰撞点的位置,Quaternion.identity,不进行任何旋转

Instantiate( SlipPrefab, CorrespondingGroundHit.point, Quaternion.identity );

}

}


我有理解不正确的地方,麻烦指正一下……!


下一篇总结一下,呵呵!

转载于:https://www.cnblogs.com/alongu3d/archive/2012/12/26/wuliche2.html