当前位置: 首页 > news >正文

Unity类银河战士恶魔城学习总结(P179 Enemy Archer 弓箭手)

教程源地址:https://www.udemy.com/course/2d-rpg-alexdev/

本章节实现了敌人弓箭手的制作

Enemy_Archer.cs

核心功能

  1. 状态机管理敌人的行为

    • 定义了多个状态对象(如 idleStatemoveStateattackState 等),通过状态机管理敌人的状态切换。
    • 状态包括空闲、移动、攻击、跳跃、受击眩晕、死亡等。
  2. 攻击逻辑

    • 使用 AnimationSepcoalAttackTrigger 方法生成箭矢。
    • 创建箭矢对象时,调用 Arrow_Controller.SetUpArrow 为其设置速度和伤害信息。
    • 箭矢会根据面向方向(facingDir)飞向目标。
  3. 地形检测

    • GroundBenhundCheck 方法:检查敌人背后的地面是否存在,通过 Physics2D.BoxCast 实现。
    • WallBehind 方法:检测敌人背后的墙壁是否存在,通过 Physics2D.Raycast 实现。
    • 这些方法用于辅助弓箭手的移动或跳跃逻辑,确保其行为合理。
  4. 受击与死亡

    • CanBeStunned 方法:判断弓箭手是否能被眩晕,并切换到 stunnedState
    • Die 方法:当弓箭手死亡时,切换到 deadState
  5. 可视化调试

    • OnDrawGizmos 方法:在 Unity 编辑器中绘制背后地面检测区域,帮助开发者直观了解地形检测的范围。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;//2024.12.11
public class Enemy_Archer : Enemy
{[Header("弓箭手特殊信息")]//Archer specific info[SerializeField] private GameObject arrowPrefab;[SerializeField] private float arrowSpeed;[SerializeField] private int arrowDamage;public Vector2 jumpVelocity;public float jumpCooldown;public float safeDistance;//安全距离[HideInInspector]public float lastTimeJumped;[Header("额外的碰撞检查")]//Additional collision check[SerializeField] private Transform groundBehindCheck;[SerializeField] private Vector2 groundBehindCheckSize;#region Statespublic ArcherIdleState idleState { get; private set; }public ArcherMoveState moveState { get; private set; }public ArcherBattleState battleState { get; private set; }public ArcherAttackState attackState { get; private set; }public ArcherDeadState deadState { get; private set; }public ArcherStunnedState stunnedState { get; private set; }public ArcherJumpState ArcherJumpState { get; private set; }#endregionprotected override void Awake(){base.Awake();idleState = new ArcherIdleState(this, stateMachine, "Idle", this);moveState = new ArcherMoveState(this, stateMachine, "Move", this);battleState = new ArcherBattleState(this, stateMachine, "Idle", this);attackState = new ArcherAttackState(this, stateMachine, "Attack", this);deadState = new ArcherDeadState(this, stateMachine, "Move", this);stunnedState = new ArcherStunnedState(this, stateMachine, "Stun", this);ArcherJumpState = new ArcherJumpState(this, stateMachine, "Jump", this);}protected override void Start(){base.Start();stateMachine.Initialize(idleState);}public override bool CanBeStunned(){if (base.CanBeStunned()){stateMachine.ChangeState(stunnedState);return true;}return false;}public override void Die(){base.Die();stateMachine.ChangeState(deadState);}public override void AnimationSepcoalAttackTrigger(){GameObject newArrow = Instantiate(arrowPrefab, attackCheck.position, Quaternion.identity);newArrow.GetComponent<Arrow_Controller>().SetUpArrow(arrowSpeed * facingDir, stats);}public bool GroundBenhundCheck() => Physics2D.BoxCast(groundBehindCheck.position, groundBehindCheckSize, 0, Vector2.zero, 0, whatIsGround);public bool WallBehind() => Physics2D.Raycast(wallCheck.position, Vector2.right * -facingDir, wallCheckDistance +2, whatIsGround);protected override void OnDrawGizmos(){base.OnDrawGizmos();Gizmos.DrawWireCube(groundBehindCheck.position, groundBehindCheckSize);}
}

ArcherMoveState.cs

