Please help me create a Tower Defense Tower Placement System

I’m a young scripter.. but I don’t know anything about tower defense deployment system (I can’t watch YouTube). I read books and asked AI, but nothing worked… Please help me..

2 Likes

We can break down a tower placement system as:

  • Click on screen
  • Validate click (see if the tower can actually be placed there)
  • Place model (tower)

The simplest way to get the location the mouse is clicking on is with player:GetMouse()

local PS = game:GetService("Players")
local UIS = game:GetService("UserInputService")

local player = PS.LocalPlayer
local mouse = player:GetMouse()

UIS.InputBegan:Connect(function(input, isTyping)
	if isTyping then -- if player is currently not focused on game (eg chatting)
		return
	end
	
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		local hitCFrame: CFrame = mouse.Hit -- cframe of mouseclick
		
		-- send information to server
	end
end)

Once you get hitCFrame on the client, we have to communicate that to the server. This (client-to-server) can be done with a RemoteEvent.

local remoteEvent: RemoteEvent = ...

-- inside inputbegan...
if input.UserInputType == Enum.UserInputType.MouseButton1 then
	local hitCFrame: CFrame = mouse.Hit -- cframe of mouseclick

	remoteEvent:FireServer(hitCFrame) -- send information to server
end

Then on the server, you can do your validation logic. If the CFrame is valid, place the tower to that CFrame.

local remoteEvent: RemoteEvent = ...

-- inside inputbegan...
remoteEvent.OnServerEvent:Connect(function(hitCFrame: CFrame)
	local isValid = false
	
	-- check if hitCFrame is valid, if yes then set isValid to true
	
	if isValid then
		-- place tower model
	end
end)
2 Likes

I’m pretty sure you have to put the player:GetMouse() inside the input began event, if not it would just get the position of the mouse when the script is run.

local PS = game:GetService("Players")
local UIS = game:GetService("UserInputService")

local player = PS.LocalPlayer

UIS.InputBegan:Connect(function(input, isTyping)
	if isTyping then -- if player is currently not focused on game (eg chatting)
		return
	end
	local mouse = player:GetMouse()

	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		local hitCFrame: CFrame = mouse.Hit -- cframe of mouseclick
		
		-- send information to server
	end
end)

Please correct me if i’m wrong

He was correct, the GetMouse method only returns the mouse object, so as long as you’re getting Mouse.Hit every heartbeat, you should be fine.

Oh i didnt knew that, sorry and thanks a lot

1 Like

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