Help with HingeConstraint math

Hello, I’m having an issue with calculating a HingeConstraint’s target angle. As you can see in my attached clip, it calculates the first 90 degree half of the circle correctly, but for some reason the second 90 degree half of the circle the target angle completely inverses. Could somebody please check my math for me? Or is there an easier way to calculate this without using arctangents?

function targetAngle(targetPos)
	local startPos = Vector2.new(legs.Position.X,legs.Position.Z)
	targetPos = Vector2.new(targetPos.HumanoidRootPart.Position.X,targetPos.HumanoidRootPart.Position.Z)

    --width over height
	local ratio = (targetPos.Y-startPos.Y)/(targetPos.X-startPos.X)
    --convert to radians
	local angle = math.atan(ratio)

    --convert to degrees
	angle = angle*(180/math.pi)
	return (angle)
end

2 Likes

Solution: I forgot that atan2 exists :rofl:

function targetAngle(targetPos)
	local startPos = Vector2.new(legs.Position.X,legs.Position.Z)
	targetPos = Vector2.new(targetPos.HumanoidRootPart.Position.X,targetPos.HumanoidRootPart.Position.Z)

	local angle = math.atan2((targetPos.Y-startPos.Y),(targetPos.X-startPos.X))

	return math.deg(angle)
end
1 Like