Unity3D Development – Rigidbody Reset Force / Motion Code

In my new game I need to be able to give an object in motion a new force (same magnitude) in a random direction with a button press. Here’s my C# solution using Coroutines.
Its working perfectly for me and solves the weird physics problem with stopping/starting using rigidbody.isKinematic.

All these code snippets are in the script attached to the object:

Vector3 eulers = Vector3.zero;
private bool waiter;

IEnumerator shotRedirect()
{
yield return new WaitForSeconds(0.0f);
eulers = transform.eulerAngles;
eulers.x = Random.Range(0,360);
transform.eulerAngles = eulers;
rigidbody.isKinematic = true;
StartCoroutine(shotRedirectPart2());
}

IEnumerator shotRedirectPart2()
{
yield return new WaitForSeconds(0.01f);
rigidbody.isKinematic = false;
rigidbody.AddForce(transform.forward * shotPower);
}

private void Waits()
{
waiter = true;
}

void Update()
{
if(waiter == true)
{
if (Input.GetKeyDown(KeyCode.A))
{
StartCoroutine(shotRedirect());
}
waiter = false;
Invoke("Waits",0f);
}
]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s