Unity3d實現人物跳躍

首先給對象添加剛體和碰撞體。

在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;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章