Can some one please give me some tips on how to find the 2 nearest objects to the player? I’ve succesfully managed to get the (one) most nearest object to the player but I don’t know how to get the next nearest object. Any tips will be appreciated!
Generally speaking, you’ll need to check the distance (or squared distance) between the player and each object of interest, and then select the objects corresponding to the distances (or squared distances) with the lowest values.
You could use a ‘sort’ function for this, or you could just compute the results directly. The rest is just programming, basically; if you’re having trouble with it though, perhaps you could post what you have so far and describe what problems you’re having exactly.
@ Jesse: Thanks for your reply. The code i’m using is the ‘standaard’ code from the doc’s:
I was thinking of putting the objects in to a array and Sort them based on the distance. This has no succes at the moment. Hope you can give me some tips. Thanks!
if you’re looking for the MMO/RPG targeting with TAB here’s the script i use. Is from BurgZerg Arcade videos, works perfect.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Targeting : MonoBehaviour {
public List<Transform> targets;
public Transform selectedTarget;
private Transform myTransform;
// Use this for initialization
void Start () {
targets = new List<Transform>();
selectedTarget = null;
myTransform = transform;
AddAllEnemies();
}
public void AddAllEnemies()
{
GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject enemy in go)
AddTarget(enemy.transform);
}
public void AddTarget(Transform enemy)
{
targets.Add(enemy);
}
private void SortTargetsByDistance()
{
targets.Sort(delegate(Transform t1, Transform t2) {
return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
});
}
private void TargetEnemy()
{
if(selectedTarget == null)
{
SortTargetsByDistance();
selectedTarget = targets[0];
}
else
{
int index = targets.IndexOf(selectedTarget);
if(index < targets.Count - 1)
{
index++;
}
else
{
index = 0;
}
DeselectedTarget();
selectedTarget = targets[index];
}
SelectTarget();
}
private void SelectTarget()
{
selectedTarget.renderer.material.color = Color.red;
PlayerAttack pa = (PlayerAttack)GetComponent("PlayerAttack");
pa.target = selectedTarget.gameObject;
}
private void DeselectedTarget()
{
selectedTarget.renderer.material.color = Color.blue;
selectedTarget = null;
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Tab))
{
TargetEnemy();
}
}
}
Just asign your enemy with tag “Enemy”. When u press TAB selects the neares enemy, if u hit again TAB you’ll get the next to nearest. The target will become RED if selected, BLUE if deselected.