using System.Collections; using System.Collections.Generic; using UnityEngine; public…
- User
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Enemy : MonoBehaviour { public float speed = 2f; public float chaseRange = 5f; private Transform player; private Vector2 targetPosition; private Rigidbody2D rb; private Animator anim; private SpriteRenderer spriteRenderer;
codeprivate void Start() { rb = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); spriteRenderer = GetComponent<SpriteRenderer>(); player = GameObject.FindGameObjectWithTag("Player").transform; // Set initial target position as the current position targetPosition = rb.position; } private void Update() { // Calculate the distance to the player float distanceToPlayer = Vector2.Distance(rb.position, player.position); // If the player is within chase range, set player’s position as the target if (distanceToPlayer < chaseRange) { targetPosition = player.position; } else { // If the enemy reached the target position, set a new random target position float distanceToTarget = Vector2.Distance(rb.position, targetPosition); if (distanceToTarget < 0.1f) { targetPosition = GetRandomPosition(); } } // Move towards the target position Vector2 direction = (targetPosition - rb.position).normalized; rb.MovePosition(rb.position + direction * speed * Time.deltaTime); anim.SetFloat("moveX", direction.x); anim.SetFloat("moveY", direction.y); // Flip the sprite horizontally if moving in negative x direction if (direction.x < 0) { spriteRenderer.flipX = true; } else { spriteRenderer.flipX = false; } } private Vector2 GetRandomPosition() { // Get a random position within the map boundaries float x = Random.Range(-5f, 5f); float y = Random.Range(-5f, 5f); return new Vector2(x, y); } - Assistant
Sure, here's an updated version of the script that includes a health variable and destroys the game object when the health reaches 0: