Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class EnemyDetection : MonoBehaviour
- {
- public float detectionRadius = 10f;
- public float moveSpeed = 5f;
- public float rotationSpeed = 180f; // Degrees per second
- public LayerMask targetLayer;
- private Transform player;
- private bool playerDetected = false;
- void Start()
- {
- player = GameObject.FindGameObjectWithTag("Player").transform;
- }
- void Update()
- {
- if (!playerDetected)
- {
- // Check if player is within detection radius
- Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, detectionRadius, targetLayer);
- foreach (Collider2D collider in colliders)
- {
- if (collider.CompareTag("Player"))
- {
- // Player detected, start moving towards and rotating to face the player
- Debug.Log("Enemy detected player!");
- playerDetected = true;
- break;
- }
- }
- }
- else
- {
- // Move towards the player
- Vector2 direction = (player.position - transform.position).normalized;
- transform.Translate(direction * moveSpeed * Time.deltaTime);
- // Rotate towards the player
- float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
- Quaternion targetRotation = Quaternion.Euler(new Vector3(0f, 0f, angle - 90f));
- transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
- }
- }
- void OnDrawGizmosSelected()
- {
- // Draw detection radius in Unity editor
- Gizmos.color = Color.red;
- Gizmos.DrawWireSphere(transform.position, detectionRadius);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement