How can I rotate a model correctly in a viewport frame?

I’ve been working with viewport frames recently, and it has been a little tough. For the past few days, I’ve been having trouble with positioning models with a primary part and gear.

I have a model of three buttons and this is what I have so far.

I want to orient it horizontally and make the top of the buttons slightly more tilted towards the camera. But, after trying to do that I get this.

I’m not good with CFrames, so I might of done something wrong.

updateButtonPreview
local function updateButtonPreview(item)
	itemPreview:ClearAllChildren()
	
	local itemObject = item["Object"]:Clone()
	itemObject.Parent = itemPreview
	itemObject:SetPrimaryPartCFrame(CFrame.new(viewportPoint)) -- viewport point is just Vector3.new(0,0,0)
	itemObject:SetPrimaryPartCFrame(itemObject.PrimaryPart.CFrame * CFrame.Angles(45,90,0))
	updateViewportCamera(itemObject,0.25)
end

I have other problems with previewing gear. The camera I apply doesn’t really fit all the gears. For example, I have a burger too close to the camera, and then a cake that is facing the wrong way. How would I account for all the different rotations and distances of each gear?

Here is the code for the gear preview and the viewport camera.

updateGearPreview
local function updateGearPreview(item)
	itemPreview:ClearAllChildren()
	
	local itemObject = item["Object"]:Clone()
	local model = Instance.new("Model")
	local handle = itemObject:FindFirstChild("Handle")
	handle.Parent = model
	model.PrimaryPart = handle
	itemObject = model
	itemObject.Parent = itemPreview
	itemObject:SetPrimaryPartCFrame(CFrame.new(viewportPoint))
	updateViewportCamera(itemObject,5)
end
updateViewportCamera
local function updateViewportCamera(item,distance)
	local cframe, size = item:GetBoundingBox()
	
	local max = math.max(size.X, size.Y, size.Z)
	local distance = (max/math.tan(math.rad(viewportCamera.FieldOfView))) * distance
	local currentDistance = (max/2) * distance
	
	viewportCamera.CFrame = CFrame.new(viewportPoint + Vector3.new(0,0,currentDistance), viewportPoint)
end

Any help or feedback would be appreciated!

I’m not too familiar with view port frames. But I do know that Sleitnick has made a pretty cool math video on view port frames have you checked that out?

1 Like

Funny enough I did already watch this, but I didn’t want to dive into the math :P. (math in school and in programming will probably make my brain hurt) I’ll probably go rewatch it if I got a good idea on how to implement it.