Make whole Model look at player

I made a gun, the only thing about it is the fact that every single part of it is a separate part. I made a script to make the gun look at the player but it only moves the PrimaryPart. how can I make it move the whole gun?

local MaxLookDistance = 275
local MovementSpeed = 4

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local Chat = game:GetService("Chat")
local Debris = game:GetService("Debris")
local Gun = script.Parent.PrimaryPart
local DefaultCFrame = Gun.CFrame

local function getNearestPlayer()
	local part = nil
	local dist = MaxLookDistance
	for i,v in ipairs(Players:GetPlayers()) do
		local character = v.Character
		if character then
			local root = character:FindFirstChild("HumanoidRootPart")
			if root then
				local thisDist = (root.Position-Gun.Position).Magnitude
				if thisDist < dist then
					dist = thisDist
					part = root
				end
			end
		end
	end
	return part
end

local focusedPart = nil
local lastCheck = 0

RunService.Heartbeat:Connect(function(delta)
	if focusedPart then
		local cf = CFrame.lookAt(
			DefaultCFrame.Position,
			focusedPart.Position
		)
		Gun.CFrame = Gun.CFrame:Lerp(cf, delta * MovementSpeed)
	else
		Gun.CFrame = Gun.CFrame:Lerp(
			DefaultCFrame,
			delta * MovementSpeed
		)
	end
	if time() > lastCheck then
		lastCheck = time() + 1
		focusedPart = getNearestPlayer()
	end
end)

Gun.Anchored = true

The video shows my error.

4 Likes

I see, you need to weld all the parts of the gun to the primarypart

3 Likes

would i make it a motor6D or a regular weld?

edit: nevermind i needed to make a regular weld, thank you!

2 Likes

You could use WeldConstraint.

for _, child in pairs(model:GetChildren()) do
    if child:IsA("BasePart") then
        if child.Name == "Door" then
            local weld = Instance.new("WeldConstraint")
            weld.Part0 = child
            weld.Parent = child
        elseif child.Name == "Part" then
            if not weld then
                warn()
            else
                weld.Part1 = child
            end
        else
            warn()
        end
    end
end
2 Likes

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