适合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 圆形碰撞器 目的是不让怪物摔倒
剩下就可以添加对应的动画效果
实现后的效果