BasePart Orientation to GuiObject Rotation

I wanted to make a ImageLabel rotate where the Part is pointing at but im not sure how to do it…



For this you would need some cframe math.

You have a camera cframe and a part cframe. You would want to get the relative cframe of the camera to the part.

Imagine we have your camera and a part

we want to find the angle between these parts.

The most popular way to find the angle between two vectors, but it doesn’t actually maintain direction for the angle so it is off of the table.

So how do we figure this out?
Through trig and CFrame manipulation of course!
If we ignore the positional components of the cframe and just focus on rotation. We can now model the angle we need.

image

The easiest way to do that is to get the part’s cframe relative to the camera. So we are able to just focus on finding the angle of one lookvector instead of finding the angle between two.

you can think of this as rotating the blue and black arrow to make the black arrow “zero” then getting the blue arrow’s cframe
image

Now that we have the blue arrow’s cframe we can get the green angle by using trig!

However thats a topic for another post. I have a demonstration of how you would achieve something like this

local imageLabel = script.Parent.ImageLabel
local part = game.Workspace:WaitForChild("Model"):WaitForChild("test")
local camera = game.Workspace.CurrentCamera


function GetAngleFromXY(X, Y)
	--check rare perpendicular cases to save on trig functions
	if Y == 0 then
		return if X > 0 then 90 else -90
	end
	
	--different logic based on if the x is negative or not because trig
	if X > 0 then
		return math.deg(math.atan(Y/X))
	else
		--use identical formula but make X positive and flip it by adding 180 degrees
		return math.deg(math.atan(Y/X))+180
	end
end

game:GetService("RunService").RenderStepped:Connect(function()
	--getting the "relative CFrame" like I explained earlier
	local newCF = part.CFrame:ToObjectSpace(camera.CFrame)
	--using just the lookvector from that
	local diff = newCF.LookVector
	
	--use our get angle trig function using z and x for x and y components. Essentially flattening the vector
	--we add 90 to our angle because the arrow is pointing left and not up, try +0, +90, -90, and +180 depending on your image
	local angle = GetAngleFromXY(diff.Z, diff.X) + 90
	
	imageLabel.Rotation = angle 
end)
1 Like

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