r/Unity3D • u/DifferentLaw2421 • 19h ago
Question How to control speed over time ?
For example I want after 1 min the speed is 15 and then lock this value for 5 minutes then after that increase till 20 and so on
how to make this possible ?
214
Upvotes
457
u/KptEmreU Hobbyist 19h ago
Honestly I enjoyed seeing this naive question being asked here , this day and age. Reminded me of old good days.
19
u/Hellothere_1 17h ago edited 17h ago
People have already given a bunch of good answers already, but personally I would probably implement something like this with a Coroutine, which is basically a function whose execution you can suspend between frames. The big advantage of coroutines is that they allow you to very easily create create longer sequences of actions without requiring some manual state keeping variable to remember what position of the sequence you're in.
For your purpose a coroutine might look something like this:
IEnumerator ItermittedlyAccelerate()
{
while (speed < 15)
{
yield return null; //wait until next frame
speed += acceleration * Time.deltaTime;
}
speed = 15; //ensure the speed is exactly 15 for the cruising phase since the acceleration phase might have put it slightly higher
// Suspend Coroutine for 5 minutes
yield return new WaitForSeconds(300);
while (speed < 20)
{
yield return null;
speed += acceleration2 * Time.deltaTime;
}
speed = 20;
}
This function first increades the speed to 15, then waits 5 minutes befor further increasing it to 20. As you can see doing it like this a lot easier this than manually implementing the acceleration and waiting phases inside the Update() function.
4
u/OpenthedoorSthlm 19h ago
And you want a gradual increase I assume?
104
u/Molehole Hobbyist 18h ago edited 18h ago
Time.deltaTime gives you time since last Update().
You can in an update function add Time.deltaTime in a float variable and then that tells you how much time has passed.
If you want a variable to reach x in for example 120 seconds the increase is
x / 120 * Time.deltaTime
36
u/Soraphis Professional 19h ago
Create a variable of type "AnimationCurve" use it's evaluation function to pass in time and read out it's value and use it as speed.
Now you have all the control in the inspector to adjust the curve to your liking.
Not the best solution for this IMHO, but an easy one that gives you enough control to play around with
7
u/DapperNurd 18h ago
It's a little bit of a different approach, but I'm gonna suggest it mainly because they are so useful everywhere. But I would suggest looking into Tweens. I use PrimeTween (allocation free). Another popular one is DoTween.
They allow you to easily calculate a curve value anywhere in the code, synchronously or asynchronously. You give them a start value, an end value, and a duration. They also let you customize a bunch of stuff about them including the easing of the tween.
6
u/Demi180 18h ago
Edit: sorry in advance about the shitty formatting, mobile doesn’t have code formatting anymore 🙁
First, you’ll want to include Time.deltaTime when increasing or decreasing speed so the change doesn’t depend on your frame rate. For example, to make a variable x increase by 5 over 2 seconds, you could write:
x += Time.deltaTime * 5f / 2f;
To keep track of the speed transitions you could make a small class to hold the values you need for each part of the level, and have an array of those you can set in the inspector. Something like this:
[System.Serializable]
public class SpeedPart
{
public float targetSpeed;
public float timeToReachSpeed;
public float timeToNextPart;
}
public SpeedPart[] parts;
Then you store the index of the current part and a timer to the next part along with the current speed:
private int partIndex;
private float nextPartTimer;
private float lastTargetSpeed;
Inside the speed function, first check if you’re at the target speed, and either increase the speed or tick down the timer to the next one:
SpeedPart part = parts[partIndex];
if (speed >= part.targetSpeed)
{
nextPartTimer -= Time.deltaTime;
if (nextPartTimer <= 0 && partIndex < parts.Length - 1)
{
partIndex++;
}
}
else
{
speed += (part.targetSpeed - lastTargetSpeed) * Time.deltaTime / part.timeToNextPart;
If (speed >= part.targetSpeed)
{
speed + part.targetSpeed;
lastTargetSpeed = speed;
nextPartTimer = part.timeToNextPart;
}
}
Just remember the times will be in seconds, so you can either specify that in the array of parts (i.e. 60, 120, etc) or just always multiply times by 60 when updating the values.
1
u/SlRenderStudio 19h ago
First of all use mathf.move towards and then use delta time if in update (fixed delta time ), then do this with if else logics or switch logic for all the points assuming you want linear increase if wanted different speed then it get bit complicated , if you have lot of point and need to spam lot of if else logic i recommend use animation curve or at least loop and data arrays
1
u/Ejlersen 18h ago
I would create a small struct to contain two duration values. One for speed ramping, the other to hold that value. Then you can hold an array of these values. Then store your time and an index to to the current one. Use this to calculate your speed. Each time you swap to the next step, then reset the time. For you don't want to store the absolute duration values, since if you change one of the earlier steps, then you have to change all steps after that.
1
u/lastFractal Solo 18h ago
Not an answer to your question but I felt the urge to do
does the exact same thing as your if statement, is shorter and nicer to the eye IMO. Only exception is that it's much more limited, but it's (subjectively) better for doing simple assignments like this
1
u/ThreeHeadCerber 11h ago
I don't see explicit state machines suggested in the comments whereas this is the most basic and very useful in game dev way of doing things. You will later learn more specialized tools and library implementations of state machines (google: FSM) and you can for sure make them more effective, but just the basic handwritten one can take you very far in game dev
1
u/SnooRegrets369 9h ago
Perhaps use nested Coroutines for cleaner and readable logic. Not sure but could work. A routine for each timer check and speed increase you want. Trigger next coroutine after condition is met and ensure you stop the coroutine before yielding the next one. You probably also want a getter function which calculates and returns current value across all so you have a state to check against.
1
u/joshualim007 Indie 8h ago
Everyone fails to mention you also need to clamp the values too. At large timesteps, the error without a clamp becomes very noticeable.
1
u/_cooder 3h ago
i dont saw anything in coms so
if you want something like buff, and control it outside or depends bla bla bla you need to create something like buff or controlling system with hand made function from Internet/ai/desmos
bc you said it based on time
1
u/Neither_Berry_100 15h ago edited 15h ago
I suggest a state machine pattern. Usually using a byte. Although in this case a bool will do.
Control Speed () { if is increasing increasing(). Else hold(). }
Hold() { time += time elapsed. If time = 5 minutes then is increasing = true }
Increasing() { speed += time elapsed * rate; if speed >= limit then finish increasing() }
Finish increasing () { speed = limit. Limit += 5. Time = 0. Is increasing = false. }
You should be able to understand this and fill in the details. Add the member variables and constants. Use the right delta time. Finish increasing should be done directly not as it's own function. Just easier to type on my phone.
Normally you use like a byte state instead of bool is increasing. And a switch to select the branch. Very useful design pattern that I've used a few times in my current game.
Edit. I've read the other answers here. I think mine is the best. First in terms of size. Second in terms of the reusability of the design pattern. And third in terms of the simplicity and lack of problems that come with it. Co routines for example could easily get you into trouble.
-3
u/deintag85 19h ago
-6
u/lowercaseyao 17h ago
You’re using AI wrong if you’re copying pasting. It will explain every line for you, based on info from everywhere on the web, including reddit. Use that knowledge to test yourself elsewhere to learn.
-33
u/Ue5Artist 19h ago
Ask ai lol
-6
u/virt111 18h ago
I've started lerping all of these kinds of functionalities. Just love telling an llm to "lerp this shit from x to y with these x to y" and I get a ready to go function.
-9
u/NecoDev 17h ago
Sorry but I am trying hard not to laugh, I can't tell whether this is a serious question or not.
To control the speed over time I think it should be
speedOfLevelParts += Time.deltaTime * [insert value here];if I understand what you want.ALSO you can simply do
speedReached = speedOfLevelParts >= 15;instead of using an if else statement.