I'm making a tower defense game, and the placing system is not working

I am making a tower defense game, and I’m trying to make a placing system.

I am trying to set the CFrame of a part that the localscript creates to the mouse.Hit.

This is my code:

local button = script.Parent
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

button.MouseButton1Down:Connect(function()
	local part = Instance.new("Part")
	part.Parent = game.Workspace
	part.CFrame = mouse.Hit
end)

All of this is in a local script in a textbutton.
The problem is that it spawns the part, but the part doesn’t move.
I am getting no error.

you’re only setting the CFrame of the part one time, you’re not updating it. what i would suggest doing is updating it in a RenderStepped loop, and then disconnect it once the tower has been placed.

2 Likes

I’ve done this and it works, but the part keeps floating to the camera for a second before snapping to where it should be, and the part is rotated.
Code:

local button = script.Parent
local PlaceEvent = game.ReplicatedStorage:WaitForChild("Events").PlaceEvent
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local RS = game:GetService("RunService")

button.MouseButton1Down:Connect(function()
	local part = Instance.new("Part")
	part.Parent = game.Workspace
	RS.RenderStepped:Connect(function()
		part.CFrame = mouse.Hit
	end)
end)

Edit: I’ve done some more testing and it seems that the rotation of the part is related to the camera angle.

1 Like

that’s probably because the part has CanCollide set to true, which is on by default.
now, it should properly adhere to the cursor’s position.

local button = script.Parent
local PlaceEvent = game.ReplicatedStorage:WaitForChild("Events").PlaceEvent
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local RS = game:GetService("RunService")

button.MouseButton1Down:Connect(function()
	local part = Instance.new("Part")
	part.CanCollide = false
	part.Parent = workspace
	part.Size = Vector3.new(0.1, 2, 2)
	part.Material = Enum.Material.Neon
	part.Shape = Enum.PartType.Cylinder
	part.Transparency = 0.54
	part.Color = Color3.fromRGB(43, 255, 128)
	part.CFrame = part.CFrame * CFrame.Angles(0, 0, math.rad(90)) -- rotating 90 degrees due to it being a cylinder

	RS.RenderStepped:Connect(function()
		part.Position = mouse.Hit.p
	end)
end)

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