- Home /
Increase speed of vehicle - math question (javascript)
I have an endless runner game that I want to increase with speed as the game goes on. I want it to increase at a quicker rate at the beginning and a slower rate as time goes on. I figured a square root function would accomplish this but I realize it doesn't. For example:
speed = 10
function gameSpeed(){
speed = Mathf.Sqrt(speed);
Debug.Log(speed);
}
InvokeRepeating("gameSpeed",0,1);
When I run this it prints: 3.16, 1.77, 1.33, etc. It does what I want except it gets smaller and smaller.
I also thought of a square function such as:
speed = 10
function gameSpeed(){
speed = Mathf.Pow(speed, 2);
Debug.Log(speed);
}
InvokeRepeating("gameSpeed",0,1);
And when I run this one it prints: 100, 1000, 100000000, etc. This one is at least increasing, except it is increasing at a slower rate at the beginning and a faster rate as more time goes on, opposite of what I want.
I just need the parent function of the equation, I know how to modify it to increase at the rates I want.
Answer by byurocks23 · Mar 19, 2014 at 07:09 PM
I found my answer:
speed = 10
function gameSpeed(){
speed += 100 / speed;
Debug.Log(speed);
}
InvokeRepeating("gameSpeed",0,1);
Answer by SirCrazyNugget · Mar 19, 2014 at 06:42 PM
Why not just use a variable that increases by timeDelta then multiple that by a constant to get the rate of increase you require?
var speed = 10;
function gameSpeed(){
speed += Time.deltaTime * 0.1;
}
Answer by kyzk · Mar 19, 2014 at 08:24 PM
In the "speed = Mathf.Sqrt(speed)" your speed variable is recursively defined in terms of its previous value, so speed becomes smaller EVERY second. Instead you need to take the square root of the time elapsed since the game started, as well as the starting speed. Here is a plot of what you have.
So instead you need to something like
startSpeed = 10
speed = 10
time = 0
function gameSpeed(){
speed = startSpeed + Mathf.Sqrt(time);
time++; //Since this function is only called every second.
Debug.Log(speed);
}
InvokeRepeating("gameSpeed",0,1);
Which will generate a speed plot that looks like
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Calculations Wrong? 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
A counting script? 1 Answer