Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- #if UNITY_EDITOR
- using UnityEditor;
- #endif
- public class EnemyAI : MonoBehaviour {
- public float visualDetectionRadius;
- public float audioDetectionRadius;
- public float peripheral;
- public float turnSpeed = 1f;
- public float speed = 1f;
- // Use this for initialization
- void Start () {
- }
- // Update is called once per frame
- void Update ()
- {
- SpotTarget();
- HearTarget();
- }
- void SpotTarget()
- {
- Collider[] colliders = Physics.OverlapSphere(transform.position, visualDetectionRadius);
- foreach (Collider collider in colliders)
- {
- // check if target is player
- if (collider.CompareTag("Player"))
- {
- //transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(transform.forward, collider.transform.position, turnSpeed, 0f));
- //turn towards the player
- float playerDirection = transform.position.AngleToFaceTarget(collider.transform.position);
- float myFacing = transform.eulerAngles.y;
- if (Mathf.DeltaAngle(myFacing, playerDirection) <= peripheral)
- {
- RaycastHit hit;
- if (Physics.Raycast(transform.position, transform.forward, out hit)
- && hit.transform.CompareTag("Player"))
- {
- Charge();
- }
- LookAtTarget(collider.transform);
- // checking if object exists in front of us && object is tagged player
- }
- }
- }
- }
- void HearTarget()
- {
- Collider[] colliders = Physics.OverlapSphere(transform.position, audioDetectionRadius);
- foreach (Collider collider in colliders)
- {
- // check if target is player
- if (collider.CompareTag("Player"))
- {
- LookAtTarget(collider.transform);
- }
- }
- }
- void LookAtTarget(Transform target)
- {
- //transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(transform.forward, collider.transform.position, turnSpeed, 0f));
- //turn towards the player
- float angleToTurn = transform.position.AngleToFaceTarget(target.position);
- Quaternion newRotation = Quaternion.Euler(0, angleToTurn, 0);
- transform.rotation = Quaternion.RotateTowards(transform.rotation, newRotation, 120f * Time.deltaTime);
- }
- private void Charge()
- {
- // moving forward 1m / second
- transform.position += transform.forward * speed* Time.deltaTime;
- }
- #if UNITY_EDITOR
- void OnDrawGizmos()
- {
- Gizmos.color = Color.black;
- Gizmos.DrawWireSphere(transform.position, visualDetectionRadius);
- Gizmos.color = Color.red;
- Gizmos.DrawWireSphere(transform.position, audioDetectionRadius);
- //Vector3 leftPeripheralTarget = transform.rot(Vector3.forward * visualDetectionRadius).
- //Gizmos.DrawRay(transform.position, ()
- }
- #endif
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement