Local child rotation and transform.LookAt

ok so i know similar questions have been asked and answered a ton of times but i am still having trouble.

i have a gun that i am using transform.LookAt to look at the player, i want to attach the gun to an enemy, the problem is i want the gun to stay relatively forward facing on the enemy (so like the gun can turn 45 degrees left/right while the enemy still holds the gun forward)

i have tried:

transform.LookAt(target.transform.position);
    if(transform.rotation.y > .45)
    	{
    		transform.rotation.y = .45;
    	}else if(transform.rotation.y < -.45)
    	{
    		transform.rotation.y = -.45;
    	}

it works stationary but it’s the rotation in the world so once the enemy turns it’s all ruined

So i tried euler angles:

transform.LookAt(target.transform.position);
if(transform.localEulerAngles.y > 45)
	{
		transform.localEulerAngles.y = 45;
	}
	if(transform.localEulerAngles.y < 315)
	{
		transform.localEulerAngles.y = 315;
	}

it works with one if statement at a time but i dont know how to apply both because looking completely straight is 360/0 degrees and i want to limit its left/right rotation at 45/315

i know the answer must be simple and im stupid but it’s been a few days now and i dont know how to solve this, thanks

Your question is hard for me to grasp, but I think what you need is to clamp the values using the Clamp() function

Directly accessing ‘eulerAngles’ or ‘localEulerAngles’ can cause issues. Rotations are stored internally as Quaternions, and the eulerAngle you read back out may not be the one you put in. Also it is recommended to not assign axis independently. From the manual:

“Do not set one of the eulerAngles axis separately (eg. eulerAngles.x = 10; ) since this will lead to drift and undesired rotations.”

With all this said, it is possible what you are doing will work…especially if the x, and y values of the localEulerAngle remain near 0. So if what I’m about to suggest does not work, you will have to approach the problem differently.

As for your code, try this:

if(transform.localEulerAngles.y > 45 && transform.localEulerAngles.y <= 180)
    {
       transform.localEulerAngles.y = 45;
    }
    else if(transform.localEulerAngles.y < 315 && transform.localEulerAngles.y > 180)
    {
       transform.localEulerAngles.y = 315;
    }