Tank Turret faces correctly until I rotate and it somehow inverts?

I have tried making my tank’s turret spin using HingeConstraint Servo TargetAngle stuff. Using a script I originally found on DevForum, with some modifications, I eventually got it to work, however when I rotate the tank in any direction, the system inverts kind of? Hard to explain with words will attach a video below showing off the issue

	if Equipped then
		local D = Mouse.Hit.Position - Turret.PrimPart.CFrame.Position
		local Angle = math.deg(math.atan2(-D.Z, D.X))
		Turret.PrimPart.HingeConstraint.TargetAngle = Angle - Turret.Hinge.Orientation.X

I’ve tried tweaking around with the script, changing to X, Y and Z, changing origin parts, etc, and nothing correctly works.

Pretty sure it’s the calculation in this line. You are using Turret.Hinge.Orientation.X which if I am assuming correctly is the Orientation of a Part named Hinge.
Since the tank body is rotating about 180 degrees in the video, and the orientation of your mouse to turret aiming point is about 180 out, what happens if you just make it Turret.PrimPart.HingeConstraint.TargetAngle = Angle

1 Like

This function should work for all types of hinge constraints:

local function calculateServoAngle(hinge, targetPosition)
	local baseAttachment = hinge.Attachment0

	local object_horizontal_offset = (baseAttachment.WorldCFrame):PointToObjectSpace(target.Position)
	local object_yaw_angle = math.atan2(object_horizontal_offset.Y, -object_horizontal_offset.Z)
	object_yaw_angle = math.deg(object_yaw_angle)

	return object_yaw_angle

Nothing changes, same thing happens

Is Target.Position your Mouse position, or something else?

Yep if the target is the mouse position vector3 or part position.

local baseAttachment = Turret.PrimPart.HingeConstraint.Attachment0
local object_horizontal_offset = (baseAttachment.WorldCFrame):PointToObjectSpace(Mouse.Hit.Position)
local object_yaw_angle = math.atan2(object_horizontal_offset.Y, -object_horizontal_offset.Z)
object_yaw_angle = math.deg(object_yaw_angle)
Turret.PrimPart.HingeConstraint.TargetAngle = object_yaw_angle

Does not work either, ends up spinning endlessly in whatever direction the mouse is pointed?
type or paste code here

Swap the base attachment, it should be the attachment that is the one not spinning or being turned.

Getting closer, no longer rotates the opposite direction when turning the vehicle, it stays still as it should. However, the last issue is that it’s just straight up inverted.

Check your turret attachments and model, multiply the attachment1 or 0 by 180 degrees to uninvert it.

lol, sorry I’m so exhausted that I’m confused by the most basic stuff right now, what do I multiply in the attachment?

Never mind, fixed it. Changed -object_horizontal_offset.Z to be positive. Thank you so much for the help!

Sorry, I meant rotate it, one method is to multiple by CFrame.Angles