unity 2d 角色顺畅的移动+跳跃+动画切换

参考:https://www.bilibili.com/video/av82865782?t=818

直接贴代码

playerController.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerController : MonoBehaviour
{
    public Rigidbody2D rb;
    public Collider2D coll;
    public Animator anim;
    public float jumpforce ,speed;

    public Transform groundCheck;
    public LayerMask ground;//碰撞体过滤 

    public bool isGround, isJump;

    bool jumpPressed;
    int jumpCount;
    
    
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<Collider2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Jump") && jumpCount > 0)
        {
            jumpPressed = true;
        }
        
    }

    //每秒固定执行的操作,与设备无关
    private void FixedUpdate()
    {
        isGround = Physics2D.OverlapCircle(groundCheck.position, 0.1f, ground);//判断是否在地面
        GroundMovement();
        SwitchAnim();
        Jump();
    }

    //根据输入控制水平方向的移动和以及方向变化
    void GroundMovement()
    {
        float horizontalMove = Input.GetAxisRaw("Horizontal");//只有0 -1 1 三个数字
        rb.velocity = new Vector2(horizontalMove * speed, rb.velocity.y);

        if (horizontalMove != 0)
        {
            transform.localScale = new Vector3(horizontalMove, 1, 1);//控制翻转
        }
       
    }

    void Jump()
    {
        
        if (isGround)
        {
            jumpCount = 2;//在地面的时候就恢复可跳跃次数
            isJump = false;
        }

        if(jumpPressed && isGround)
        {
            isJump = true;
            rb.velocity = new Vector2(rb.velocity.x, jumpforce);
            jumpCount--;
            jumpPressed = false;//每0.02秒检测按键是否松开
            
        }

        else if (jumpPressed && jumpCount > 0 && !isGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpforce);
            jumpCount--;
            jumpPressed = false;
            
        }

    }

    //控制动画转移
    void SwitchAnim()
    {
        //判断是否跑
        anim.SetFloat("running", Mathf.Abs(rb.velocity.x));
        //判断下落还是上跳
        anim.SetFloat("jumping", rb.velocity.y);
        //判断是否返回静止状态
        if (isGround)
        {
            anim.SetBool("idle", true);
        }
        else
            anim.SetBool("idle", false);


    }


   
}

在这里插入图片描述

  • 11
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值