using System.Collections;
using UnityEngine;public class ArcherMoveState : ArcherGroundState
{public ArcherMoveState(Enemy _enemyBase, EnemyStateMachine _stateMachine, string _animBoolName, Enemy_Archer _enemy) : base(_enemyBase, _stateMachine, _animBoolName, _enemy){}public override void Enter(){base.Enter();}public override void Exit(){base.Exit();}public override void Update(){base.Update();enemy.SetVelocity(enemy.moveSpeed * enemy.facingDir, enemy.rb.velocity.y);if (enemy.IsWallDetected() || !enemy.IsGroundDetected())//撞墙或者没有路反转{enemy.Flip();stateMachine.ChangeState(enemy.idleState);}}
}

Arrow_Controller.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;//2024.12.11
public class Arrow_Controller : MonoBehaviour
{[SerializeField] private int damage;//箭矢造成的伤害值[SerializeField] private string targetLayerName = "Player";//箭矢的目标层[SerializeField] private float xVelocity;[SerializeField] private Rigidbody2D rb;[SerializeField] private bool canMove;[SerializeField] private bool flipped;private CharacterStats myStats;private void Update(){if(canMove)rb.velocity = new Vector2(xVelocity, rb.velocity.y);}public void SetUpArrow(float _speed,CharacterStats _myStats){xVelocity = _speed;myStats = _myStats;}private void OnTriggerEnter2D(Collider2D collision){if(collision.gameObject.layer == LayerMask.NameToLayer(targetLayerName)){collision.GetComponent<CharacterStats>().TakeDamage(damage);//箭的伤害myStats.DoDamage(collision.GetComponent<CharacterStats>());//弓箭手的额外属性StuckInto(collision);}else if (collision.gameObject.layer == LayerMask.NameToLayer("Ground")){StuckInto(collision);}}private void StuckInto(Collider2D collision)//射中目标{GetComponentInChildren<ParticleSystem>().Stop();//停止粒子系统GetComponent<Collider2D>().enabled = false;canMove = false;rb.isKinematic = true;//刚体为运动rb.constraints = RigidbodyConstraints2D.FreezeAll;transform.parent = collision.transform;//箭矢的父物体为碰撞物体Destroy(gameObject, Random.Range(5,7));}public void FlipArrow(){if (flipped)return;xVelocity = xVelocity * -1;flipped = true;transform.Rotate(0,180,0);targetLayerName = "Enemy";}
}

ArcherBattleState.cs

using System.Collections;
using UnityEngine;//2024.12.11
public class ArcherBattleState : EnemyState
{private Transform player;private Enemy_Archer enemy;private int moveDir;public ArcherBattleState(Enemy _enemyBase, EnemyStateMachine _stateMachine, string _animBoolName, Enemy_Archer _enemy) : base(_enemyBase, _stateMachine, _animBoolName){this.enemy = _enemy;}public override void Enter(){base.Enter();//player = GameObject.Find("Player").transform;player = PlayerManager.instance.player.transform;if (player.GetComponent<PlayerStats>().isDead)stateMachine.ChangeState(enemy.moveState);}public override void Update(){base.Update();if (enemy.IsPlayerDetected()){stateTimer = enemy.battleTime;if (enemy.IsPlayerDetected().distance < enemy.safeDistance)//小于安全距离{if (CanJump())stateMachine.ChangeState(enemy.ArcherJumpState);//跳走}if (enemy.IsPlayerDetected().distance < enemy.attackDistance){if (CanAttack())stateMachine.ChangeState(enemy.attackState);}}else{if (stateTimer < 0 || Vector2.Distance(player.transform.position, enemy.transform.position) > 10)//超过距离或者时间到了stateMachine.ChangeState(enemy.idleState);}BattleStateFlipController();}private void BattleStateFlipController(){if (player.position.x > enemy.transform.position.x && enemy.facingDir == -1)enemy.Flip();else if (player.position.x < enemy.transform.position.x && enemy.facingDir == 1)enemy.Flip();}public override void Exit(){base.Exit();}private bool CanAttack(){if (Time.time >= enemy.lastTimeAttack + enemy.attackCoolDown){enemy.attackCoolDown = Random.Range(enemy.minAttackCoolDown, enemy.maxAttackCoolDown);enemy.lastTimeAttack = Time.time;return true;}elsereturn false;}private bool CanJump(){if(enemy.GroundBenhundCheck() == false || enemy.WallBehind() ==true)return false;if (Time.time >= enemy.lastTimeJumped + enemy.jumpCooldown){enemy.lastTimeJumped = Time.time;return true;}return false;}
}

ArcherGroundState.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;//2024.12.11
public class ArcherGroundState : EnemyState
{protected Transform player;protected Enemy_Archer enemy;public ArcherGroundState(Enemy _enemyBase, EnemyStateMachine _stateMachine, string _animBoolName,Enemy_Archer _enemy) : base(_enemyBase, _stateMachine, _animBoolName){enemy = _enemy;}public override void Enter(){base.Enter();player = PlayerManager.instance.player.transform;//p63 3:43改}public override void Exit(){base.Exit();}public override void Update(){base.Update();if (enemy.IsPlayerDetected() || Vector2.Distance(enemy.transform.position, player.transform.position) < enemy.agroDistance){stateMachine.ChangeState(enemy.battleState);}}
}

ArcherIdleState.cs

using System.Collections;
using UnityEngine;public class ArcherIdleState : ArcherGroundState
{public ArcherIdleState(Enemy _enemyBase, EnemyStateMachine _stateMachine, string _animBoolName, Enemy_Archer _enemy) : base(_enemyBase, _stateMachine, _animBoolName, _enemy){}public override void Enter(){base.Enter();stateTimer = enemy.idleTime;}public override void Exit(){base.Exit();AudioManager.instance.PlaySFX(24, enemy.transform);}public override void Update(){base.Update();if (stateTimer < 0){stateMachine.ChangeState(enemy.moveState);}}
}

 ArcherStunnedState.cs

using System.Collections;
using UnityEngine;//2024.12.11
public class ArcherStunnedState : EnemyState
{private Enemy_Archer enemy;public ArcherStunnedState(Enemy _enemyBase, EnemyStateMachine _stateMachine, string _animBoolName, Enemy_Archer enemy) : base(_enemyBase, _stateMachine, _animBoolName){this.enemy = enemy;}public override void Enter(){base.Enter();enemy.fx.InvokeRepeating("RedColorBlink", 0, .1f); //这行代码使用 InvokeRepeating 方法,每隔 0.1 秒调用一次 RedColorBlink 方法。stateTimer = enemy.stunDuration;rb.velocity = new Vector2(-enemy.facingDir * enemy.stunDirection.x, enemy.stunDirection.y);}public override void Exit(){base.Exit();enemy.fx.Invoke("CancelColorChange", 0);//Invoke 方法用于在指定的延迟时间后调用某个方法。在这里,延迟时间为 0}public override void Update(){base.Update();if (stateTimer < 0)stateMachine.ChangeState(enemy.idleState);}
}

ArcherAttackState.cs

using System.Collections;
using UnityEngine;public class ArcherAttackState : EnemyState
{private Enemy_Archer enemy;public ArcherAttackState(Enemy _enemyBase, EnemyStateMachine _stateMachine, string _animBoolName, Enemy_Archer _enemy) : base(_enemyBase, _stateMachine, _animBoolName){this.enemy = _enemy;}public override void Enter(){base.Enter();}public override void Exit(){base.Exit();enemy.lastTimeAttack = Time.time;}public override void Update(){base.Update();enemy.SetZeroVelocity();if (triggerCalled)stateMachine.ChangeState(enemy.battleState);}
}

相关文章:

Unity类银河战士恶魔城学习总结(P179 Enemy Archer 弓箭手)

教程源地址&#xff1a;https://www.udemy.com/course/2d-rpg-alexdev/ 本章节实现了敌人弓箭手的制作 Enemy_Archer.cs 核心功能 状态机管理敌人的行为 定义了多个状态对象&#xff08;如 idleState、moveState、attackState 等&#xff09;&#xff0c;通过状态机管理敌人的…...

SpringCloud集成sleuth和zipkin实现微服务链路追踪

文章目录 前言技术积累spring cloud sleuth介绍zipkin介绍Zipkin与Sleuth的协作 SpringCloud多模块搭建Zipkin Server部署docker pull 镜像启动zipkin server SpringCloud 接入 Sleuth 与 Zipkinpom引入依赖 (springboot2.6)appilication.yml配置修改增加测试链路代码 调用微服…...

Python随机抽取Excel数据并在处理后整合为一个文件

本文介绍基于Python语言&#xff0c;针对一个文件夹下大量的Excel表格文件&#xff0c;基于其中每一个文件&#xff0c;随机从其中选取一部分数据&#xff0c;并将全部文件中随机获取的数据合并为一个新的Excel表格文件的方法。 首先&#xff0c;我们来明确一下本文的具体需求。…...

Linux+Docker onlyoffice 启用 HTTPS 端口支持

文章目录 一、需求二、配置2.1 创建容器2.2 进入容器2.3 生成私钥和证书 2.4 测试访问 一、需求 上篇文章介绍了如何搭建一个 onlyoffice 在线预览服务&#xff0c;但是我们实际场景调用该服务的网站是协议是 https 的 &#xff0c;但是 onlyoffice 服务还没做配置&#xff0c…...

在 Visual Studio Code 中编译、调试和执行 Makefile 工程 llama2.c

在 Visual Studio Code 中编译、调试和执行 Makefile 工程 llama2.c 1. Installing the extension (在 Visual Studio Code 中安装插件)1.1. Extensions for Visual Studio Code1.2. C/C1.2.1. Pre-requisites 1.3. Makefile Tools 2. Configuring your project (配置项目)2.1.…...

python中math模块常用函数

文章目录 math模块简介各种三角函数反三角函数取整函数欧几里得距离绝对值最大公约数开根号幂阶乘函数 math模块简介 math模块是python标准库的一部分&#xff0c;提供了对于浮点数相关的数学运算&#xff0c;下面是常用的一些function 各种三角函数反三角函数 math.cos、ma…...

优化 Vue 3 开发体验:配置 Vite 使用 WebStorm 作为 Vue DevTools 的默认编辑器

优化 Vue 3 开发体验&#xff1a;配置 Vite 使用 WebStorm 替代 VS Code 作为 Vue DevTools 的默认编辑器 在 Vue 3 项目开发中&#xff0c;合理配置开发工具可以大大提升我们的工作效率。本文将介绍如何配置 Vite&#xff0c;使其在使用 Vue DevTools 时将默认编辑器从 VS Co…...

【C语言练习(9)—有一个正整数,求是几位数然后逆序打印】

C语言练习&#xff08;9&#xff09; 文章目录 C语言练习&#xff08;9&#xff09;前言题目题目解析结果总结 前言 主要到整数的取余(%)和整数的取商(/)&#xff0c;判断语句if…else if …else的使用 题目 给一个不多于3位的正整数&#xff0c;要求:一、求它是几位数&…...

热敏打印机的控制

首次接触热敏打印机&#xff0c;本来没有特别之处&#xff0c;花了大概十天时间完成一款猫学王热敏打印机&#xff0c;给到客户体验后&#xff0c;客户反馈说打字看起来不明显&#xff0c;打印照片有条纹&#xff0c;所以引起了我对于他的关注&#xff0c;几点不足之处需要优化…...

【closerAI ComfyUI】电商赋能,AI模特套图生产,各种姿势自定义,高度保持人物服饰场景一致性,摆拍街拍专用

closerAIGCcloserAI,一个深入探索前沿人工智能与AIGC领域的资讯平台,我们旨在让AIGC渗入我们的工作与生活中,让我们一起探索AIGC的无限可能性!aigc.douyoubuy.cn 【closerAI ComfyUI】电商赋能,AI模特套图生产,各种姿势自定义,高度保持人物服饰场景一致性,摆拍街拍专用…...

ARM学习(36)静态扫描规则学习以及工具使用

笔者来学习了解一下静态扫描以及其规则,并且亲身是实践一下对arm 架构的代码进行扫描。 1、静态扫描认识 静态扫描:对代码源文件按照一定的规则进行扫描,来发现一些潜在的问题或者风险,因为不涉及代码运行,所以其一般只是发现一些规范或则一些质量问题,当然这些可能存在潜…...

使用 Docker Compose 部署 Redis 主从与 Sentinel 高可用集群

文章目录 使用 Docker Compose 部署 Redis 主从与 Sentinel 高可用集群Redis 主从架构简介Redis Sentinel 简介配置文件1. 主节点配置 (redis-master.conf)2. 从节点配置 (redis-slave1.conf 和 redis-slave2.conf)redis-slave1.confredis-slave2.conf3. Sentinel 配置 (sentin…...

警惕!手动调整服务器时间可能引发的系统灾难

警惕&#xff01;手动调整服务器时间可能引发的系统灾难 1. 鉴权机制1.1 基于时间戳的签名验证1.2 基于会话的认证机制&#xff08;JWT、TOTP&#xff09; 2. 雪花算法生成 ID 的影响2.1 时间戳回拨导致 ID 冲突2.2 ID 顺序被打乱 3. 日志记录与审计3.1 日志顺序错误3.2 审计日…...

MySQL追梦旅途之性能优化

1、索引优化 索引可以显著加速查询操作&#xff0c;但过多或不适当的索引也会带来负面影响&#xff08;如增加写入开销&#xff09;。因此&#xff0c;选择合适的索引至关重要。 创建索引&#xff1a; 为经常用于WHERE子句、JOIN条件和ORDER BY排序的列创建索引。 CREATE I…...

【机器学习】【无监督学习——聚类】从零开始掌握聚类分析:探索数据背后的隐藏模式与应用实例

从零开始掌握聚类分析&#xff1a;探索数据背后的隐藏模式与应用实例 基本概念聚类分类聚类算法的评价指标&#xff08;1&#xff09;内部指标轮廓系数&#xff08;Silhouette Coefficient&#xff09;DB指数&#xff08;Davies-Bouldin Index&#xff09;Dunn指数 &#xff08…...

基于深度Q网络(Deep Q-Network,DQN)的机器人路径规划,可以自定义地图,MATLAB代码

深度Q网络&#xff08;Deep Q-Network&#xff0c;DQN&#xff09;是一种结合了深度学习和Q学习的强化学习算法&#xff0c;由DeepMind在2015年提出。 1. 算法介绍 DQN算法通过使用深度神经网络来近似Q值函数&#xff0c;解决了传统Q-learning在处理具有大量状态和动作的复杂…...

Python-从文件中读取数据-Sat-Sun

10.1 文件读取数据可以整个文件读取&#xff0c;也可以逐行读取。 首先在保存有.py文件的文件夹里创建一个pi_digist.txt文件&#xff0c;文件内容是 3.14 9265 3589执行程序 file_reader.py with open(pi_digist.txt) as file_object: #接受文件名参数&#xff0c;在程序所…...

测试工程师的职业规划

测试人员在管理上的发展 基层测试管理者&#xff1a;测试组长 工作内容&#xff1a;安排小组工作&#xff0c;提升小组成员测试能力&#xff0c;负责重要的测试工作。 负责对象&#xff1a;版本&#xff0c;项目 中层测试管理者&#xff1a;测试经理 负责对象&#xff1…...

使用 Puppeteer 快速上手 Node.js 爬虫

使用 Puppeteer 库通过自动化浏览器来访问百度图片搜索&#xff0c;并在搜索结果中下载图片。代码分为两部分&#xff1a; 自动化浏览器任务&#xff1a;使用 Puppeteer 浏览百度图片搜索并获取图片 URL。图片下载&#xff1a;检查图片 URL 类型&#xff08;base64 或 URL&…...

浏览器的跨域问题与解决方案

浏览器的跨域问题与解决方案 浏览器的跨域问题源于同源策略&#xff08;Same-Origin Policy&#xff09;这一安全机制。同源策略要求两个页面具有相同的协议、域名和端口号&#xff0c;才能相互访问资源和数据。这一机制旨在防止恶意网站执行跨站脚本攻击&#xff0c;从而保护…...

rknn优化教程(二)

文章目录 1. 前述2. 三方库的封装2.1 xrepo中的库2.2 xrepo之外的库2.2.1 opencv2.2.2 rknnrt2.2.3 spdlog 3. rknn_engine库 1. 前述 OK&#xff0c;开始写第二篇的内容了。这篇博客主要能写一下&#xff1a; 如何给一些三方库按照xmake方式进行封装&#xff0c;供调用如何按…...

使用van-uploader 的UI组件,结合vue2如何实现图片上传组件的封装

以下是基于 vant-ui&#xff08;适配 Vue2 版本 &#xff09;实现截图中照片上传预览、删除功能&#xff0c;并封装成可复用组件的完整代码&#xff0c;包含样式和逻辑实现&#xff0c;可直接在 Vue2 项目中使用&#xff1a; 1. 封装的图片上传组件 ImageUploader.vue <te…...

IT供电系统绝缘监测及故障定位解决方案

随着新能源的快速发展&#xff0c;光伏电站、储能系统及充电设备已广泛应用于现代能源网络。在光伏领域&#xff0c;IT供电系统凭借其持续供电性好、安全性高等优势成为光伏首选&#xff0c;但在长期运行中&#xff0c;例如老化、潮湿、隐裂、机械损伤等问题会影响光伏板绝缘层…...

分布式增量爬虫实现方案

之前我们在讨论的是分布式爬虫如何实现增量爬取。增量爬虫的目标是只爬取新产生或发生变化的页面&#xff0c;避免重复抓取&#xff0c;以节省资源和时间。 在分布式环境下&#xff0c;增量爬虫的实现需要考虑多个爬虫节点之间的协调和去重。 另一种思路&#xff1a;将增量判…...

html-<abbr> 缩写或首字母缩略词

定义与作用 <abbr> 标签用于表示缩写或首字母缩略词&#xff0c;它可以帮助用户更好地理解缩写的含义&#xff0c;尤其是对于那些不熟悉该缩写的用户。 title 属性的内容提供了缩写的详细说明。当用户将鼠标悬停在缩写上时&#xff0c;会显示一个提示框。 示例&#x…...

学校时钟系统,标准考场时钟系统,AI亮相2025高考,赛思时钟系统为教育公平筑起“精准防线”

2025年#高考 将在近日拉开帷幕&#xff0c;#AI 监考一度冲上热搜。当AI深度融入高考&#xff0c;#时间同步 不再是辅助功能&#xff0c;而是决定AI监考系统成败的“生命线”。 AI亮相2025高考&#xff0c;40种异常行为0.5秒精准识别 2025年高考即将拉开帷幕&#xff0c;江西、…...

【Java学习笔记】BigInteger 和 BigDecimal 类

BigInteger 和 BigDecimal 类 二者共有的常见方法 方法功能add加subtract减multiply乘divide除 注意点&#xff1a;传参类型必须是类对象 一、BigInteger 1. 作用&#xff1a;适合保存比较大的整型数 2. 使用说明 创建BigInteger对象 传入字符串 3. 代码示例 import j…...

通过 Ansible 在 Windows 2022 上安装 IIS Web 服务器

拓扑结构 这是一个用于通过 Ansible 部署 IIS Web 服务器的实验室拓扑。 前提条件&#xff1a; 在被管理的节点上安装WinRm 准备一张自签名的证书 开放防火墙入站tcp 5985 5986端口 准备自签名证书 PS C:\Users\azureuser> $cert New-SelfSignedCertificate -DnsName &…...

一些实用的chrome扩展0x01

简介 浏览器扩展程序有助于自动化任务、查找隐藏的漏洞、隐藏自身痕迹。以下列出了一些必备扩展程序&#xff0c;无论是测试应用程序、搜寻漏洞还是收集情报&#xff0c;它们都能提升工作流程。 FoxyProxy 代理管理工具&#xff0c;此扩展简化了使用代理&#xff08;如 Burp…...

深度解析:etcd 在 Milvus 向量数据库中的关键作用

目录 &#x1f680; 深度解析&#xff1a;etcd 在 Milvus 向量数据库中的关键作用 &#x1f4a1; 什么是 etcd&#xff1f; &#x1f9e0; Milvus 架构简介 &#x1f4e6; etcd 在 Milvus 中的核心作用 &#x1f527; 实际工作流程示意 ⚠️ 如果 etcd 出现问题会怎样&am…...