Boslem
1
Hi there,
I have come across a problem within a project I am working on. I want to have a 2D level where the character runs across the screen endlessly until it hits a trigger that will end the level.
My problem is that when I play the same level over and over I seem to get slight variations in the time that it takes to get to the trigger, even though I don’t change any variables in the collision box’s the character move’s across. I cant seem to find a problem within my code and I am thinking that its probably obvious but I have been staring at it for so long that I have become code blind.
The movement code for my character is as follows:
void FixedUpdate()
{
if (GameManager.Instance.gameEnd == false)
{
rigidbody2D.velocity = transform.right * maxSpeed;
}
}
And the code for my game timer is as follows:
void Start ()
{
startTime = (int)Time.time;
}
void FixedUpdate ()
{
gameTime = ((int)Time.time) - startTime;
seconds = (int)gameTime;
ms = (int)((Time.time * 100) - (startTime * 100)) % 100;
gameTimeString = string.Format("{0:00} : {1:00}", seconds,ms );
}
I have read a lot of posts both on here and other forums and cant seem to find a solution to my problem, so any help would be much appreciated.
Thanks!
The way that you cast to an int in your code could be a source of errors. I expect that it could give one second of variation between runs. I would cast only where necessary and keep all storage of times in floats.
void Start ()
{
startTime = Time.time;
}
void FixedUpdate ()
{
gameTime = Time.time - startTime;
seconds = gameTime;
ms = (Time.time * 1000 - startTime * 1000) % 1000; // Milliseconds in 1000ths of a second for clarity
gameTimeString = string.Format("{0:00} : {1:00}", (int)seconds, (int)(ms/10) );
}
Also, the Unity documentation says that Time.time returns the time of the start of the frame. If the game runs at 24 frames a second this should cause errors.
You could increment and decrement the speed of the charcter based on how far it has got and how far you expected it to get based on the distance it has travelled and the time elapsed. This could let it catch up if going to slow.