1. 程式人生 > >Unity中不用自帶重力實現跳躍的方法

Unity中不用自帶重力實現跳躍的方法

程式碼分為三部分:

  1. Update()中的輸入判定程式碼
  2. LateUpdate()中的跳躍實現部分
  3. OnCollisionEnter()與OnCollisionExit()的落地&離地檢測部分

當玩家按下跳躍鍵時進入跳躍狀態並判斷當前的水平速度

        //跳躍判定
        if (Input.GetButtonDown("Jump") &&nextJump)            //不能在落地前跳躍
            if (currentBaseState.fullPathHash == walkingState|| 
                currentBaseState.fullPathHash == runningState||
                currentBaseState.fullPathHash == standingState)//不能在動畫完成前跳躍
{ nextJump = false;//落地前無法再次起跳 GameManager.isJumping = true;//進入跳躍狀態 if (GameManager.isStanding) { jumpV_x = 0;//處於站立狀態時水平初速度為0 GameManager.isStanding = false;//改變當前狀態由站立到跳躍,下同 } if
(GameManager.isWalking) { jumpV_x = Haxis * moveSpeed; GameManager.isWalking = false; } if (GameManager.isRunning) //加速跳躍 { jumpV_x = Haxis * moveSpeed; jumpVelocity = GameManager.jumpVelocity * GameManager.jumpMultiple;//加速跳躍時豎向分速度也提高
GameManager.isRunning = false; } }

當跳躍狀態==true時每幀移動相應的豎向,水平距離

    private void LateUpdate()
    {
        transform.Translate(Vector3.right * Time.deltaTime * moveSpeed * Haxis); //角色移動實現
        if (GameManager.isJumping)                   //跳躍實現
        {

            jumpHight += jumpVelocity * Time.deltaTime * jumpSpeed;
            jumpVelocity = jumpVelocity - 9.8f * Time.deltaTime * jumpSpeed;
            currentPosition.y = jumpHight;
            currentPosition.x = privousPosition.x + Time.deltaTime * jumpV_x; //空中水平移動實現
            transform.position = currentPosition;

        }

落地以後退出跳躍狀態,允許進行下次跳躍,並將跳躍速度的全域性變量回歸初始值以便下次跳躍

    void OnCollisionEnter(Collision collider)
    {
        //落地檢測
        if (collider.gameObject.tag == "Ground")
        {
            nextJump = true;
            GameManager.isGround = true;
            GameManager.isJumping = false;

            //落地還原速度
            moveSpeed = GameManager.moveSpeed;           
            jumpVelocity = GameManager.jumpVelocity;
            jumpHight = 0;
            jumpV_x = 0;

            Debug.Log("ground!");
        }
    }
    void OnCollisionExit(Collision collider)
    {
        //離地檢測
        if (collider.gameObject.tag == "Ground")
            GameManager.isGround = false;
        Debug.Log("offground!");
    }