Враги заходят в друг друга unity 2D
Когда я начинаю убегать от врагов(у меня отвечает отдельный скрипт за их спавн), они как-бы сливаются друг с другом и в итоге все находятся в одном враге(то есть может показаться что там не 5 врагов, а 1). Возможно это связанно с transform, но я не знаю.
Код:
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour
{
public float seeDistance = 2f;
public float attackDistance = 2f;
public float speed;
float speed2;
public Rigidbody2D rb;
Transform target;
public GameObject deathEffect;
void Start()
{
target = GameObject.FindWithTag("Player").GetComponent<Transform>();
speed2 = speed;
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
if (!die)
{
Target();
FollowPlayer();
}
}
private void Target()
{
if (target == null)
{
Start();
}
}
private void FollowPlayer()
{
var dir = (target.position - transform.position).normalized;
rb.velocity = dir * speed;
if (Vector2.Distance(transform.position, target.transform.position) <= seeDistance && Vector2.Distance(transform.position, target.transform.position) > attackDistance)
{
speed = speed2;
EnemyFlip();
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.fixedDeltaTime);
}
else if (Vector2.Distance(transform.position, target.transform.position) <= attackDistance)
{
speed = 0;
}
if (Hp == 0)
{
Die();
}
}
private bool horizontalMove = true;
private void EnemyFlip()
{
if (target.transform.position.x > gameObject.transform.position.x && !horizontalMove)
{
horizontalMove = !horizontalMove;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
else if (target.transform.position.x < gameObject.transform.position.x && horizontalMove)
{
horizontalMove = !horizontalMove;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
public int Hp;
bool die = false;
private void Die()
{
die = true;
Vector3 theScale = transform.localScale;
if (theScale.x > 0)
{
gameObject.transform.Rotate(0, 0, 90);
}
else if (theScale.x < 0)
{
gameObject.transform.Rotate(0, 0, 270);
}
gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll;
speed = 0;
}
public void TakeDamage(int damage)
{
Instantiate(deathEffect, transform.position, Quaternion.identity);
Hp -= damage;
}
private float timeAttack;
public float startTimeAttack;
public int damage;
public void OnTriggerStay2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
if (timeAttack <= 0)
{
}
else
{
timeAttack -= Time.deltaTime;
}
}
}
}
Ответы (2 шт):
Автор решения: Риксед
→ Ссылка
Если игра Top-Down: Добавь врагам Collider и Rigidbody2D, отключи в Rigidbody2D использование гравитации, и включи FreezeRotation, а если игра платформер: Добавь врагам Collider и Rigidbody2D
Автор решения: Korsakov Lev
→ Ссылка
Итог: если у кого-то будет такая же проблема, то просто отключите freeze position и включайте в случае крайней необходимости :)