Limiting Camera CFrame

So I’m trying to create an ability in my game which creates a shield in front of a player. The shield is just a part thats connected to the player with a motor6D.

The idea was just to rotate the C0 of the Motor6D when the player rotates their camera up and down. The intended effect was just supposed to be a shield that rotates with the players camera, and is limited to just rotating up and down around the character, but it should never rotate behind the character.

I wrote a script that works, but the issue is that sometimes the rotation goes beyond what it should, resulting in the shield ending up behind the player. In the following video you’ll see the X axis of the camera printed in degrees, and ideally it should be within the range of -90 to 90, it sometimes exceeds that range.

local script:

local Part = Instance.new("Part")
Part.Parent = workspace
Part.CanCollide = false
Part.Size = Vector3.new(10,20,1)
Part.Massless = true
local M6 = Instance.new("Motor6D")
local Character = script.Parent
local HRP = Character:WaitForChild("HumanoidRootPart")
M6.Parent = HRP
M6.Part0 = HRP
M6.Part1 = Part


local RS = game:GetService("RunService")
RS.Heartbeat:Connect(function()
	local CameraCF = workspace.CurrentCamera.CFrame
	local x,y,z = CameraCF:ToEulerAnglesXYZ()
	print(math.deg(x))
	M6.C0 = CFrame.Angles(x,0,0) * CFrame.new(0, 0, -5)
end)

And in case your wondering, I already tried math.clamp`ing the rotation, and doing so just ends up in a weird flickering effect where the part just teleports up and down.

If anyone knows how I can make this script work as intended that would be helpful.

1 Like

You need to get the camera CFrame in relation to the HumanoidRootPart to get the angle you want. I also recommend using ToEulerAnglesYXZ() here since applying angles in that order will give you a more accurate X angle in this scenario.

local RS = game:GetService("RunService")
RS.Heartbeat:Connect(function()
	local CameraCF = workspace.CurrentCamera.CFrame
	local HRPCF = HRP.CFrame
	
	local LocalCF = HRPCF:ToObjectSpace(CameraCF)
	
	local x,y,z = LocalCF:ToEulerAnglesYXZ()
	
	M6.C0 = CFrame.Angles(x,0,0) * CFrame.new(0, 0, -5)
end)
2 Likes

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