Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How would I make a hingeconstraint point to the mouse?

Hello there! I am trying to make a space-ship with a gun on the bottom. I am trying to make it so the player in the gunner seat can rotate/fire the weapon. I am using a hingeconstraint to rotate it every time the player moves the mouse, but I don't know the formula for the rotation. Any help would be appreciated! (All I need is the formula, I already have everything else setup) This is the weapon on the bottom of the ship

1 comment

0

If I were to rephrase this, it'd be me trying to convert a vector into a angle

1 answer

✓ Accepted answer

Assuming the hinge is rotating around its X axis (I think that's the only possibility, not sure if that can be changed or not) then the formula would be the inverse tangent of the mouse's CFrame's Z component over its Y component, once you transform the mouse's CFrame to be relative to the hinge's attachment. Complicated? It's easier if you can see it laid out in code:

local relativeVector = hinge.Attachment0.CFrame:ToObjectSpace(mouse.Hit).LookVector
hinge.TargetAngle = math.deg(math.atan2(relativeVector.Z, relativeVector.Y))

If you care to understand the math a little better, here is the math involved.

With the hinge rotating around the X axis, you can see the other axises are positioned like so

When taking the LookVector of the CFrame relative to the hinge, you get a unit vector that represents a direction from the hinge. If you move this direction towards the hinge you can see that it forms a triangle, with the vector itself being the hypotenuse and its components being the sides (Z and Y values). The angle you need to rotate the hinge by is located in this triangle. You have all the sides, so you can find the angle using an inverse trig function.

We're going to use inverse tangent because it allows us to use Roblox's math.atan2 function, which takes into account the signs of both the values that form the ratio. By taking into account both signs, we can make sure our angle is located in the proper quadrant if viewed as a unit circle. Without this, we would get the wrong angle 50% of the time, because there are 2 angles to every tangent value, and the regular math.atan function will give us the same 1 angle every time regardless of which angle we really want. I won't elaborate further on the use of atan2 but if you're interested in understanding it better feel free to let me know.

2 comments

1

Thank you so much for your help! I really dislike Vector math and couldn't do that stuff for the life of me lol. I'll let you know if I do need help!

0

I'm still getting some unexpected behavior, do you mind if we talk on disc?

This discussion is preserved as it was. New answers, comments, and votes are closed.