Unity-2D平台游戏 二段跳跃实现

狄新立
2023-12-01

1、定义相关变量

    [Header("Horizontal Movement")]
    public float speedWalk;
    public float speedRun;
    float moveDirection;
    bool isWalking;
    bool isRuning;
    public float directionX;

    [Header( "Vertical Movement" )]
    public float jumpForce;
    public bool isJumping;
    public bool canJump;
    public float amountOfJumps;
    float jumpDelay = 0.25f;
    float jumpTimer;
    float amountOfJumpsLeft;
    bool isCrouching;

    [Header( "Collision" )]
    public bool isGrounded;


    [Header( "Physics" )]
    public float gravity = 1f;
    public float linearDrag=4f;
    public float fallMultiplier = 5f;

    [Header( "Components" )]
    Rigidbody2D ribody;
    Animator animator;
    public LayerMask whatIsGround;
    public Transform [] groundChecks = new Transform [3];

2、编写检测是否在地面函数

    void CheckIsGroud () {
        bool checkResult;
        for(int i = 0; i < 3; i++) {
            checkResult = Physics2D.Linecast( transform.position, groundChecks [i].position, whatIsGround );
            isGrounded = checkResult;
            if (isGrounded)
                break;
        }

    }

3、编写检测能否起跳函数

    void CheckCanJump () {
        if (isGrounded&&ribody.velocity.y<=0) {
            canJump = true;
            isJumping = false;
            animator.SetBool( "IsJumping", isJumping );
            amountOfJumpsLeft = amountOfJumps;
        }

        if (amountOfJumpsLeft<=0) {
            canJump = false;
        }
        if(!isGrounded&&amountOfJumpsLeft>0) {
            canJump = true;
            isJumping = true;
            animator.SetBool( "IsJumping", isJumping );

        }            
       
    }

4、编写跳跃控制函数

    void JumpControl () {

        if (canJump) {
       
                if (Input.GetButtonDown( "Jump" )) {
                    amountOfJumpsLeft--;     
                    isWalking = false;
                    isRuning = false;
                    isJumping = true;
                    animator.SetBool( "IsJumping", isJumping );
                    animator.SetBool( "IsRuning", isRuning );
                    animator.SetBool( "IsWalking", isWalking );
                    ribody.velocity = new Vector2( ribody.velocity.x, 0 );
                ribody.AddForce( Vector2.up * jumpForce, ForceMode2D.Impulse );
           
                }                   
        }
        else {
            
            isJumping = true;
            animator.SetBool( "IsJumping", isJumping );
            
        }

    }

以上,结束!

 类似资料: