- Home /
gradually raise moving speed but got different results on different devices
I have an idea to make moving bugs(i.e. animals) raise their speed gradually. So I have the following code :
float m_speedRatio = 1;
float m_fracJourney = 0;
void Update(){
m_speedRatio += 0.01f
m_fracJourney += 5f * Time.deltaTime * this.speedRatio;
transform.position = Vector3.MoveTowards( fromVec3, toVec3, m_fracJourney );
}
As you can see, every bug with this script will move towards the target position, toVec3. In the environment of my notebook, this caused an a little bit slower moving speed, but it made a crazy fast speed in my desktop PC.
How can I fix it to make my game have the similar playing speed no matter it runs on any device ?
My project's TimeManager settings :
Fixed Timestep setting : 0.02
Maximum Allowed Timestep : 0.3333
Time Scale : 1
Thanks !
Answer by robertbu · Aug 27, 2013 at 11:05 AM
Your problem is on line 5. You increase by a fixed amount every frame. On some devices, your frame rate might average only 30 fps, on others, 100 fps.
You can handle this one of two ways. You can scale your m_speedRatio by Time.deltaTime:
m_speedRatio += 0.6 * Time.deltaTime;
Or you can move your scale of m_speedRatio into FixedUpdate() where you have a fixed frame rate for the increase.
I multiply Time.deltaTime at the very next line. Don't you think they are the same ?
Image your game running at two different speeds, 30fps and 100fps. At 30 fps, m_speedRatio would increase at the rate of .3 per second. At 100 fps, the increase would be 1.0 per second (three times faster). You do scale m_fracJourney by Time.deltaTime, but since m_seedRatio is not scaled, you get the uneven performance.
I only see this tiny slice of your code, but I don't understand why you have both m_speedRatio and m_fracJourney unless you are trying for a non-linear increase in speed.
I just resolved this problem in the way of FixedUpdate() as you mentioned. Also, I gave some attributes to bugs such as value of m_speedRatio, etc. If I have to find out some thresholds for those variables on different devices, I think FixedUpdate() can make all things less complicated. Thanks. And yes, its a non-linear increasing speed.
Your answer
Follow this Question
Related Questions
How to slow down my spawn rate? 1 Answer
MoveTowards with animation 1 Answer
Using time.deltatime to move from coordinate to coordinate is too fast? 1 Answer
Changing the spawn rate 0 Answers