3-1. 野猪 - 基本的移动逻辑和动画

野猪实现移动

添加一个 Enemy 类

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

public class Enemy : MonoBehaviour
{
    protected Rigidbody2D rb;
    protected Animator anim;

    [Header("基本参数")]
    public float normalSpeed;
    public float chaseSpeed;
    public float currentSpeed;
    public Vector3 faceDir;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        currentSpeed = normalSpeed;
    }

    private void Update()
    {
        if (transform.localScale.x > 0)
        {
            // 此时野猪是朝左的
            faceDir = new Vector3(-1, 0, 0);
        }
        else if (transform.localScale.x < 0)
        {
            // 此时野猪是朝右的
            faceDir = new Vector3(1, 0, 0);
        }
    }

    private void FixedUpdate()
    {
        Move();
    }

    public virtual void Move()
    {
        rb.velocity = new Vector2(currentSpeed * faceDir.x, rb.velocity.y);
    }
}

根据野猪当前的 localScale.x,修改它刚体的 velocity

野猪增加空闲、走路、跑步动画

切图做动画片段

增加 walk 和 run 这两个 bool 变量,通过这两个变量控制野猪的状态

最后 Boar类 继承 Enemy类,重写 Move 方法

这样就能在播放动画的同时移动了

项目相关代码

代码仓库:https://gitee.com/nbda1121440/2DAdventure.git

标签:20240224_1936

posted @   hellozjf  阅读(56)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示