- Home /
How to get distance between two object by using a pinpoint? Or Tag?
I was able to get distance of two objects using raycast but I need to get distance using the raycast to pin point one object then to another game object and get the distance between those two.
Here is a screenshot:
Here is my code so far.
using UnityEngine; using System.Collections;
public class RaycastDistance : MonoBehaviour {
public GUIText distanceText;//This will hold the value of distance from Point A
public GUIText distanceBText;//This will hold the value of the distance from Point B
public Transform other;
private float distance;
void Start ()
{
distance = 0;//Distance initial value set to 0
SetDistanceText ();//Use to call the function SetDistanceText
distanceBText.text = "";
}
// Update is called once per frame
void Update ()
{
RaycastHit hit;
Vector3 up = transform.TransformDirection (Vector3.forward);//This where the raycast should point either forward,up,down,etc.0
Debug.DrawRay (transform.position, up * 100, Color.green);//Raycast draws line in green
if (Physics.Raycast (transform.position, up, out hit))
{
distance = hit.distance;
distanceText.text = "Distance: " + distance.ToString();
distanceBText.text = "YOU GOT THE DISTANCE MEASUREMENT!!";
Debug.Log("This distance is " + hit.distance);
}
}
void SetDistanceText()
{
distanceText.text = "Distance: " + distance.ToString();
}
}
Please really need help. Thanks.
Answer by Dave29483 · Sep 29, 2016 at 07:56 AM
It may be better to have the raycast simply return and store the transform of the last two objects selected. Then you can do the following once both transforms are assigned;
distance = (target.position - source.position).magnitude;
Your answer
![](https://koobas.hobune.stream/wayback/20220612093611im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Select an Enemy C# 1 Answer
Distribute terrain in zones 3 Answers
Click On/Off Manager - C# 2 Answers
Reverse object position order 1 Answer