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!");
    }

你可能感兴趣的:(unity)