Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.AI;
- public class EnemyMovement : MonoBehaviour
- {
- public float fov = 120f;
- public float loseThreshold = 10f;
- public float viewDistance = 10f;
- public float wonderRadius = 10f;
- public float rotationMultiplyer = 15f;
- private bool isAware = false;
- private bool isDetecting = false;
- private float loseTimer = 0;
- private float playerDistance;
- private Vector3 wanderPoint;
- Transform player;
- NavMeshAgent nav;
- public Transform shoot;
- private void Awake()
- {
- player = GameObject.FindGameObjectWithTag("Player").transform;
- nav = GetComponent<NavMeshAgent>();
- wanderPoint = RandomNavPoint();
- }
- private void Update()
- {
- Chase();
- }
- public void SearchForPlayer()
- {
- if (Vector3.Angle(Vector3.forward, transform.InverseTransformPoint(player.position)) < fov / 2f)
- {
- if (Vector3.Distance(player.position, transform.position) < viewDistance)
- {
- RaycastHit hit;
- if (Physics.Linecast(transform.position, player.position, out hit, -1))
- {
- if (hit.transform.CompareTag("Player"))
- {
- OnAware();
- }
- else
- {
- isDetecting = false;
- }
- }
- else
- {
- isDetecting = false;
- }
- }
- else
- {
- isDetecting = false;
- }
- }
- else
- {
- isDetecting = false;
- }
- }
- public void OnAware()
- {
- isAware = true;
- isDetecting = true;
- loseTimer = 0f;
- }
- public void Chase()
- {
- if (isAware)
- {
- FacePlayer();
- nav.SetDestination(player.position);
- if (!isDetecting)
- {
- loseTimer += Time.deltaTime;
- if (loseTimer >= loseThreshold)
- {
- isAware = false;
- loseTimer = 0f;
- }
- }
- }
- else
- {
- Wander();
- }
- SearchForPlayer();
- }
- void FacePlayer()
- {
- Vector3 direction = (player.position - transform.position).normalized;
- Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
- transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotationMultiplyer);
- }
- public void Wander()
- {
- if (Vector3.Distance(transform.position, wanderPoint) < 5f)
- {
- wanderPoint = RandomNavPoint();
- }
- else
- {
- nav.SetDestination(wanderPoint);
- }
- }
- public Vector3 RandomNavPoint()
- {
- Vector3 randomPoint = (Random.insideUnitSphere * wonderRadius) + transform.position;
- NavMeshHit navHit;
- NavMesh.SamplePosition(randomPoint, out navHit, wonderRadius, -1);
- return new Vector3(navHit.position.x, transform.position.y, navHit.position.z);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement