unity3D 2D简单的怪物自动寻路
适合2D游戏怪物自动寻路,不会攻击人
①首先创建怪物到面板,并添加左右移动坐标点
所谓的左右点就是创建两个空对象,拖到需要移动的位置,当怪物的子物体
②创建脚本拖到怪物上,将左右移动坐标点物体拖入对应位置
效果
代码部分
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class monster_frog : MonoBehaviour 6 { 7 public Rigidbody2D rb; //怪物刚体 8 public Transform pos_left, pos_right; //怪物移动左右坐标 9 public float speed; //移动速速 10 public bool faceLeft = true; //脸朝向 11 public float leftx, rightx; //存储怪物移动左右坐标点 12 13 // Start is called before the first frame update 14 void Start() 15 { 16 rb = GetComponent<Rigidbody2D>(); 17 //断绝当前对象的子父级关系,这样做是为了让子物体的坐标不跟随父物体一起移动 18 transform.DetachChildren(); 19 //获取坐标 20 leftx = pos_left.position.x; 21 rightx = pos_right.position.x; 22 //卸磨杀驴,节省资源 23 Destroy(pos_left.gameObject); 24 Destroy(pos_right.gameObject); 25 } 26 27 // Update is called once per frame 28 void Update() 29 { 30 move(); 31 } 32 33 //移动 34 void move() 35 { 36 //如果脸朝左 37 if (faceLeft) 38 { 39 //就朝左移动,y轴不变 40 rb.velocity = new Vector2(-speed, rb.velocity.y); 41 42 //如果当前坐标小于左侧坐标 43 if (transform.position.x < leftx) 44 { 45 //掉头 -1是往右看 46 transform.localScale = new Vector3(-1, 1, 1); 47 faceLeft = false; 48 } 49 } 50 //如果脸朝右 51 else 52 { 53 //则向右移动 54 rb.velocity = new Vector2(speed, rb.velocity.y); 55 56 //掉头,往左 57 if (transform.position.x > rightx) 58 { 59 transform.localScale = new Vector3(1, 1, 1); 60 faceLeft = true; 61 } 62 } 63 } 64 }
补充:
怪物需要的组件有:
Rigidbody2D
Circle Collider 2D 圆形碰撞器 目的是不让怪物摔倒
剩下就可以添加对应的动画效果
实现后的效果
时间若流水,恍惚间逝去
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?