How to find the distance between unknown object and player
Hi :) I'm creating simulator of my neighborhood, I used "real world terrain assest that build me the terrain and the buildings. I have a player that can move in the area, now I want to know the distance between my player to the building he looks at. the building made with diffrent mashes (over 200), right know thay dont have any coliders or rigidbody I thought to send an empty object until it collids with a building or the terrain then use the distance function. But I dont know wich collider to use? how to assign them without moving one by one?
Answer by highpockets · Mar 08, 2021 at 10:10 PM
First of all you should put a collider on the buildings, a mesh collider will be most accurate, but also the most expensive. If you don’t need to be so accurate, maybe you can get away with box colliders, you will have to choose what is best for your situation. Thereafter I think your best bet is to use Physics.Raycast()
and get the hit info.
//As in the docs with some small changes
int layerMask = 1 << 8; //building layer is whatever layer you give them and set it here
RaycastHit hit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(transform.position, transform.forward, out hit, Mathf.Infinity, layerMask))
{
Debug.Log(hit.distance);//distance to the hit position which is not the distance from the origin of the building
Debug.Log(Vector3.Distance(hit.transform.position, transform.position);//distance from origin of building to this game object’s position
}
@highpockets Thanks!!! All my buildings have a roof and a wall object that containe the mesh, is ther a faster way to had them all mesh colider than going one by one?
How do you create the buildings? Are you creating them dynamically by code, if so, just give them a layer and a mesh collider right after you instantiate them. If they are made with prefabs, just add what you need to the prefabs and all of the buildings should have the components. Did you give them a tag?? You can iterate over all the objects returned by the tag.. It’s really hard to help without knowing some more info about your setup in regards to the buildings in the scene
Your answer
Follow this Question
Related Questions
Alternative to OnCollisionStay? 1 Answer
How i prevent 2 obejcts with kinematic checked in both rigidbodies collide? 3 Answers
I have two different objects I would like to check when A and B gameObjects are collided ? 1 Answer
HELP WITH COLLISIONS 0 Answers
[SOLVED] Colliders aren't working properly. Clipping through ground. 1 Answer