How to limit rotation to target

if (m_LastKnownPosition != SelectedTarget.transform.position)
{
m_LastKnownPosition = SelectedTarget.transform.position;
m_LookAtRotation = Quaternion.LookRotation(m_LastKnownPosition - transform.position);
}
if (transform.rotation != m_LookAtRotation)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, m_LookAtRotation, RotationSpeed * Time.deltaTime);
}

This script rotates GameObject with it, to SelectedTarget. But I like to limit this rotation. So, if the SelectedTarget is behind this GameObject it won’t rotate. (I like to get effect of cannon on the ship. Cannon won’t to shoot by his ship. ;D)

i assume the cannon is a child object of a ship that also rotates. So you would need to use local rotation of the cannon to check degrees. i also assume that this is 3D and Y is up. this would limit the local Y axis of the cannon on the ship when attached to the cannon by storing where it started in the start function.

	public float speed;
	public float max;

	float startrotation;
	Vector3 v;	
	float twist;
	void Start (){
		//store the cannons local start rotation on y axis;
		startrotation=transform.localEulerAngles.y;

		//set the amount of rotation degree allowed from the start rotation
		max = 30f;
    }
void Update(){

		//change speed to your liking
		speed = Time.deltaTime*50f; 

		  
		    v = SelectedTarget.transform.position-transform.position;
			v = v.normalized;
			transform.rotation = Quaternion.LookRotation (Vector3.RotateTowards (transform.forward, v,speed, 0.0F));
	
		// get the difference between start angle y and current y
	twist = Mathf.DeltaAngle (startrotation, transform.localEulerAngles.y);

	if(twist>max){transform.localEulerAngles=new Vector3(transform.eulerAngles.x,max,transform.eulerAngles.z);}
	if(twist<-max){transform.localEulerAngles=new Vector3(transform.eulerAngles.x,-max,transform.eulerAngles.z);}
		

}

You can lock the rotation of an object using Mathf.Clamp(current_value, min, max)

I would suggest you trying to put this line at the end of the update. I am assuming that it is the Y axis:

transform.eulerAngles = new Vector3(transform.eulerAngles.x, Mathf.Clamp(transform.eulerAngles.y, MIN_VALUE, MAX_VALUE), transform.eulerAngles.z);

In MIN_VALUE and MAX_VALUE it is up to you to set.

you could also try to do this:

public float MIN_VALUE = 0, MAX_VALUE = 50;

void LateUpdate(){
     transform.eulerAngles = new Vector3(transform.eulerAngles.x, Mathf.Clamp(transform.eulerAngles.y, MIN_VALUE, MAX_VALUE), transform.eulerAngles.z);
}

And don’t forget to apply the script to the object that you want to lock its rotation.

I hope it helps!

-GR1M