unity2D 物体移动以及多段跳跃

针对实现在Unity中对2D物体的移动以及多端跳跃的实现

        在移动方面采用Translate()方法直接移动物体位

        在跳跃方面使用两个bool变量jumpTime和jumpTimes控制跳跃时间和跳跃次数

代码如下:

//定义物体是否在地面状态    
    private bool isGrounded;
    //定义物体脚下位置
    public Transform feetPos;
    //定义碰撞检测范围
    public float checkRadius;
    //定义地面layer
    public LayerMask whatIsGround;

    //定义跳跃力度
    public float jumpForce = 20f;
    //定义水平移动速度
    public float speed = 0.02f ;

    //定义跳跃次数
    public int jumpTimesCounter = 1;
    private int jumpTimes ;

    //定义跳跃时间
    public  float jumpTime;
    private float jumpTimeCounter;

    //定义刚体变量
    Rigidbody2D rb;

    void Start()
    {
        //设置物体的刚体组件
        rb = GetComponent();
    }

     void FixedUpdate()
    {
        //控制水平移动
        float moveInput = Input.GetAxis("Horizontal")*speed;
        transform.Translate(moveInput,0,0);
    }


    void Update()
    { 
        //设置与地面接触状态
        isGrounded = Physics2D.OverlapCircle(feetPos.position,checkRadius,whatIsGround);

        // 处于地面状态时重置跳跃次数
        if (isGrounded)
        {
            jumpTimes = jumpTimesCounter;
        }

        //跳跃次数大于0 时按下space可以跳跃
       if(  Input.GetKeyDown(KeyCode.Space) && jumpTimes > 0)
        {
            //设置跳跃时间
            jumpTimeCounter = jumpTime;
            rb.velocity = Vector2.up * jumpForce;
        }

        //长按space跳得更高
        if (Input.GetKey(KeyCode.Space )&& jumpTimes>0)
        {
            //跳跃时间大于 0 时,可以长跳
            if (jumpTimeCounter > 0 )
            {
                rb.velocity = Vector2.up * jumpForce;
                jumpTimeCounter -= Time.deltaTime;
            }
           
        }

        //抬起space时,跳跃次数减1,跳跃次数为0无法再次跳跃
        if (Input.GetKeyUp(KeyCode.Space) )
        {
            jumpTimes--;
        }
    }

你可能感兴趣的:(unity)