首先给对象添加刚体和碰撞体。
在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;