Untitled
unknown
csharp
a year ago
1.9 kB
148
Indexable
using UnityEngine;
// This script is for an enemy that will follow a player by searching for a 'Player' tag - Gatsby
public class Enemy : MonoBehaviour
{
public float moveSpeed = 2f; // Movement speed of the enemy
private Transform target; // Target to follow (player's transform when detected)
private SpriteRenderer _spriteRenderer;
public void Awake()
{
_spriteRenderer = GetComponent<SpriteRenderer>();
}
private void Update()
{
// If a target is set (player is within range), follow the target
if (target != null)
{
FollowTarget();
}
}
private void FollowTarget()
{
// Calculate direction towards the target
Vector2 direction = (target.position - transform.position).normalized;
_spriteRenderer.flipX = direction.x > 0;
// Move the enemy towards the target
transform.position = Vector2.MoveTowards(transform.position, target.position, moveSpeed * Time.deltaTime);
}
private void OnTriggerEnter2D(Collider2D other)
{
// Check if the collided object has the "Player" tag
if (other.CompareTag("Player"))
{
target = other.transform; // Set the player's transform as the target
}
}
private void OnTriggerExit2D(Collider2D other)
{
// If the player leaves the detection range, clear the target
if (other.CompareTag("Player"))
{
target = null; // Stop following the player
}
}
private void OnDrawGizmosSelected()
{
// Visualize the detection range in the editor using the collider's radius
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, GetComponent<CircleCollider2D>().radius);
}
}
Editor is loading...
Leave a Comment