Lock rotation (range of motion) of auto-aiming bullet spawner

Hi,
I have an auto-aiming bullet spawner attached to my Player and would like to limit its range of motion so that it cannot aim too far off to the left/right/up/down. I have come across a few techniques using Mathf.Clamp and Quaternions but cannot get this to work as it should. I am looking for say a -30 to 30 degree limit for both the X and the Y rotation. The aiming is simply achieved using a trigger ahead of the Player which detects any enemies entering and then aims at them if they are inside it.

My script simply takes in the direction of the enemy and then assigns the bullet spawner’s direction to this. It then uses LookRotation to look in the direction, thus:

transform.rotation = Quaternion.LookRotation(bulletDirection);

Any help would be great.
Thanks

You could use something like this…

    		if(target){
    			Vector3 dir = (target.position - _myTransform.position).normalized;
    			float direction = Vector3.Dot(dir, transform.forward);
    			
    			dir = (target.position - _myTransform.position).normalized;
    			direction = Vector3.Dot(dir, transform.right);
    			
    			if(direction > rotLimit){
    				//turn aimer left
    			}
    			else if(direction < -rotLimit){
    				//turn aimer right				
    			}
    			else{
    				//do nothing				
    			}
    		}
    		else{
    			//do nothing
    		}

Then copy the same thing for Up and Down, maybe add a distance check if you want it to have a specific range. This would keep the auto aimer tracking the target at the max of its rotation (might be good for a turret in a tower defense type game). Not sure if that’s exactly what you want but it would be easily modified for other purposes.

I think this will help. Click!