- Home /
how to cultivate the distance
How to calculate the distance between 2 points and show it to the screen
Answer by haidao0923 · Jul 25, 2018 at 04:21 AM
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public Transform other;
void Example()
{
if (other)
{
float dist = Vector3.Distance(other.position, transform.position);
print("Distance to other: " + dist);
}
}
}
Answer by FatsWaller · Jul 25, 2018 at 08:20 AM
To show it to the UI, you will need to have a text object in the scene and create a variable that updates its value.
The distance of two points can be calculated simply by reading the unity manual: https://docs.unity3d.com/ScriptReference/Vector3.Distance.html
Here's an example: (Don't forget to include the "using UnityEngine.UI;"!)
using System.Collections;
using UnityEngine.UI;
using UnityEngine;
public class DisplayDistance : MonoBehaviour {
public float Distance;
public Text DistanceText;
void Update(){
Distance = Vector3.Distance(other.position, transform.position);
DistanceText.text = "Distance: " + Distance.ToString();
}
}
Your answer
Follow this Question
Related Questions
When is Velocity calculated? 1 Answer
Find angle between two gameobjects? 1 Answer
Angle between vectors - calculation 2 Answers
Object slows down when moving to a NavPoint, speed is not constant 1 Answer
Obtaining a perpendicular point? 1 Answer