Тэги:
#unity #tutorial #find #closest #enemy #video #game #devКомментарии:
Hey Man, Thanks for the code. It is detecting the players but for some reason it's not showing the closest enemy.
ОтветитьThank you , after a long trip of research God Bless You
ОтветитьI didn't know what to do, thank you!!
ОтветитьThank you. With some little modifications, You unblocked my issue
ОтветитьThank you so much for this!
ОтветитьFor some reason, it doesn't detect the enemies in the collider. I think I wrote everything perfectly but it still doesn't work.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrackEnemies : MonoBehaviour
{
public List<GameObject> enemies = new List<GameObject>(); //The enemies player detection collider is touching
public GameObject closestEnemyInDirection; // The closest enemy in the direction the player is facing
public Transform body; //The body the player using to find as the player
private void Start()
{
}
public void FindClosestGameObject()
{
GameObject closest = null;
float distance = 41.0f;
Vector3 position = body.transform.position;
foreach (GameObject go in enemies)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
closestEnemyInDirection = closest;
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Enemy")
{
for (int i = 0; i < enemies.Count; i++)
{
if (other.gameObject == enemies[i])
{
return;
}
}
enemies.Add(other.gameObject);
FindClosestGameObject();
Debug.Log("ye");
}
}
private void OnTriggerExit(Collider other)
{
if(other.tag == "Enemy")
{
for (int i = 0; i < enemies.Count; i++)
{
if (other.gameObject == enemies[i])
{
if(enemies[i] == closestEnemyInDirection)
{
closestEnemyInDirection = null;
}
enemies.RemoveAt(i);
}
}
}
}
}
This is actually awesome, and for some reason really hard to find. Most tutorials focus on the closes enemy period, but games usually allow focus to closes enemies on a specific direction (hack and slashes, or detecting closest points based on camera angle...). Thanks for the code!
ОтветитьLike
Ответить