using System.Collections;
using System.Collections.Generic;
using UnityEngine;<img src="https://habrastorage.org/webt/66/fd/3c/66fd3caf7ab9f607750350.png" alt="image"/>
using UnityEngine.UI;
using TMPro;
public class Enemy : MonoBehaviour
{
[Header("Parameters Health")]
public float maxHealth;
private float health;
public Slider healthSlider;
public TMP_Text healthText;
[Header("Parameters")]
public float normalSpeed;
private float speed;
public Player pl;
public Animator anim;
[Header("Positions")]
public Transform player; // переменная для хранения игрока
public Transform enemy; // переменная для хранения врага
public GameObject enemyObject;
[Header("Attack")]
public float timeAttack;
private float isTimeAttack;
public Transform attackPoint;
public LayerMask playerLayers;
public float attackRange = 1f;
public int attackDamage = 10;
[Header("Loot")]
public int MaxMoney;
public int MinMoney;
public int enemyMoney;
void Start()
{
health = maxHealth;
speed = normalSpeed;
anim = GetComponent<Animator>();
isTimeAttack = timeAttack;
enemyMoney = Random.Range(MinMoney, MaxMoney);
}
void Update()
{
Vector3 playerPos = player.position;
Vector3 enemyPos = enemy.position;
if (playerPos.x < enemyPos.x) // игрок находится слева от врага
{
enemyObject.transform.localScale = new Vector3(-1, 1, 1); // поворачиваем врага влево
}
else // игрок находится справа от врага
{
enemyObject.transform.localScale = new Vector3(1, 1, 1); // поворачиваем врага вправо
}
float distance = Vector2.Distance(playerPos, enemyPos); // Растояние от врага до Игрока
transform.position = Vector3.MoveTowards(transform.position, playerPos, speed * Time.deltaTime);
if (isTimeAttack > 0)
{
isTimeAttack -= Time.deltaTime;
}
if (distance < 1.5f) // Остановка врага
{
speed = 0;
if (isTimeAttack <= 0) // Атака
{
anim.SetTrigger("Attack");
isTimeAttack = timeAttack;
}
}
else
{
anim.SetTrigger("Run");
speed = normalSpeed;
}
if (health <= 0) // Смерть врага
{
pl.money += enemyMoney;
Destroy(gameObject);
}
HealthBar();
}
public void TakeDamage(int damage)
{
health -= damage;
}
void HealthBar()
{
healthSlider.maxValue = maxHealth;
healthSlider.minValue = 0;
healthSlider.value = health;
healthText.text = health + "/" + maxHealth;
}
public void Attack()
{
Collider2D[] players = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, playerLayers);
Debug.Log("1");
for (int i = 0; i < players.Length; i++)
{
// Нанесение урона врагу
players[i].GetComponent<Player>().TakeDamage(attackDamage);
Debug.Log("2");
}
}
private void OnDrawGizmosSelected()
{
if (attackPoint == null)
return;
Gizmos.DrawWireSphere(attackPoint.position, attackRange);
}
}
public void SetTarget(Transform target)
{
player = target;
}
GameObject newEnemy = Instantiate(_enemy.gameObject);
newEnemy.GetComponent<Enemy>().SetTarget(_player.transform);
Transform player == (Player)pl.gameObject.transform
Transform enemy ==this.transform == enemyObject.transform