- Home /
Timescale and Timers - what am I doing wrong?
I have a timer that tells how much time has passed since the start of the game:
worldTime += Time.deltaTime;
I have a gameObject that moves in the x axis from position A = 0 to B = 5. Everytime it arrives at one of those positions I register how long it took to do so. Here is the code:
var testCube : Transform;
private var testCubeAtZero : boolean;
private var cubeSpeed : float = 1;
var currentTime : float = 0;
var timeDifference : float = 0;
Update()
if (testCubeAtZero){
testCube.position.x += Time.deltaTime;
if (testCube.position.x > 5){
timeDifference = scriptWorld.worldTime - currentTime;
currentTime = scriptWorld.worldTime;
print("Pos 0 - Time Dif: " + timeDifference.ToString("f2"));
timeDifference = 0;
testCubeAtZero = false;
}
}
else {
testCube.position.x -= Time.deltaTime;
if (testCube.position.x < 0){
timeDifference = scriptWorld.worldTime - currentTime;
currentTime = scriptWorld.worldTime;
print("Pos 5 - Time Dif: " + timeDifference.ToString("f2"));
timeDifference = 0;
testCubeAtZero = true;
}
}
When the timeScale is 1, it takes 5.04 seconds to go from A to B and vice versa. If I increase the timeScale it starts to take longer from A to B and the values are no longer stable (e.g. with timeScale = 30 it takes around 6 seconds and the higher I go in the timeScale the worst it gets )
I need the time it takes between the two points, in "game time" to be always the same (5.04 secs) no matter how fast or slow the timescale is. Am I doing something wrong? I can't figure it out.
Any help very appreciated!
Answer by rutter · Jun 17, 2014 at 05:51 AM
Let's suppose your game is running at a nice and smooth 60fps. That means each frame takes about 17ms to process and render, so Time.deltaTime
will be about 0.017
.
If you set Time.timeScale
to 30
, you'll tell Unity to pretend that 510ms have passed between frames. At that point, Time.deltaTime
will indicate that your update calls are coming in roughly half-second intervals. At that speed, it's no wonder you're starting to lose accuracy.
You'll be hard pressed to find a game engine that can reliably simulate a 30x speed increase.
Perhaps there are other ways to accomplish the effect you're looking for?
Thanks for the reply. In my project I need to allow the player to fast forward time (similar to The Sims x3 time speed) so he doesn't have to wait for certain events to happen. The problem is that I need something around 7 $$anonymous$$utes to take 4 to 5 seconds (timeScale = 90). How else would I be able to achieve something like this?