Enemy Chase Script

Hello! I am creating a game in which a player must wander a forest to find a car to escape with. However, there is meant to be a monster that will chase the player through the woods, and it’s meant to have a line of sight that it can see you with so that I can make it faster than the player, but make it so that you can lose it by breaking line of sight through the trees. I’m VERY new to Unity, and I’m just making this project for fun, so I’m not sure how to create a script for this, or if there’s something else I’m meant to do.

using UnityEngine;
public class SeekAndChase : MonoBehaviour  // Monster script for a rigidbody capsule
{
Rigidbody rb; // Add a low friction physics material to the monster's collider to help prevent the monster from snagging onto a tree
public Transform player; // Use the editor to drag the player object onto this

    void Start()
    {
        rb=GetComponent<Rigidbody>();
        rb.drag=1;
        rb.freezeRotation=true;
    }

    void FixedUpdate()
    {
        Vector3 target=transform.position+transform.forward+transform.right*Time.deltaTime; // Look around for the player
        Vector3 playerDirection=player.position-transform.position;
        if (Vector3.Dot(playerDirection.normalized,transform.forward)>0.5f && playerDirection.magnitude<50)// player within our field of view?
            if (Physics.Raycast(transform.position,playerDirection,out RaycastHit hit,50)) // What's between us and the player?
                if (hit.transform.CompareTag("Player")) // Just the player ahead?
                    target=player.position; // make the player our target
                   
        if (playerDirection.magnitude<1.5f)    // have we reached the player?
            UnityEditor.EditorApplication.isPlaying=false;  // Quit the game (in editor only)

        Vector3 targetDirection=(target-transform.position).normalized;
        rb.AddForce(targetDirection*10); // head towards the target position (10 is the speed)
        rb.MoveRotation(Quaternion.LookRotation(targetDirection)); // look towards the target
    }
}
1 Like

I greatly appreciate your help, and was wanting to ask a follow up question. How could I learn more about scripting? I’m wanting to pursue this further, but I’m not sure how to properly learn and digest all of the different systems and how to code solutions for problems.

Creating and using scripts.

1 Like