I need help with another script

Ok so im working on a small tds type project and a ran into another problem. Whenever im trying to spawn a tower the tower keeps on flying into the camera, idk how to fix this so here is the script:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local towers = ReplicatedStorage:WaitForChild("Towers")
local Camera = workspace.CurrentCamera
local gui = script.Parent
local towerToSpawn = nil

local function MouseRaycast(exclude) 
	local MousePosition = UserInputService:GetMouseLocation()
	local MouseRay =Camera:ViewportPointToRay(MousePosition.X, MousePosition.Y)
	local raycastParams = RaycastParams.new()
	
	raycastParams.FilterType = Enum.RaycastFilterType.Exclude
	raycastParams.FilterDescendantsInstances = exclude
	
	local raycastResult = workspace:Raycast(MouseRay.Origin, MouseRay.Direction * 1000)
	

	return raycastResult
end

local function AddPlaceholderTower(name)
	local towerExsits = towers:FindFirstChild(name)
	if towerExsits then
		towerToSpawn = towerExsits:Clone()
		towerToSpawn.Parent = workspace.Towers
	end
end

gui.Spawn.Activated:Connect(function()
	AddPlaceholderTower("Slinger")
end)

UserInputService.InputBegan:Connect(function(input, processed)
	if processed then
		return
	end

	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		end
end)
RunService.RenderStepped:Connect(function()
	if towerToSpawn  then
		local result = MouseRaycast({towerToSpawn})
		if result and result.Instance then
			local x = result.Position.X
			local y = result.Position.Y
			local z = result.Position.Z
			local cframe = CFrame.new(x,y,z)
			towerToSpawn:SetPrimaryPartCFrame(cframe)
	end

	end
end)

no error in output so im a bit confused.
thx in advance, im new to scripting. :smiley:

1 Like

Does anyone know how to help .
Video demonstration:

I’m gonna assume it’s the fact that you never reset towerToSpawn after setting the tower’s CFrame.

I will try when I come back from outside

while i was gone i released my mistake in line

local raycastResult = workspace:Raycast(MouseRay.Origin, MouseRay.Direction * 1000)

i forgot to add ,raycastParams
so now it would be

local raycastResult = workspace:Raycast(MouseRay.Origin, MouseRay.Direction * 1000, raycastParams)
	

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