- Home /
Reduce ConstantForce value after specified time. WaitForSeconds()?
heyhey again, another question!
previously, i got help with manipulating the constantforce value on my object, upon entering a trigger. now, i'm trying to go beyond that, and do an additional "function"? i want the object to return to its original force, or "speed" after "x" number of time (maybe 5 seconds).
i have no knowledge of anything c#, but i'm learning fast! i started trying to write my own code to do the above, but after all the errors i was getting in the console, i finally have it running ok, i fixed my own errors.
but my code is not doing what i was trying to achieve! can someone take a look and point me in the right direction? in the easiest "straigh forward english layman words" that i could understand and continue learning?
thanks!
here's my code:
using UnityEngine; using System.Collections;
public class Booster : MonoBehaviour { //private vehicle = GameObject.Find("vehicle"); //obtain a reference to the object with the script attached //private constantForce = vehicle.GetComponent<engine>(); //obtain a reference to the script itself //private currentSpeed = constantForce.force; //copy the value of the life variable to a local variable public GameObject target;
// Update is called once per frame
void Update () {
}
void OnTriggerEnter () {
Boost();
StartCoroutine(Slowdown());
}
private void Boost(){
//Engine e = target.GetComponent<Engine>();
//You don't need a cast, that the whole point of generics.
//I don't think you need this either.
ConstantForce motor = target.GetComponent<ConstantForce>();
//You needed an instance.
motor.force = Vector3.forward * 5000;
//Hard-coded values are generally not good.
}
IEnumerator Slowdown(){
ConstantForce motor = target.GetComponent<ConstantForce>();
yield return new WaitForSeconds(1);
motor.force = Vector3.forward * -2500;
}
}
what is happening now is that, yes, the object does "slowdown" because its being "pushed backwards in the negative value"...but that is the problem, it gets pushed backwards eventually, not just have the speed being reduce, its like it reduces from 10, to 0, then -10 which ends up being reverse!
Answer by Bob5602 · Jan 26, 2011 at 06:12 PM
You could put in a simple if statement so it only gets pushed backwards if the velocity is greater than 0. Then it won't go negative.