2D Collision Avoidance & Smoothly rotating game object

Hello,

Looking for a little help here. Thanks for reading!

The Problem: I’ve set up basic obstacle avoidance for characters using raycast. Rapid changes in direction as a result of avoiding obstacles is making the characters oscillate between a variety of directions. Need some way to smooth the rotation.

Info on Game: 2D top down on x/z. Using sprite sheets for graphics.

Code to orientate characters to target

targetHeading = targetPosition - transform.position;
targetDirection = targetHeading.normalized;

Collision Avoidance Code

There are three rays being cast. This is the code for the center one.

// Declare RayCastHit
RaycastHit hit;
			
// Raycast forward from transform, to a distance of 2
if(Physics.Raycast(transform.position, transform.forward, out hit, 4f))
{
	// Make sure ray is not hitting itself
	if(hit.transform != transform) 
	{
		if(hit.collider.gameObject.tag == "Enemy" || hit.collider.gameObject.tag == "Player")
		{
			Debug.Log("EnemyScript.FindAIInput: RayHit on " + hit.collider.gameObject.tag);
						
			// Add direction from hit face, times how much force to repel by
			targetDirection += hit.normal * 100;
		}
	}}

Code for moving and rotating Gameobject

rigidbody.AddForce (targetDirection.normalized * moveSpeed * Time.deltaTime);
		
// Rotate to targetDirection
transform.rotation = Quaternion.LookRotation(targetDirection); // Converts target direction vector to Quaternion
transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0); 
		
// Set the position
transform.position = new Vector3(transform.position.x, 0, transform.position.z);

Thanks again! Let me know if you need any more information!

Kind of obvious, but disabling rotation in the update dramatically improved the stuttering. Here’s the code incase it’s of use to someone else.

if(rayhit == false)
		{
			// Add force along targetHeading
			//rigidbody.AddForce (targetHeading.normalized * moveSpeed * Time.deltaTime);
			rigidbody.AddForce (targetDirection.normalized * moveSpeed * Time.deltaTime);
		
			// Rotate to targetDirection
			transform.rotation = Quaternion.LookRotation(targetDirection); // Converts target direction vector to Quaternion
			transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0); 
		
			// Set the position
			transform.position = new Vector3(transform.position.x, 0, transform.position.z);
		}
		
		else
		{
			rigidbody.AddForce (targetDirection.normalized * moveSpeed * Time.deltaTime);
			transform.position = new Vector3(transform.position.x, 0, transform.position.z);
			
			rayhit = false;
		}