How to add limits for alignOrientation

I am trying to create a code which will rotate given part in direction of players mouse using alignOrientation. That’s easy but how do i add limits for rotation? Let’s imagine that we need to let part freely rotate on Y axis but make it unable to rotate for more than 45 degrees in both up and down on x axis.

I already tried to do it through geting orientation from :ToOrientation(), clamping by math.clamp() and returning in CFrame.Angles but it only follow limits when facing world front direction. In other case it gives unexpected rotation. And yes I was including difference between radians and degrees.

Here is the part of the code that is responsible for this

--CFrame which will rotate part without including limits
local potentialCFrame = CFrame.lookAt(helicopterRoot.Position, lookPosition.Position)
local pitch, yaw, roll = potentialCFrame:ToOrientation()
local orientationVector = Vector3.new(
	math.deg(pitch),
	math.deg(yaw),
	math.deg(roll)
	)
--Clamped orientation which in theory must be ok
alignOrientation.CFrame = CFrame.Angles(
    math.rad(math.clamp(orientationVector.X,-45,45)),
    math.rad(orientationVector.Y),
    math.rad(orientationVector.Z)
)

English isn’t my native language so be aware of misundarstanding. I will be happy to hear any response!

1 Like

you’d have to apply the ‘limit’ relative to the direction the player is facing (or something like that)
how you do that is something i can’t tell you though

2 Likes
local rootPos = helicopterRoot.Position
local targetPos = lookPosition.Position
local dir = (targetPos - rootPos).Unit
local yAxis = Vector3.new(0, 1, 0)

local yawCFrame = CFrame.new(Vector3.zero, Vector3.new(dir.X, 0, dir.Z))
local localDir = yawCFrame:Inverse():VectorToObjectSpace(dir)
local pitch = math.asin(math.clamp(localDir.Y, -math.sin(math.rad(45)), math.sin(math.rad(45))))

alignOrientation.CFrame = yawCFrame * CFrame.Angles(pitch, 0, 0)

This should work regardless of world-facing direction and avoids the gimbal issue.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.