look toward a target with limitation

hey guys, i’m using this script to rotate my turret toward a target, it looks at my target only on z axis .is there any way to limit its rotation to be only rotated from 90 degrees to -90 degrees.
thanks.

using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class LookOnlyOnZ : MonoBehaviour {
    	// Use this for initialization
    	public Transform target;
    	public float damping;
    
    
    	void Start () {
    
    
    	}
    
    	// Update is called once per frame
    	void Update ()
    	{
    
    		var lookPos = target.position - transform.position;
    		lookPos.z= 0;
    		var rotation = Quaternion.LookRotation(lookPos);
    		transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
    	}
    }

There are actually a few ways :

  1. Check for angle between target and object, if between -90 and 90, look at. (Use Angle() method to get the angle)

  2. Use a half circle collider, if target enters the collider, look at it.

2D game (Sprites)

Here, I suppose the “idle” sprite is facing right (aligned with the local red axis in the scene view)

public Transform target;
public float damping;

private Quaternion initialRotation;

private void Start()
{
    initialRotation = transform.rotation;
}

// Update is called once per frame
void Update () {
    Vector3 lookPos = target.position - transform.position;
    lookPos.z = 0;
    float angle = Vector3.SignedAngle(initialRotation * Vector3.right, lookPos, Vector3.forward);
    Quaternion rotation = initialRotation * Quaternion.AngleAxis( Mathf.Clamp( angle, -90, 90 ), Vector3.forward) ;
    transform.rotation = Quaternion.Slerp( transform.rotation, rotation, Time.deltaTime * damping );
}

3D version (3D models)

Here, I suppose the “idle” 3D model is facing forward (aligned with the local blue axis in the scene view)

public Transform target;
public float damping;

private Quaternion initialRotation;

private void Start()
{
    initialRotation = transform.rotation;
}

// Update is called once per frame
void Update () {
    Vector3 lookPos = target.position - transform.position;
    lookPos.y = 0;
    float angle = Vector3.SignedAngle(initialRotation * Vector3.forward, lookPos, Vector3.up);
    Quaternion rotation = initialRotation * Quaternion.AngleAxis( Mathf.Clamp( angle, -90, 90 ), Vector3.up) ;
    transform.rotation = Quaternion.Slerp( transform.rotation, rotation, Time.deltaTime * damping );
}