Enemy chasing player

Viewed 57

I am trying to write a script for an enemy to chase a player for about 2 seconds and then stopping. I want to have the player run into a boxcollider and when this happens the enemy will chase the player for 2 seconds. I've been trying for a while and had no luck. I'm hoping someone with more skill can help me write this code so it works properly using Unity 2d. Thanks

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;
}
1 Answers

Below is my implementation:

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;
}

There are some assumptions I have made. Mainly that the this script belongs on the knight. Also the collider is what interacts with the environment. Meaning physically. If you have a trigger that does the detection you should be using OnTriggerEnter instead of OnCollisionEnter

Related