首先給對象添加剛體和碰撞體。
在FixedUpdate中寫入如下代碼,不能是Update,因爲是物理屬性,必須要FixedUpdate
GetComponent<Rigidbody>().velocity += new Vector3(0, 5, 0); //添加加速度
GetComponent<Rigidbody>().AddForce(Vector3.up * mJumpSpeed); //給剛體一個向上的力,力的大小爲Vector3.up*mJumpSpeed
完整代碼如下
transform.rotation = Quaternion.LookRotation(Vector3.forward, Vector3.up);
if (Input.GetButtonDown("Jump"))
{
if (ground == true)
{
//transform.Translate(new Vector3(Input.GetAxis("Horizontal")*distance, 2, Input.GetAxis("Vertical")*distance));
GetComponent<Rigidbody>().velocity += new Vector3(0, 5, 0);
GetComponent<Rigidbody>().AddForce(Vector3.up * mJumpSpeed);
ground = false;
Debug.Log("I am Pressing Jump");
}
}
ground用來判斷你是在空中還是地面,如果是在空中,當然不能再讓你跳。
另外如果要取消反衝力,在start方法里加GetComponent<Rigidbody>().freezeRotation = true;