- Home /
How do you check if a game object is in the radius of another game object?
I am building a merging game where I want to check if a tower of the same kind is placed on the node beside the first one. Basically I want to check if a game object of the same kind is beside the current game object. I have tried different ways that I thought were familiar but have had no progress. (also, this happens within a button output).
My sort of script*
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Merge : MonoBehaviour
{
//a radius that covers 8 nodes
public float nearTurret = 6f;
//the prefab that is going to be merged
public GameObject slingshot;
//On click event =
public void TowerMerge()
{
if () // < I don't know what to put here, what I want to do is (if slingshot is in radius of nearTurret) then ...
{
Debug.Log("Fuse towers");
}
else
{
Debug.Log("No tower near");
}
}
//Radius Gizmos
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(transform.position, nearTurret);
}
}
Answer by tormentoarmagedoom · Feb 12, 2020 at 03:48 PM
Hello there.
You need to calculate the distance between the 2 objects:
if (Vector3.Distance (Object1.tranform.position, Object2.tranform.position) < 100)
{
//Do something because the distance is less than 100
}
IF the number of towers in the map is not very big you can check for all other towers. If you have so many towers, You should create a Trigger collider to detect all towers inside the colliider, and then check for its distance to be sure.
Good Luck!
okay, it kinda works this time the only problem being that it detects itself as a mergeable tower. for example. if I place one tower and hit on fuse then it says "distance to other" 0.05 and then fuses. in that case, it should just do nothing since it should not merge with itself. How can I prevent this?
my code now looks like this
public void Tower$$anonymous$$erge()
{
if (other)
{
float dist = Vector3.Distance(other.position, transform.position);
print("Distance to other: " + dist);
if (dist < 5)
{
Debug.Log("Fused");
}else
{
Debug.Log("No towers nearby");
}
}
}
Just add this to the if conditions:
if (other != gameObject)
$$anonymous$$eaning if "other" is not itself
Bye!
yee, so that didn't work? any more ideas because I am so lost at this point.