How would I limit up and down movement?

Hello there

I’m creating a player controlled turrent and I’m trying to do the up and down movement of the turrent, I’ve already solved the 360 degree turning and just need to fix the up and down movement.

External Media

As you can see the turrent moves normally however when you go up or down then it looks weird. I’m trying to limit the up and down movement to the barrel of the turrent only instead of the whole turrent.

Here is my code:

UserInputService.InputChanged:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseMovement then
		Mouse.TargetFilter = Turrent
		

		
		
		TurrentBody.WeldConstraint.Enabled = false
		TurrentBody.CFrame = CFrame.new(TurrentBody.Position, Mouse.Hit.Position)
		TurrentBody.WeldConstraint.Enabled = true
		
	end
end)

Any help is appreciated, thanks

1 Like

Try looking into using math.clamp(), that should be able to help you limit the angle or movement.

UserInputService.InputChanged:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseMovement then
		Mouse.TargetFilter = Turrent
		local _,y,_ = CFrame.new(TurrentBody.Position, Mouse.Hit.Position):ToOrientation()
		TurrentBody.WeldConstraint.Enabled = false
		TurrentBody.CFrame = CFrame.new(TurrentBody.Position)*CFrame.Angles(0,y,0) -- 90 degree max rotation
		TurrentBody.WeldConstraint.Enabled = true
	end
end)

Explaination
What I did here is I broke the CFrame Orientation into its x,y,z componenets using CFrame:ToOrientation() which returns a tuple so you can use it like
local X,Y,Z = CFrane:ToOrientation() where CFrame being your CFrame.

1 Like

Thanks, after tweaking around with it a bit it works however how would I make it so when you move the mouse up the barrel of the turrent moves up and when you move it down it goes back to its original position?

You can change the cframe of the barrel independently.

Is it possible to first know when the mouse moves up or down though?

Yes!

UserInputService.InputChanged:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseMovement then
		Mouse.TargetFilter = Turrent
		local x,y,_ = CFrame.new(TurrentBody.Position, Mouse.Hit.Position):ToOrientation() -- x is the up down axis of the mouse. Now just set the barrels cframe to x using a weld constraint for simplistics sake.
		TurrentBody.WeldConstraint.Enabled = false
		TurrentBody.CFrame = CFrame.new(TurrentBody.Position)*CFrame.Angles(0,y,0) -- 90 degree max rotation
		TurrentBody.WeldConstraint.Enabled = true
	end
end)

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