So for my top-down RPG, there are enemies in the overworld that will chase you if you get too close. (Like most turn-based RPGs nowadays.) The way it works is that the enemy spawner instantiates enemies at a random position at the start of the scene. That’s not the problem, but the problem is the enemy overworld script itself.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyOverworld : MonoBehaviour
{
[Header("Details")]
public BattleChar[] enemiesInArea;
public int musicToPlay;
public int maxAmountOfEnemies;
public bool cannotFlee;
public bool boss;
[SerializeField] private Rigidbody2D m_Rigigbody;
[Header("Overworld Details")]
public float speed;
Vector3 dirToPlayer;
public bool chase = false;
void FixedUpdate()
{
if (!GameManager.instance.battleActive && chase)
{
dirToPlayer = (CameraController.instance.target.position - transform.position).normalized;
if (dirToPlayer.magnitude > 0)
{
m_Rigigbody.MovePosition(Vector2.MoveTowards(m_Rigigbody.position, CameraController.instance.target.position, speed * Time.deltaTime));
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (!chase)
{
chase = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (chase)
{
float wait = 1;
while (wait > 0)
{
wait -= Time.deltaTime;
}
chase = false;
}
}
public IEnumerator StartBattleCo()
{
List<string> enemies = new();
UIFade.instance.FadeToBlack();
GameManager.instance.battleActive = true;
int amount = 1;
if (!boss)
{
amount = Random.Range(1, maxAmountOfEnemies);
}
for (int i = 0; i < amount; i++)
{
int enemy = Random.Range(0, enemiesInArea.Length);
if (enemiesInArea[enemy].rareEnemy)
{
int chance = Random.Range(0, enemiesInArea[enemy].rarity * 10);
if (chance <= enemiesInArea[enemy].rarity)
{
enemies.Add(enemiesInArea[enemy].charName);
}
else
{
i = i--;
}
}
else
{
enemies.Add(enemiesInArea[enemy].charName);
}
}
yield return new WaitForSeconds(1.5f);
BattleManager.instance.BattleStart(enemies.ToArray(), cannotFlee, boss, musicToPlay);
UIFade.instance.FadeFromBlack();
enemies.Clear();
Destroy(gameObject);
}
}
When the enemy chases the player, they’ll always overlap one another.
Each enemy has a solid capsule collider and a circle collider that’s a trigger for the battle ienumerator. I’ve tried different methods like translating the position instead of using MoveTowards, but it’s not working.