2d平台怪物逻辑
2d来回巡逻
遇到坑会自动转向
可配置单次方向行走的时间,转向等待时间等
using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using UnityEngine; using UnityEngine.Serialization; [RequireComponent(typeof(Rigidbody2D))] public class AI2dPatrol : MonoBehaviour { public Rigidbody2D body2D; public Transform rayPoint;//射线发射点 public float rayLength = 3;//射线长度 public float speed = 4;//怪物速度 public int turnWaitTime;//转向时间 public float oneTime;//走一个方向的时间 public bool autoTurn = true;//遇坑自动转向 private float nowTime = 0; private int moveDir = 1;//移动方向 1为左 public Vector3 curSpeed; private bool isPause = false; private void FixedUpdate() { if (isPause) { return; } Move(); if (oneTime > 0) { if (nowTime >= oneTime) { nowTime = 0; TurnFace(); } nowTime += Time.deltaTime; } if (autoTurn) { RaycastHit2D groundInfo = Physics2D.Raycast(rayPoint.position, Vector2.down, rayLength); if (groundInfo.collider == false) { TurnFace(); } //scene模式下显示射线 Debug.DrawRay(rayPoint.position, Vector2.down * rayLength, Color.blue); } } //转向 async void TurnFace() { isPause = true; await Task.Delay(turnWaitTime * 1000); moveDir = -moveDir; var origin = transform.localScale; transform.localScale = new Vector3(-origin.x, origin.y, origin.z); isPause = false; } //移动 void Move() { //transform.Translate(Vector2.left * speed * Time.deltaTime * moveDir); Vector3 targetVelocity = new Vector2(-moveDir * speed, body2D.velocity.y); body2D.velocity = Vector3.SmoothDamp(body2D.velocity, targetVelocity, ref curSpeed, 0.1f); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~