Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using UnityEngine;
- //MADE BY LSTHIMO
- public class PlayerAI : Player {
- //Line of sight
- [Header ("Line of sight")]
- public Transform viewport;
- [Space (5)]
- public float viewAngle = 110;
- public float viewRadius = 10;
- public LayerMask detectable;
- public int detectableLayerIndex;
- Collider playerCollider;
- void Start () {
- playerCollider = GetComponent<Collider> ();
- }
- void Update () {
- GetObjectsInSight ();
- }
- List<Collider> detectedColliders = new List<Collider> ();
- void GetObjectsInSight () {
- //Check if there is a detectable object in the view radius
- if (Physics.CheckSphere (viewport.position, viewRadius, detectable)) {
- //Get the detectable objects that are in radius
- Collider[] detectableCollidersArray = Physics.OverlapSphere (viewport.position, viewRadius, detectable);
- //Put the detectable objects in a list
- detectedColliders.RemoveRange(0, detectedColliders.Count);
- foreach (Collider c in detectableCollidersArray) {
- if (c != playerCollider) {
- detectedColliders.Add (c);
- }
- }
- //Check if objects are detectable
- for (int index = 0; index < detectedColliders.Count; index++) {
- //Get collider
- Collider collider = detectedColliders[index];
- //Get angle
- Vector3 selfPosV3 = viewport.position + viewport.forward * viewRadius;
- Vector2 selfPos = new Vector2 (selfPosV3.x, selfPosV3.z);
- Vector2 detectablePos = new Vector2 (collider.transform.position.x, collider.transform.position.z);
- float angle = Vector2.Angle (selfPos, detectablePos);
- //Check if angle is in LOS
- if (angle >= -viewAngle / 2 && angle <= viewAngle / 2) {
- //Set layer to ignore
- int detectableValue = detectable.value;
- detectableValue = ~detectableValue;
- //Check if an object is obstructing the view
- if (Physics.Linecast (viewport.position, collider.bounds.center, detectableValue)) {
- detectedColliders.RemoveAt (index);
- index -= 1;
- }
- } else {
- detectedColliders.RemoveAt (index);
- index -= 1;
- }
- }
- //Sort colliders by distance to viewpoint
- detectedColliders = detectedColliders.OrderBy (point => Vector3.Distance (viewport.transform.position, point.transform.position)).ToList ();
- print ("There are " + detectedColliders.Count + " objects in my LOS");
- }
- }
- float Positive (float input) {
- if (input < 0) {
- return input * -1;
- } else {
- return input;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement