Calculate distance and find nearest object
I'm making a 2D game and want to have the AI enemies find the nearest object with the tag "Friendly" or "Player". The objects with those tags will be constantly moving, so that needs to be taken in account. Heres what I have so far, I just need to figure out how to determine the nearest object, and then set its constant position as a target until it dies or something comes closer.
My code:
private Rigidbody2D bruteRigidBody;
private float test;
private Vector2 center;
public float radius;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
center = transform.position;
PathFinder(center, radius);
}
void PathFinder(Vector2 center, float radius)
{
Collider2D[] enemies = Physics2D.OverlapCircle(center, radius, friendlies);
int i = 0;
while (i < enemies.Length)
{
if(enemies[i].gameObject.tag == "Player")
{
test = Vector3.Distance(center, enemies[i].transform.position);
}
if(enemies[i].gameObject.tag == "Friendly")
{
test = Vector3.Distance(center, enemies[i].transform.position);
}
i++;
}
}
Important note: The line of code that is
Collider2D[] enemies = Physics2D.OverlapCircle(center, radius, friendlies);
is unfinished and I didn't really know what I was doing when I wrote it. The friendlies variable is a layer, and as I said I need it to find gameObjects with tags. I'm not sure how I could change this to find tags.
Not sure this is what you want, but If you want to find tags, use a bunch of Raycasts combined with if other.tag="friendly"
or if other.tag="enemy".
Can you explain a little more? I'm confused on how a Raycast would help
And also, how would I calculate the distance between the characters, and find the closest one?
Answer by OutOfRam · Nov 27, 2016 at 10:04 AM
https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html
Check out the second example on this page, I think it is what you are looking for
Your answer
Follow this Question
Related Questions
Physics Movement without Physics Reactions 1 Answer
Physics2D, impersonate old RigidBody2D "Freeze Position" How? 1 Answer
Calculation errors? 0 Answers
How to make object with velocity bounce off the obstacles? 0 Answers
How can i get a transform to move to another transform if it is touching it? 0 Answers