- Home /
Help with distance counter
I am making a mini golf game, and i want to show how far the distance you traveled on a gui when you touch a hole (the end). I've tried a script but it just shows the distance from the ball to the hole on the gui.
Script:
using UnityEngine;
using System.Collections;
public class distance : MonoBehaviour {
public static int distanceTravelled = 0;
public Transform other;
void OnGUI ()
{
if (other) {
float dist = Vector3.Distance (other.position, transform.position);
if (dist < 2) {
GUI.Box (new Rect (0, 0, 100, 100), "Distance : " + dist);
}
}
}
}
Answer by ShadyProductions · Jan 07, 2018 at 06:21 PM
Perhaps you should try it like this (put this script on the ball):
You can add your own custom condition for when the ball touches the hole, to only show GUI.
float distanceTravelled = 0;
Vector3 lastPosition;
void Start()
{
lastPosition = transform.position;
}
void Update()
{
distanceTravelled += Vector3.Distance(transform.position, lastPosition);
lastPosition = transform.position;
}
void OnGUI ()
{
GUI.Box (new Rect (0, 0, 100, 100), "Distance : " + distanceTravelled);
}
Your answer
Follow this Question
Related Questions
Need to vertically space buttons in scripting C# 1 Answer
Script filling Scene with empty gameObjects 2 Answers
allowing only one child object per paremnt object at any given time. 0 Answers
Game is not restarting after gameOver=true 1 Answer
Make player move to location and stop within a certain distance 1 Answer