Coroutines on physics

Hi Guys,

I’m trying to create sequential actions with physics that can blend and look natural, but keep full control to edit.

I was using FixedUpdate(), but by the end it’ll have a load of if(blah blah) statements in there and bools that’ll just make it look messy and not be as easily controllable imo.

Can you use Coroutines to control physics? Are the physics still essentially written the same way?

This is my current code for the FixedUpdate():

	void FixedUpdate()
	{	
		if(hitDelay > 0)
		{
			hitDelay -= Time.deltaTime;
			return;
		}
		
		// Creates a new speed every frame
		float newSpeed = (moonAccel + moonDefaultForce);
		
		// Will check the position each time
		if( checkPlayerPos <= 0 )
		{
			if(lastTarget == "PlayerOne")
			{
				playerPos = (GameObject.FindGameObjectWithTag("PlayerTwo").transform.position - transform.position).normalized;
			}
			// If player two set target as player one.
			else if(lastTarget == "PlayerTwo")
			{
				playerPos = (GameObject.FindGameObjectWithTag("PlayerOne").transform.position - transform.position).normalized;
			}
			else
			{
				//Will not be called logically.. it's only so we can set the variable outside the if statement.
				playerPos = (GameObject.FindGameObjectWithTag("PlayerTwo").transform.position - transform.position).normalized;
			}
			
			checkPlayerPos = 3.0f;
		}
		else
		{
			checkPlayerPos -= Time.deltaTime;
		}
		
		Vector3 predictedVel = playerPos * newSpeed;
		
		if(rigidbody.velocity.magnitude > predictedVel.magnitude)
		{
			moonAccel = rigidbody.velocity.magnitude;
			
			newSpeed = (moonAccel + moonDefaultForce);
		}
		
		predictedVel = playerPos * newSpeed;
		
		// Finally assign the lerp...
		rigidbody.velocity = Vector3.Lerp(rigidbody.velocity, predictedVel, Time.deltaTime);
	}

There’s going to be multiple ways that the object will be manipulated by physics, and each one is a separate ‘action’ so it makes sense for it to be a coroutine. I was wondering if I can use physics in coroutines, and if so if there’s any difference between FixedUpdate() and IEnumerator for the physics to work.

Thanks guys,

Found my own answer:

http://unity3d.com/learn/tutorials/modules/intermediate/scripting/coroutines

this i just a tip if you feel that things are getting too cluttered.

use more functions to divide up your if-statements.

i think of problems in this fashion:

If something is true, run “this function” else run “this function”. then in that function you have more if statements that performe functions.

try to write as "generic functions as possible so that you can “reuse” functions whenever it is possible.

people are very often afraid to use functions with proper function names and instaed doing massive nested if-statements all over the place.

keep coding!

/T