unity2D:如何实现二段跳?

注:该文为学习笔记,具体请看b站upM-Studio的unity教程2D入门

环境:unity2020.3

本节内容:改善跳跃手感,并实现二段跳

先说一下概念,听不懂没事,看下完整代码就懂了

跳跃手感改善

一般原因是因为update和FixedUpdate的一些内容不配套

比如FIxedupdate需要乘time.fixeddeltatime

另外,Player一定是在地面上才可以进行跳跃的,所以需要判断Player是否在地面上

从之前的Coll.IsTouchingLayers(Groud)改成Physics2D.OverlapCircle(GroundCheck.position,0.2f,Groud);

赋值跳跃初速度的时候没有乘时间所以放在update中更新:rb.velocity=Vector2.up*Jumpforce;

二段跳

搞一个int变量专门计数,每次踩到地面,就让它重新变成1,每跳跃一次-1,跳的同时判断是否大于0,如果小于0说明没有跳跃的机会了

完整代码如下:

    //jump
    public float  Jumpforce;//跳跃力度
    public Transform GroundCheck;//为了改善手感的,没有也可以啦
    private bool isGround;//用于判断是否能进行跳跃操作
    private int extraJump;//二段跳

    void FixedUpdate()
    {
        isGround=Physics2D.OverlapCircle(GroundCheck.position,0.2f,Groud);
    }
    
    void Update()
    {
        Jump();
    }


    //跳跃
    void Jump()
    {
        //二段跳 要放在update里面 因为没×fixedDeltaTime
        if(isGround)
        {
            extraJump=1;//踩在地面上的时候,可以跳两次       
        }
        if(Input.GetButtonDown("Jump")&&extraJump>0)
        {
            rb.velocity=Vector2.up*Jumpforce;//相当于new Vector2(0,1)
            extraJump--;
            Anim .SetBool("jumping",true);
            jumpAudio.Play();            
        }
    }

猜你喜欢

转载自blog.csdn.net/karonneveralone/article/details/120010593#comments_20232489