I’m trying for the time to be output when the gameobject (earth) has returned to its original position - aka the orbital period.
The code is below:
Text textbox;
private Vector3 initialposition;
private float timeperiod = 0;
private Vector3 trailpos;
// Use this for initialization
void Start () {
var earth = GameObject.Find("Earth");
initialposition = earth.transform.position;
textbox = GetComponent<Text>();
}
// Update is called once per frame
void Update () {
var earth = GameObject.Find("Earth");
if (earth.transform.position == initialposition)
{
timeperiod = Time.realtimeSinceStartup - timeperiod;
textbox.text += "Orbital Period: " + timeperiod.ToString() + "
";
}
}
I don’t see what I’m doing wrong - or why there’s an output ONLY once after around 1 second has elapsed.
Can anyone see what I’m doing wrong? Thank you in advance.
The earth will never be at exactly the same place as it has been before, this is because the frame-rate varies a lot in a game and so the timestep (I guess you are using Time.deltaTime?) is never consistent and therefore it won’t end up at exactly the same starting position as it did before.
That’s the easy explanation, but actually this is a common new-programmer’s mistake: floats (a Vector3 is made up of 3 floats) are saved in a tricky way in memory that gives them rounding errors. So sometimes you think all your objects have x-coordinate at 3, but actually it is 3.000000001 or something.
Long story short: don’t use equality checks with floats (use integers for that) lower-than and higher-than checks are fine.
As for a solution, you can try using Vector3.Distance(earth.transform.position, initialposition)
to check if it is in a certain range of the starting point (This will be true for multiple frames!)
I hope you learned some things
-Gameplay4all