Created
September 21, 2022 03:36
-
-
Save townofdon/27bbf5edbe8a89b9b7a2ea7227a62e61 to your computer and use it in GitHub Desktop.
Enemy Sight Cone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using UnityEngine; | |
public class AIController : MonoBehaviour { | |
[SerializeField][Range(0f, 20f)] float sightRange = 5f; | |
[SerializeField][Range(0f, 1f)] float sightAngle = 0.3f; | |
GameObject player; | |
Vector3 headingToPlayer; | |
Vector3 sightHeading; | |
void Start() { | |
StartCoroutine(CFindPlayer()); | |
} | |
void Update() { | |
AttackBehaviour(); | |
} | |
private void AttackBehaviour() { | |
if (IsPlayerInSight()) { | |
// attack player | |
} else { | |
// resume patrol / guard / whatever | |
} | |
} | |
bool IsPlayerInSight() { | |
if (!player == null) return false; | |
if (Vector3.Distance(transform.position, player.transform.position) > sightRange) return false; | |
headingToPlayer = (player.transform.position - transform.position).normalized; | |
sightHeading = transform.forward; | |
if (Vector3.Dot(sightHeading, headingToPlayer) < (1 - sightAngle)) return false; | |
// could also perform a raycast here to make sure that nothing is obscuring the player from sight | |
return true; | |
} | |
void OnDrawGizmos() { | |
Gizmos.color = Color.blue; | |
if (IsPlayerInSight()) Gizmos.color = Color.red; | |
Gizmos.DrawWireSphere(transform.position, sightRange); | |
// note - these lines do not extend all the way to the edge of the wire sphere - simple fix would be normalizing and then multiplying each result by sightRange | |
Gizmos.DrawLine(transform.position, transform.position + transform.forward * sightRange * (1 - sightAngle) + transform.right * sightRange * sightAngle); | |
Gizmos.DrawLine(transform.position, transform.position + transform.forward * sightRange * (1 - sightAngle) - transform.right * sightRange * sightAngle); | |
Gizmos.DrawLine(transform.position, transform.position + transform.forward * sightRange * (1 - sightAngle) + transform.up * sightRange * sightAngle); | |
Gizmos.DrawLine(transform.position, transform.position + transform.forward * sightRange * (1 - sightAngle) - transform.up * sightRange * sightAngle); | |
} | |
IEnumerator CFindPlayer() { | |
while (true) { | |
yield return new WaitForSeconds(0.25f); | |
if (player != null) continue; | |
player = GameObject.FindWithTag("Player"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment