unity純粹物理驅動方式
首先見官方文件
In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour. Don't set the velocity of an object every physics step, this will lead to unrealistic physics simulation. A typical example where you would change the velocity is when jumping in a first person shooter, because you want an immediate change in velocity.
不要在每一幀中改變物體的剛體速度,否則會導致不真實的物理效果,比如如下程式碼,實際執行時,角色會發生嚴重的抖動
void FixedUpdate() { float horizon=input.getAix("Hozizontal");
rigidebody.Velocity= new Vector2(maxSpeed*horizon,rigidbody.velocity.y);
}
或者
void FixedUpdate() { float horizon=input.getAix("Hozizontal");
rigidebody.Addforce(new vector2(maxForce*horizon));
}
因此不能在幀執行過程中做出任何改變速度的行為,最好的方式是使用物理引擎本身的持續力來實現對物體的推動
//正常運動狀態:跳躍,走動
void NormalMove() {
float j = Input.GetAxis("Jump");
if (grounded && (Input.GetButtonUp("Jump") || j > 0.99f))
{
rigid2D.AddForce(new Vector2(0, j * jumpForce));
}
if (Input.GetKey(KeyCode.D))
{
if (rigid2D.velocity.x < maxSpeed.x) //如果運動的速度小於最大速度,那麼
constantForce2D.force = new Vector2(horizonForce, 0); //讓持續的推動力為預製的力
else constantForce2D.force = new Vector2(0, 0); //如果速度大於等於最大速度,那麼讓推動力為0
}
else if (Input.GetKey(KeyCode.A))
{
if (rigid2D.velocity.x > -maxSpeed.x)
constantForce2D.force = new Vector2(-horizonForce, 0);
else constantForce2D.force = new Vector2(0, 0);
}
else constantForce2D.force = new Vector2(0, 0);
//如果不想讓角色水平運動,那麼設定角色減速,否則讓阻力為0,表示角色掉落或者在運動過程中
if (grounded && !(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D) || Input.GetKeyDown(KeyCode.Space))&&!lockIgnore) rigid2D.drag = 20f;
else rigid2D.drag = 0f;
}
物體的元件設定如下,其中物理材質的屬性全部設定為0,物理檢測為continues,睡眠模式為never sleep,interpolate為Interpolate