適合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 圓形碰撞器 目的是不讓怪物摔倒
剩下就可以添加對應的動畫效果
實現后的效果