我正在尝试编写一个脚本,让敌人追赶玩家大约 2 秒然后停止。我想让玩家遇到一个盒子碰撞器,当这种情况发生时,敌人会追赶玩家 2 秒。我已经尝试了一段时间但没有运气。我希望有更多技能的人可以帮助我编写这段代码,以便它可以使用 Unity 2d 正常工作。谢谢
void Start()
{
var x = 0;
var y = 0;
player = GameObject.Find("Player").GetComponent<PlayerMovement>().playerBox;
}
public void OnCollisionEnter2D(Collision2D collision)
{
//If the player is touching the knights targetting box, then run the command to chase.
if (collision.collider.tag == "Player")
{
isChasing = true;
chase();
}
}
public void chase()
{
if (isChasing)
{
var x = playerTransform.position.x - enemyTransform.position.x;
var y = playerTransform.position.y - enemyTransform.position.y;
knightRB.velocity = new Vector2(x / 20, y / 20);
StartCoroutine(StopChasing());
}
}
IEnumerator StopChasing()
{
yield return new WaitForSeconds(2);
isChasing = false;
}
以下是我的实现:
Transfrom target;
bool isChasing;
float speed = 5;
RigidBody knightRB;
// -----------------------------------------------------------------------------
// Sets up the knight
void Start()
{
target = GameObject.Find("Player").transform;
knightRB = GetComponent<RigidBody>();
}
// -----------------------------------------------------------------------------
//Checks for a collision with the player
void OnCollisionEnter2D(Collision2D collision)
{
//If the player is touching the knights targetting box, then run the command to chase.
if (collision.collider.tag == "Player" && !isChasing)
{
StartCoRoutine(ChaseSequence());
}
}
// -----------------------------------------------------------------------------
// handles the chase
void FixedUpdate()
{
Chase();
}
void Chase()
{
if (!isChasing)
return;
var direction = (target.position - transform.position).normalized;
knightRB.MovePosition(transfrom.position + direction * Time.deltaTime * speed);
}
// -----------------------------------------------------------------------------
// Stops and starts the chase sequence
IEnumerator ChaseSequence()
{
isChasing = true;
yield return new WaitForSeconds(2);
isChasing = false;
}
我做了一些假设。主要是这个剧本属于骑士。对撞机也是与环境相互作用的。物理意义。如果您有一个进行检测的触发器,您应该使用
OnTriggerEnter
而不是 OnCollisionEnter
您可以使用统一的内置导航网格代理,我认为这可以解决您的问题,就像您可以做的那样
_agent = this.GetComponent<NavMeshAgent>();
_player = this.GetComponent<Transform>();
void OnCollisionEnter(Collision collision)
{
_agent.destination = _player.position;
}
我不知道我提供的代码是否适用于您的实例,您可能需要针对您的特定游戏进行修改。