How to find the relative rotation between a part and humanoidrootpart (in 360 degrees)

Hello, I’m struggling a bit with relative rotations right now. I’m wanting to find which side of a part, the humanoidrootpart is relative to in degrees.

Example: Right side being 90 degrees, left side being 270 degrees, front side being 0 (360) degrees & back side being 180 degrees.

Illustration:
image

I don’t know a good way of explaining this, so it’d be great if someone understands what I mean.

3 Likes

So if I understand this question correctly, you want to find out, given some part, if the player is more ‘in front’, ‘to the left’, ‘to the right’ or ‘behind’ that part given its orientation and position?

1 Like

I managed to do it myself. It took a while but here is the code:

local Part1 = script.Parent.Part

local Part2 = script.Parent.Part2

function GetRelativeRotation(a, b)

a.CFrame = CFrame.new(a.CFrame.p, b.CFrame.p)

local RelRotation = CFrame.new(a.CFrame.p, b.CFrame.p)

RelRotation = math.atan2(RelRotation.LookVector.X, RelRotation.LookVector.Z)

RelRotation = math.deg(RelRotation)

RelRotation = math.floor((RelRotation/10)+.5) * 10

RelRotation = RelRotation + 180

RelRotation = math.floor((RelRotation / 90)+.5) * 90

if RelRotation == 360 then RelRotation = 0 end

return RelRotation

end

game:GetService("RunService").Stepped:Connect(function()

print(GetRelativeRotation(Part1, Part2))

end)

The use-case isn’t important to explain for this, but here it is in action (just to check that the rotations are right)

https://gyazo.com/c5940e4d1515f6154050681f2d109a01.gif

1 Like

I’m pretty sure you can do this by comparing vectors(?)
I was looking at this yesterday so it’s still pretty fresh in my mind.
Assuming the part is at point (a1,a2) along the X and Z axis and the player is at point (b1,b2) you can do

angle = math.atan((b2-b1)/(a2-a1)) --(in radians)

You may have to switch the numerator and denominator if the angle is wrong, but I’m pretty sure this is what you want

If I understand your problem correctly, you could use the dot product.

local unit = (game.Workspace.Metro_AA.HumanoidRootPart.Position -game.Workspace.Part.CFrame.p).unit

print(math.deg(math.acos(game.Workspace.Part.CFrame.LookVector:Dot(unit))))