【发布时间】:2019-01-20 02:58:43
【问题描述】:
我有一个脚本可以让敌人在场景中寻找随机物体的区域,如果敌人发现了物体,那么敌人就会向前移动。但是,这不是我希望敌人做的,我希望敌人向目标移动,而不是敌人向前移动,然后一旦敌人到达目标,我希望敌人停止它的移动。我有不同类型的对象,带有不同的标签,所以我认为使用对象的标签名称移动对象不会有效。我希望找到一种使用对象的图层名称将敌人移动到最近的对象的方法,因为我所有的对象都具有相同的图层名称,这意味着无论在场景中生成什么对象,敌人都可以向它移动。当我的敌人看到物体时,有没有办法将其移向物体?谢谢您的帮助!
这是我目前的代码:
public Transform sightStart, sightEnd, sightStart2, sightEnd2;
public Vector3 direction = Vector3.right;
public Vector3 direction2 = Vector3.right;
public float speed = 2f;
public bool spotted = false;
public bool rotate, moveEnemy = false;
public Camera mainCam;
public GameObject EndSight, EndSight2;
void Start () {
speed = 2f;
spotted = false;
rotate = false;
moveEnemy = false;
mainCam = GameObject.Find ("Main Camera").GetComponent<Camera> ();
}
void Update () {
Behaviours ();
if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
direction.x = -1;
InvokeRepeating ("EnemySight", 0, 10f);
if (moveEnemy == false) {
RayCasting ();
Destroy (gameObject, 7f);
}
} else {
direction.x = 1;
InvokeRepeating ("EnemySight", 0, 10f);
if (moveEnemy == false) {
RayCasting2 ();
Destroy (gameObject, 7f);
}
}
}
void EnemySight() {
if (rotate == false) {
if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
EndSight.transform.Translate (direction2 * speed * Time.deltaTime);
direction2.x = 0;
direction2.y = 1;
StartCoroutine (wait1 ());
} else {
EndSight2.transform.Translate (direction2 * speed * Time.deltaTime);
direction2.x = 0;
direction2.y = 1;
StartCoroutine (wait1 ());
}
} else if (rotate == true) {
if (mainCam.WorldToScreenPoint (this.transform.position).x > Screen.width / 2) {
EndSight.transform.Translate (direction2 * speed * Time.deltaTime);
direction2.x = 0;
direction2.y = -1;
StartCoroutine (wait2 ());
} else {
EndSight2.transform.Translate (direction2 * speed * Time.deltaTime);
direction2.x = 0;
direction2.y = -1;
StartCoroutine (wait2 ());
}
}
}
IEnumerator wait1() {
yield return new WaitForSeconds (0.7f);
rotate = true;
}
IEnumerator wait2() {
yield return new WaitForSeconds (0.7f);
rotate = false;
}
void RayCasting()
{
Debug.DrawLine (sightStart.position, sightEnd.position, Color.black);
spotted = Physics2D.Linecast (sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer("Items"));
}
void RayCasting2()
{
Debug.DrawLine (sightStart2.position, sightEnd2.position, Color.black);
spotted = Physics2D.Linecast (sightStart2.position, sightEnd2.position, 1 << LayerMask.NameToLayer("Items"));
}
void Behaviours()
{
if (spotted == true) {
transform.Translate (direction * speed * Time.deltaTime);
speed = 2f;
} else if (spotted == false) {
speed = 0;
}
}
void OnTriggerExit2D (Collider2D col) {
if (col.tag == "object1") {
speed = 0;
CancelInvoke();
}
if (col.tag == "object2") {
speed = 0;
CancelInvoke();
}
if (col.tag == "object3") {
speed = 0;
CancelInvoke();
}
if (col.tag == "object4") {
speed = 0;
CancelInvoke();
}
}
}
【问题讨论】: