Reputation: 527
I am trying to make a distance meter. But I am not getting what I wanted. so I uploaded a picture. I want curved distance but I am getting straight something like displacement.
Here is my Code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class DistanceMeter : MonoBehaviour {
public GameObject current;
public GameObject destination;
private float beginPos;
private float targetPos;
private float currPos;
public Text dist;
void Start()
{
beginPos = current.transform.position.x;
targetPos = destination.transform.position.x;
}
void Update()
{
currPos = current.transform.position.x - targetPos;
int Distance = Mathf.Abs(Mathf.RoundToInt (currPos));
dist.text = Distance.ToString()+ " meters";
}
}
Upvotes: 3
Views: 961
Reputation: 17145
You can accumulate the traveled distance to find out the traveled distance on the curve:
public class DistanceMeter : MonoBehaviour
{
public GameObject current;
public GameObject destination;
private float beginPos;
private float targetPos;
private float currPos;
private float displacement;
public Text dist;
void Start()
{
beginPos = current.transform.position.x;
targetPos = destination.transform.position.x;
}
void Update()
{
float currDelta = current.transform.position.x - currPos;
currPos = current.transform.position.x;
displacement += Mathf.Abs(currDelta);
dist.text = displacement.ToString() + " meters";
}
}
But in order to find out the remaining distance (or displacement which has not traveled yet) you need to at least know the radius of the curve:
I assumed that the curve is part of a circle
If the curve is half of a circle, the displacement is radius × pi
Else if the angel is known, the displacement is radius × angel (in radians)
if angel is unknown but radius and distance is known, the displacement is 2 × radius × arcsin(distance/2 × radius)
Upvotes: 2