- Home /
Speed changes every time I use restart button
I am building a simple snake game since I'm learning how to code and use Unity. I managed to load a "Game over" scene whenever you lose and added a Restart button on that scene, but when I play the game and use that button speed changes everytime. I've been trying to solve this for the last two days and i can't find a solution.
yes, sorry.
void $$anonymous$$ove()
{
Vector2 v = transform.position;
transform.Translate(dir);
if (comio)
{
GameObject g = (GameObject)Instantiate(colaPrefab, v, Quaternion.identity);
cola.Insert(0, g.transform);
comio = false;
}
else if (cola.Count > 0)
{
cola.Last().position = v;
cola.Insert(0, cola.Last());
cola.RemoveAt(cola.Count - 1);
}
}
"cola" means tail and "comio" is eat, which is a boolean I set to false. "dir" was set to Vector.zero
this gets called here:
void Start()
{
InvokeRepeating("$$anonymous$$ove", 8 * Time.deltaTime, 8 * Time.deltaTime);
}
And this is how the button works:
public void RestartGame()
{
Scene$$anonymous$$anager.LoadScene(1);
}
I don't know if this is helpful but I did most of it following this tutorial
Answer by Eno-Khaon · May 31, 2020 at 01:02 AM
When the Start() function is called in your script, the speed of your game is being made dependent on the exact time it took to process that frame.
InvokeRepeating("Move", 8 * Time.deltaTime, 8 * Time.deltaTime);
Sometimes, the frame is processed quickly and the game plays out at high speed, while at other times, the frame might experience a performance hiccup and the game slows considerably. For example, if the frame takes 1/40 of a second, the snake will move every 0.2 seconds, but if the frame takes 1/2 of a second, the snake will only move every 4 seconds.
You should probably decide on a rate for it to move at regardless of framerate instead. As an example:
public float gameSpeed = 4.0f; // 4 moves per second
// ...
float reciprocalSpeed = 1.0f / gameSpeed;
InvokeRepeating("Move", reciprocalSpeed, reciprocalSpeed);
Your answer
Follow this Question
Related Questions
Laggy camera on const moving speed 1 Answer
Can you change the speed of a raycast? 1 Answer
How to get collision force, not relative velocity? 1 Answer
How to get the speed of an object? 3 Answers
physics collision speed problem 2 Answers