Advertisement
Krythic

ChatGPT Enemy Detection Script (Untested)

May 6th, 2024
721
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.83 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class EnemyDetection : MonoBehaviour
  4. {
  5.     public float detectionRadius = 10f;
  6.     public float moveSpeed = 5f;
  7.     public float rotationSpeed = 180f; // Degrees per second
  8.     public LayerMask targetLayer;
  9.  
  10.     private Transform player;
  11.     private bool playerDetected = false;
  12.  
  13.     void Start()
  14.     {
  15.         player = GameObject.FindGameObjectWithTag("Player").transform;
  16.     }
  17.  
  18.     void Update()
  19.     {
  20.         if (!playerDetected)
  21.         {
  22.             // Check if player is within detection radius
  23.             Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, detectionRadius, targetLayer);
  24.             foreach (Collider2D collider in colliders)
  25.             {
  26.                 if (collider.CompareTag("Player"))
  27.                 {
  28.                     // Player detected, start moving towards and rotating to face the player
  29.                     Debug.Log("Enemy detected player!");
  30.                     playerDetected = true;
  31.                     break;
  32.                 }
  33.             }
  34.         }
  35.         else
  36.         {
  37.             // Move towards the player
  38.             Vector2 direction = (player.position - transform.position).normalized;
  39.             transform.Translate(direction * moveSpeed * Time.deltaTime);
  40.  
  41.             // Rotate towards the player
  42.             float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
  43.             Quaternion targetRotation = Quaternion.Euler(new Vector3(0f, 0f, angle - 90f));
  44.             transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
  45.         }
  46.     }
  47.  
  48.     void OnDrawGizmosSelected()
  49.     {
  50.         // Draw detection radius in Unity editor
  51.         Gizmos.color = Color.red;
  52.         Gizmos.DrawWireSphere(transform.position, detectionRadius);
  53.     }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement