如何在Unity中使用OnTriggerEnter2D停止AI移动?

时间:2017-12-04 22:46:24

标签: c# unity3d

我正在为Unity中的敌人创建一个基本的AI脚本,我的大部分内容都按照我想要的方式工作。我设置敌人的方式包括2个碰撞器,一个在触碰时摧毁玩家的多边形碰撞器,以及一个空的游戏物体,它是敌人的孩子,是作为触发器的圆形碰撞器。有一个标记为Straight Road的游戏对象,当圆形对撞机与之接触时,它应该运行一个名为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)); } 函数。

{{1}}

1 个答案:

答案 0 :(得分:1)

来自documentation

  

<强> MonoBehaviour.OnTriggerEnter2D(Collider2D)

     

当另一个对象进入连接到此对象的触发器对撞机时发送(仅限2D物理)。

此处的关键字输入。换句话说,触发器用于当碰撞器区域内部时,例如进入地图区域的玩家,其中该区域是触发器对撞机。如果你想在碰撞器碰撞的情况下发生某些事情,即当你的CircleCollider与道路接触时,那么你希望碰撞器不是一个触发器,你想要的功能在OnCollisionEnter2D内。