How do I script a viewportframe so that an object appears directly in the centre? I’m having the issue where the objects I’m parenting to the viewportframe are appears in different spots(I think) and aren’t appearing where I want them to be. Any help would be appreciated. Code below.
You either need to move the model or move the camera. You could move the camera and use the lookAt cframe constructor to make a CFrame pointed directly at a part of your model:
local primaryPart -- set to primary part
local offsetRelativeToPart = primaryPart.CFrame * Vector3.new(-5,-5,-5) -- offset relative to the part
cameraPosition = primaryPart.CFrame * offsetRelativeToPart
camera.CFrame = CFrame.lookAt(cameraPosition, primaryPart.Position)
That code picks a spot relative to the primary part and then points the camera directly at the primary part. You can also add a relative offset by replacing primaryPart.Position with primaryPart.CFrame * offset in the lookAt constructor.
Hey! Your solution worked wonders! Do you have any idea how to configure that so I can rotate the camera a few degrees? Currently my model is facing to the right.
You can change the camera position by changing the offset, in the code above that’s Vector3.new(-5,-5,-5), which is -5 studs in each direction from the model.
If you want multiple positions that are perfect rotations (for tweening a rotation animation for example) you could do:
local cameraOffsetCFrame = (CFrame.lookAt(cameraPosition, primaryPart.Position) - primaryPart.Position)
local rotationCFrame = CFrame.Angles(math.rad(0), math.rad(45), math.rad(0))
camera.CFrame = cameraOffsetCFrame * rotationCFrame + primaryPart.Position
That basically centers the camera CFrame from above with the origin, rotates it around the origin by a CFrame, then moves it back to the primary part.