- Home /
Question by
fredii3 · Jan 04, 2019 at 09:51 AM ·
slidervector3.distance
Vector3 distance to fill slider.
I want to fill a slider that indicates when a distance has been traveled.
I have:
float dist = Vector3.Distance(other.position.z, transform.position.z);
dist
goes between 6 and 280.
I am confused on how to do it, because the slider goes from 0 to 1. I tried Mathf.Clamp01 and it doesn't work.
Comment
Best Answer
Answer by fafase · Jan 04, 2019 at 10:19 AM
You can set min/max value in Inspector:
The other way is to normalize the distance. It goes from 6 to 280, so make it start from 0 to 274.
float start = 6f;
float total = 274f;
float distance = Vector3.Distance(other.position.z, transform.position.z) - start;
value = distance / total;
ui-sliderinspector.png
(34.2 kB)
I'm measuring the distance between the player and the end of the level. The math you provided helped me. Here is my code for future people if the struggle with this:
using UnityEngine;
using UnityEngine.UI;
public class Game$$anonymous$$anager : $$anonymous$$onoBehaviour {
public Transform player;
public Transform levelCleared;
public Slider slider;
float dist;
private void Start()
{
}
private void Update()
{
dist = player.position.z - (levelCleared.position.z - player.position.z) * -0.1f;
float value = dist / levelCleared.position.z;
slider.value = value;
Debug.Log(value);
}
}
Answer by Hellium · Jan 04, 2019 at 10:16 AM
float dist = Vector3.Distance(other.position.z, transform.position.z);
float minDist = 6 ;
float maxDist = 280;
slider.normalizedValue = ( dist - minDist ) / ( 280 - minDist ) * (slider.maxValue - slider.minValue ) + slider.minValue;
Which can be simplified if you are SURE the value of the slider is between 0 and 1
float dist = Vector3.Distance(other.position.z, transform.position.z);
float minDist = 6 ;
float maxDist = 280;
slider.value = ( dist - minDist ) / ( 280 - minDist );