Apply Force for fixed period of time

hi
I would like to know how can i apply force for fixed time, like for 10 seconds.

function OnCollisionEnter(theCollision : Collision){
	if(theCollision.gameObject.name == "PowerUp"){
	
Destroy(theCollision.gameObject);
		
		rigidbody.AddForce(0, 0, 500);
		

	}
	}

I want to apply rigidbody.Addfocre for 10 seconds…

thanks for help in advance :slight_smile:

I guess you have to use corutines
check this thread nearby
http://forum.unity3d.com/threads/66883-Coroutine-in-C

any easier way to do it in javascript?..

Here you go, I’m not a Javascript programmer though so I can’t guarantee the syntax or whether it’ll work :wink:

var timeCount : float;
var secondsToApplyForce : float = 10;
var addingForce : boolean = false;

function FixedUpdate () {
	if(addingForce) {
		timeCount += Time.deltaTime;
	
		if(timeCount < secondsToApplyForce) {
			rigidbody.AddForce(0, 0, 500);
		} else {
			timeCount = 0;
			addingForce = false;	
		}
	}
}

function OnCollisionEnter(theCollision : Collision){
	if(theCollision.gameObject.name == "PowerUp"){
		Destroy(theCollision.gameObject);
		
		addingForce = true;
	}
}

thanks Aerozo! :slight_smile:
it worked!

If you want a function that just runs once:

function OnCollisionEnter (theCollision : Collision) {
	if (theCollision.gameObject.name == "PowerUp") {
		Destroy (theCollision.gameObject);
		AddForceOverTime (rigidbody, 10.0, Vector3(0.0, 0.0, 500.0));
	}
}

function AddForceOverTime (thisRigidbody : Rigidbody, totalTime : float, force : Vector3) {
	var timer = 0.0;
	while (timer < totalTime) {
		timer += Time.fixedDeltaTime;
		thisRigidbody.AddForce (force);
		yield WaitForFixedUpdate();
	}
}