- Home /
Calculate the distance between an object and my player
Hey
I'm trying to load a screen after my player gets to the shop. Does anyone know how to calculate the distance between an object you click on and the player.
I think i would need to find a way to record the gameObject click on, but i'm having no luck finding how to do that.
then i would probably record the location of the player and do the math from there.
right now in my code you can click on a destination and the character will go there. I just need to be able to calculate the distance and load the screen if it gets close enough.
The question is WHERE do you put the script? Is it a specific object that you will be clicking on or a variety of objects - like everything in the scene?. The figuring the distance is easy but where do you put the script? The player? then you would get the distance for anything clicked unless specifically tagged so only objects with a certain tag will calculate the distance from it to the player float distance = Vector3.Distance (object1.transform.position, object2.transform.position);
https://docs.unity3d.com/ScriptReference/Vector3.Distance.html
Answer by KapoorArjun19 · May 13, 2020 at 11:31 AM
For your point 1: Use a Raycast from your camera. The RayCastHit will return information about the collider that was hit, including the transform:
void Update()
{
if( Input.GetMouseButtonDown(0) )
{
Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
RaycastHit hit;
if( Physics.Raycast( ray, out hit, 100 ) )
{
Debug.Log( hit.transform.gameObject.name );
}
}
}
For Point 2: Use this to calculate distance between two objects:
var distance = Vector3.Distance(object1.transform.position, object2.transform.position);
Your answer
Follow this Question
Related Questions
Are Unity distances that small? 1 Answer
Declaring a Vector3 variable in C# 1 Answer
Check distance between multiple objects 1 Answer
variable++ error... 1 Answer