I’ve been working on this object placement script for a couple of weeks now and it mostly works. There is one issue that I just can’t seem to wrap my head around.
When I place the first object, everything is fine. When I go to place the second object, two instances of that object are placed in the same position. The third object has three instances, and so on. You can see this here, look at the workspace.
ModuleScript
function PlacementSystemModule.PlacingMode(i)
InPlacingMode = true
Object = script:FindFirstChild(i):Clone()
Object.Parent = game.Workspace
PlacementSystemModule.PlaceObject()
Mouse.TargetFilter = Object
game:GetService("RunService").Heartbeat:connect(function()
if InPlacingMode then
local OldCFrame = Object:GetPrimaryPartCFrame()
local NewCFrame = CFrame.new(roundAToB(Mouse.Hit.X, I), Base.Position.Y+1, roundAToB(Mouse.Hit.Z, I)) * CFrame.Angles(0, math.rad(Rotation), 0)
Object:SetPrimaryPartCFrame(OldCFrame:lerp(NewCFrame, 0.4))
if (Object.PrimaryPart.Position.X > Base.Position.X-Base.Size.X/2) and (Object.PrimaryPart.Position.Z > Base.Position.Z-Base.Size.Z/2) and (Object.PrimaryPart.Position.X < Base.Position.X+Base.Size.X/2) and (Object.PrimaryPart.Position.Z < Base.Position.Z+Base.Size.Z/2) then
InBoundary = true
Object:SetPrimaryPartCFrame(OldCFrame:lerp(NewCFrame, 0.3))
else
InBoundary = false
end
end
end)
end
function PlacementSystemModule.PlaceObject()
if InPlacingMode and Debounce then
Mouse.Button1Down:Connect(function()
Debounce = false
local PrimaryPart = Object:FindFirstChild("PrimaryPart")
if PrimaryPart then
PrimaryPart.CanCollide = true
for i, v in pairs(PrimaryPart:GetTouchingParts()) do
if v.Parent:FindFirstChild("PrimaryPart") and v.Parent ~= Object then
IsColliding = true
else
IsColliding = false
end
end
PrimaryPart.CanCollide = false
end
if InPlacingMode and InBoundary and not IsColliding then
local PlacedObject = ReplicatedStorage:FindFirstChild("PlaceRequest", true):InvokeServer(Object.Name, PlacementSystemModule.ObjectsTable[Object.Name], CFrame.new(roundAToB(Mouse.Hit.X, I), Base.Position.Y+1, roundAToB(Mouse.Hit.Z, I)) * CFrame.Angles(0, math.rad(Rotation), 0))
PlacementSystemModule.StopPlacing()
InPlacingMode = false
elseif not InBoundary then
print("Out of bounds.")
PlacementSystemModule.PlaceObject()
elseif IsColliding then
print("Object already here.")
PlacementSystemModule.PlaceObject()
end
Debounce = true
end)
end
end
function PlacementSystemModule.StopPlacing()
Object:Destroy()
if not Mouse.Target then
return
end
if InPlacingMode then
Mouse.TargetFilter = nil
InPlacingMode = false
end
end
Please advise me on what the problem is and how I would go about fixing this. Thank you.