Viewport only rotates around one car

Hello,

What I’m trying to do here, is make the camera spin around a car in a ViewportFrame, however every time I select a different car, and while this Technically works, this happens;

Code:

local CarSpawn = {}

local function rotateCar(carPart,Viewport)
	local rotation = 0;
	game:GetService("RunService").Heartbeat:Connect(function()
		local CFrame_1 = carPart.CFrame * CFrame.Angles(0, math.rad(rotation), 0) * CFrame.new(-10, 7, -10)
		CFrame_1 = CFrame.new(CFrame_1.p, carPart.Position)
		Viewport.CurrentCamera.CFrame = CFrame_1
		rotation = rotation + .5
	end)
end
function CarSpawn.showCarInfo(CarInfo, CarName, Price, Type)
	local Viewport = CarInfo.ViewportFrame
	local clonedCar = game.ReplicatedStorage.Cars[Type][CarName]:Clone()
	clonedCar.Parent = Viewport
	
	local carPart = clonedCar.PrimaryPart
	local Camera = Instance.new("Camera")
	Camera.Parent = Viewport
	Viewport.CurrentCamera = Camera

	
	
	for i,v in pairs(carPart:GetChildren()) do
		v:Destroy()
	end	
end

return CarSpawn

Thank you!

you need some kind of way to stop the .heartbeat function after you choose a different car i think connections would work probably

also if you wanna make he cam look at a part use
CF = CF.LookAt(CF.Position,target.Position)

1 Like

Could you explain how I’d set that up?

there this could help btw im not a very good explainer
also the cars look cool and i like the gui kinda resembles my style of making gui

also you could use this module which does all the calculations to fit the model in frame and it does a good job you should try it

1 Like

Still having trouble with this, this is how I have the connections set up but I’m obviously very new to them, so it’s not quite working;
Error: Players.anthlons.PlayerGui.MainUI.Client:101: attempt to index nil with 'Disconnect' - Client - Client:101

local connection
for i,v in pairs(carSpawnFrame.ScrollingFrame:GetChildren()) do
	if v:IsA('TextButton') then
		v.MouseButton1Click:Connect(function()
            connection:Disconnect()
			local carPart = clonedCar.PrimaryPart
			local Camera = Instance.new("Camera")
			Camera.Parent = carInfo.ViewportFrame
			carInfo.ViewportFrame.CurrentCamera = Camera

			for i,v in pairs(carPart:GetChildren()) do
				v:Destroy()
			end	

			local rotation = 0;
			
			connection = game:GetService("RunService").Heartbeat:Connect(function()
				local CFrame_1 = carPart.CFrame * CFrame.Angles(0, math.rad(rotation), 0) * CFrame.new(-10, 7, -10)
				CFrame_1 = CFrame.new(CFrame_1.p, carPart.Position)
				carInfo.ViewportFrame.CurrentCamera.CFrame = CFrame_1
				rotation = rotation + .5
			end)
		end)	
	end
end

try checking if a function is in the connection by doing

if connection then
   connection:Disconnect()
end

also for you heartbeat function its better to use RenderStepped cuz its more faster and makes things smooth

1 Like