- Home /
Temporarily Changing a Variable
What im trying to do is change a forward motion variable to 15 for 5 seconds then set it back to regular speed of 5 after the times ran out but later when your distance traveled is greater than 200 i want the speed to increase to 10 HERES MY CODE
if (powerUpTime >= 5) {
forwardMovementSpeed = 15.0f;
cheesePOWActive = true;
anim.SetBool("gotCheese",true);
if (powerUpTime <= 0) {
forwardMovementSpeed = 5.0f;
cheesePOWActive = false;
anim.SetBool("gotCheese",false);
And that works the problem is that when i try to use this code later it wont move the speed because its still seeing that forwardMovementSpeed = 5.0f;
if (!dead && distanceTraveled > 200) {
forwardMovementSpeed = Mathf.Lerp (forwardMovementSpeed, maxSpeed, Time.deltaTime);
}
by the way maxSpeed = 10 and this is all inside of the Update()
Put your restore code in a separate function and use Invoke().
Answer by chrischu · Oct 03, 2014 at 09:31 AM
I think you misunderstood the Mathf.Lerp method. It is meant to interpolate between two values (first parameter and second parameter), the third parameter defines how far along the interpolation is (0 means the first value is used, 1 means second value is used, 0.5 means the average between the two is used).
Therefore you should not use Time.deltaTime since it represents the time between the last update call and the current one and therefore does not go from 0 to 1 like the third parameter of Mathf.Lerp should do, but rather jumps around between different values.
If correcting the Mathf.Lerp call does not help it would be good if you could post all the code in the Update method since the error most likely lies in the bits that you haven't shown.
Answer by TubeSocSamurai · Oct 09, 2014 at 06:42 PM
thanks i figured it out tho
Still, the basic idea of Unity answers is to provide answers for problems and therefore it would be good if you could post your own solution as answer or mark another answer as accepted.
Answer by Jopan · Oct 09, 2014 at 09:25 PM
void GotCheese()
{
forwardMovementSpeed = 15.0f;
cheesePOWActive = true;
anim.SetBool("gotCheese",true);
Invoke("CheesePowDeactivate", 5f); // Call function in 5 seconds
}
void CheesePowDeactivate()
{
forwardMovementSpeed = 5.0f;
cheesePOWActive = false;
anim.SetBool("gotCheese",false);
}
// As for increasing your speed
bool speedIncreasing = false;
float movementIncreaseRate = 1f;
void Update()
{
if (!dead && distanceTraveled > 200 && !speedIncreasing)
{
speedIncreasing = true;
StartCoroutine(IncreaseSpeed());
}
}
IEnumerator IncreaseSpeed()
{
while(forwardMovementSpeed < maxSpeed)
{
forwardMovementSpeed += Time.deltaTime * movementIncreaseRate;
yield return null;
}
}
Your answer

Follow this Question
Related Questions
Tracking distance after Instantiate 2 Answers
Making a 2d "radar" for space game 2 Answers
dynamic rotation distance 1 Answer
I need help about raycast and edges 2 Answers