Clamp CFrame Euler Angles

I’m trying to make a gun turret system, however at the moment, the turret can rotate as far as it wants. So, I want to try and clamp its CFrame X rotation between -20 and 80 degrees to stop it facing backwards and such. However, with this current script, it still rotates freely. I use the vehicle seat to get input from the player, to rotate it using CFrame. Any questions feel free to ask, all help appreciated.

script.Parent.Part.Shooty.C1 = script.Parent.Part.Shooty.C1 * CFrame.fromEulerAnglesXYZ(math.clamp(math.rad(-script.Parent.VehicleSeat.Throttle), math.rad(-20), math.rad(80)), 0, 0)
1 Like

Try putting the clamp in the Y value instead of the X one

script.Parent.Part.Shooty.C1 = script.Parent.Part.Shooty.C1 * CFrame.fromEulerAnglesXYZ(0, math.clamp(math.rad(-script.Parent.VehicleSeat.Throttle), math.rad(-20), math.rad(80)), 0)

That makes it move sideways now, and still can turn wherever it wants

It’s definitely on the X axis, and I tried that with the X and no change.

This might because you are adding the rotation clamp. not setting it.

Let me simplify it first

local rotationAmount = math.clamp(math.rad(-script.Parent.VehicleSeat.Throttle), math.rad(-20), math.rad(80))
script.Parent.Part.Shooty.C1 *= CFrame.fromEulerAnglesXYZ(rotationAmount, 0, 0)

Then

local constraints = {
	["YawLeft"] = 15;
	["YawRight"] = 15;
	["ElevationAngle"] = 15;
	["DepressionAngle"] = 15;
}

local function eulerClampXY(x,y, constraints)
	local Constraints =  constraints
	local degY = math.deg(y)
	local degX = math.deg(x)
	local newY = math.clamp(degY,-Constraints.YawRight,Constraints.YawLeft)
	local newX = math.clamp(degX,-Constraints.DepressionAngle, Constraints.ElevationAngle)

	return math.rad(newX), math.rad(newY)
end


--Initial rotation Script
local rotationAmount = math.rad(-script.Parent.VehicleSeat.Throttle)
local shootyC1 = script.Parent.Part.Shooty.C1
local goalCFrame : CFrame = shootyC1 * CFrame.fromEulerAnglesXYZ(rotationAmount, 0, 0)

--EulerClamping after the rotation CFrame is applied
local x,y,z = goalCFrame:ToOrientation()
local newX, newY = eulerClampXY(x, y, constraints)

script.Parent.Part.Shooty.C1 = CFrame.fromOrientation(newX, newY, z) + shootyC1.Position

Using some old functions I took from my TurretController module script.

1 Like