[英]How do I stop AI movement with OnTriggerEnter2D in Unity?
我正在為Unity中的敵人創建一個基本的AI腳本,並且大部分腳本都按照我想要的方式工作。 我設置敵人的方式包含2個對撞機,一個多邊形對撞機,在碰觸時會摧毀玩家,以及一個空的游戲對象,它是敵人的孩子,而圓形對撞機則作為觸發對象。 有一個標記為“ Straight Road
的游戲對象,當圓碰撞器與之接觸時,它應該運行一個名為StopMovement();
的函數StopMovement();
將敵人的運動設置為0。我以前使用Debug.Log();
檢查對撞機是否識別出它在碰Straight Road
,而沒有。 這是我的下面的代碼。 我希望有人提出建議。
public class DogAI : GenericController {
public Transform target;
public float chaseRange;
public float maxDistance;
private Vector3 targetDirection;
private float targetDistance;
// Use this for initialization
void Start()
{
base.Start();
}
// Update is called once per frame
void Update()
{
base.Update();
if (target.transform != null)
{
targetDirection = target.transform.position - transform.position;
targetDirection = targetDirection.normalized;
targetDistance = Vector3.Distance(target.position, transform.position);
if (targetDistance <= chaseRange)
{
SetMovement(targetDirection);
}
Vector3 enemyScreenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (targetDistance > maxDistance)
{
Destroy(gameObject);
}
}
}
void StopMovement()
{
SetMovement(new Vector2(0,0));
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Straight Road"))
{
Debug.Log("Stop! There's a road!");//This never shows up in the log?
StopMovement();
}
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Player"))
{
DestroyObject(other.gameObject);
}
}
下面的通用控制器腳本包含SetMovement()
函數。
public abstract class GenericController : MonoBehaviour
{
public float movementSpeed = 20;
float animationSpeed = 1;
protected Rigidbody2D rigidbody;
protected Animator animator;
Vector2 movementVector;
float currentSpeed;
protected bool needAnimator = true;
// Use this for initialization
protected void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
if (needAnimator)
{
animator = GetComponent<Animator>();
animator.speed = animationSpeed;
}
}
protected void FixedUpdate()
{
rigidbody.velocity = movementVector;
currentSpeed = rigidbody.velocity.magnitude;
if (needAnimator)
animator.SetFloat("Speed", currentSpeed);
}
public void SetMovement(Vector2 input)
{
movementVector = input * movementSpeed;
}
public void SetMovement(int x, int y)
{
SetMovement(new Vector2(x, y));
}
從文檔中 :
MonoBehaviour.OnTriggerEnter2D(Collider2D)
當另一個對象進入連接到該對象的觸發對撞機時發送(僅限2D物理)。
此處的關鍵字是enter 。 換句話說,觸發是當出現對撞機的區域內 ,就像進入地圖,這里的區域是一個觸發對撞機的一個區域的球員。 如果您希望在碰撞器與道路碰撞時發生某些事情,即當CircleCollider
與道路接觸時,那么您希望碰撞器不是觸發器,並且希望功能位於OnCollisionEnter2D內部。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.