Files
2026-08-03 22:34:03 +03:00

118 lines
2.9 KiB
C#

using System.Collections;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class Enemy : MonoBehaviour
{
public float startSpeed = 1f;
public float speedIncrease = 0.2f;
public float maxSpeed = 6f;
public int health = 1;
private int currentHealth;
private Vector3 target;
private float currentSpeed;
public int damage = 1;
public int scoreValue = 10;
public float minX = -12f;
public float maxX = 12f;
public float minY = -12f;
public float maxY = 12f;
public AudioClip footstepSound;
private AudioSource audioSource;
private Animator anim;
private Rigidbody2D rb;
SpriteRenderer sr;
public void Setup(int wave)
{
health = Mathf.Clamp(1 + wave / 4, 1, 3);
}
void Start()
{
audioSource = GetComponent<AudioSource>();
rb = GetComponent<Rigidbody2D>();
currentHealth = health;
SetNewTarget();
sr = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
float hpPercent = (float)currentHealth / health;
sr.color = new Color(1f, hpPercent, hpPercent);
if (currentHealth <= 0)
{
FindAnyObjectByType<GameManager>().AddScore(scoreValue);
Destroy(gameObject);
return; // важно: чтобы не запускать корутину на уничтоженном объекте
}
StartCoroutine(HitFlash());
}
void Update()
{
// Тут только логика (флип спрайта, выбор цели)
Vector2 direction = target - transform.position;
if (direction.x > 0)
sr.flipX = false;
else if (direction.x < 0)
sr.flipX = true;
currentSpeed += speedIncrease * Time.deltaTime;
currentSpeed = Mathf.Clamp(currentSpeed, startSpeed, maxSpeed);
if (Vector3.Distance(transform.position, target) < 0.1f)
{
SetNewTarget();
}
}
void FixedUpdate()
{
// Движение через физику
Vector2 newPos = Vector2.MoveTowards(rb.position, target, currentSpeed * Time.fixedDeltaTime);
rb.MovePosition(newPos);
}
void SetNewTarget()
{
float randomX = Random.Range(minX, maxX);
float randomY = Random.Range(minY, maxY);
target = new Vector3(randomX, randomY, 0f);
}
IEnumerator HitFlash()
{
Color original = sr.color;
sr.color = Color.white;
yield return new WaitForSeconds(0.1f);
sr.color = original;
}
void PlayFootstep()
{
if (footstepSound != null)
audioSource.PlayOneShot(footstepSound, 0.02f);
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
anim.SetTrigger("Attack");
}
}
}