I’ve made a tool that basically places an object (plank) on mouse position, it works pretty well but I want to ask. Could I make this code better or more optimized?
local playersService = game:GetService("Players")
local debrisService = game:GetService("Debris")
local replicatedStorageService = game:GetService("ReplicatedStorage")
local placementEvent = replicatedStorageService.Events.Collectibles.PlacementEvent
local metalTarget = replicatedStorageService.Models.CollectiblePreset.MetalTarget
local userInputService = game:GetService("UserInputService")
local getMouse = playersService.LocalPlayer:GetMouse()
local getTool = script.Parent
local getPlayer = workspace:WaitForChild(playersService.LocalPlayer.Name)
local toolDebounce = false
local partInstance
local currentPartOrientation
local rotationDebugging = true
userInputService.InputBegan:Connect(function(getInput)
userInputService.InputBegan:Connect(function(getInput)
if getInput.KeyCode == Enum.KeyCode.R then
partInstance.CFrame = CFrame.Angles(0,math.rad(90),0) * partInstance.CFrame.Rotation + getMouse.Hit.p
elseif getInput.KeyCode == Enum.KeyCode.T then
partInstance.CFrame = CFrame.Angles(math.rad(90),0,0) * partInstance.CFrame.Rotation + getMouse.Hit.p
end
end)
end)
getTool.Equipped:Connect(function()
for i,v in ipairs(workspace.Running:GetChildren()) do
if v:IsA("Part") and v.Name == "MetalTarget" then
v:Destroy()
end
end
partInstance = metalTarget:Clone()
partInstance.Name = "MetalTarget"
partInstance.Transparency = .8
partInstance.Size = Vector3.new(8.614, 1, 18.417)
partInstance.BrickColor = BrickColor.new("Lime green")
partInstance.Parent = workspace.Running
partInstance.Anchored = true
partInstance.CanCollide = false
partInstance.CanTouch = false
partInstance.CanQuery = false
getMouse.TargetFilter = partInstance
getMouse.Move:Connect(function()
currentPartOrientation = partInstance.CFrame.Rotation
partInstance.CFrame = CFrame.new(getMouse.Hit.p) * currentPartOrientation
end)
end)
getTool.Unequipped:Connect(function()
debrisService:AddItem(partInstance, .001)
end)
getTool.Activated:Connect(function()
if toolDebounce == false then
toolDebounce = true
currentPartOrientation = partInstance.CFrame.Rotation
placementEvent:FireServer(CFrame.new(getMouse.Hit.p) * currentPartOrientation, "Metal")
task.wait(.1)
toolDebounce = false
end
end)
if getPlayer then
getPlayer.Humanoid.Died:Connect(function()
if partInstance then
debrisService:AddItem(partInstance, .001)
script:Destroy()
end
end)
else
error("PLAYER CANNOT BE FOUND!")
end
Here’s the game: Anvil Test [v3.0] - Roblox
The tool’s name is “PlanksGenerator”.