Help with Raycasting

Hello, My name is Light.
Today I was working on a placement system, it works by Equipping a tool and aiming where you want to place the object. I was able to complete it all except for the Raycasting because I have never used rays before and was quite confused as to how they worked.

Below is my attempt which did not work, if anyone could help me understand how to fix this I would highly appreciate. (Raycasting starts at line 15)

local hammer = script.Parent
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local cycleVal = 1
local chosenBuildable = "Floor"
local previewBuildable
local canBuild = true

hammer.Equipped:Connect(function(mouse)
	
	viewBuildable()
	
	mouse.Move:Connect(function()
		
		local raycastParams = RaycastParams.new()
		raycastParams.IgnoreWater = true
		raycastParams.FilterDescendantsInstances = {previewBuildable}
		raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
		local raycastResult = workspace:Raycast(hammer.Handle.Position, Vector3.new(100, 0, 0), raycastParams)
		
		if raycastResult ~= nil then
			previewBuildable.Position = raycastResult.Position
		end
		
		if canBuild == true then
			previewBuildable.Color = Color3.new(0, 1, 0)
		elseif canBuild == false then
			previewBuildable.Color = Color3.new(1, 0, 0)
		end
	end)
	
	mouse.Button1Down:Connect(function()
		if canBuild == true then
			ReplicatedStorage:WaitForChild("RemoteEvents"):WaitForChild("createBuildable"):FireServer(chosenBuildable, previewBuildable.Position)
		end
	end)
	
	mouse.Button2Down:Connect(function()
		cycleVal += 1
		if cycleVal > 2 then
			cycleVal = 1
		end
		if cycleVal == 1 then
			chosenBuildable = "Floor"
		elseif cycleVal == 2 then
			chosenBuildable = "Wall"
		end
		viewBuildable()
	end)
end)

function viewBuildable()
	if previewBuildable ~= nil then
		previewBuildable:Destroy()
	end
	previewBuildable = ReplicatedStorage:WaitForChild("Buildables"):FindFirstChild(chosenBuildable):Clone()
	previewBuildable.Parent = workspace["Short-Term"]
	previewBuildable.Transparency = .5
	previewBuildable.Material = "Plastic"
	previewBuildable.CanCollide = false
end

hammer.Unequipped:Connect(function()
	previewBuildable:Destroy()
end)

Thank you and have a great day!

1 Like

You seem to be raycasting to the world right is this what you want? or d oyou want this from the mouse out

I don’t understand your question.

so you want a preview build where your mouse is aiming in game?

Yes, whereever the mouse is aiming is where previewBuildable should be.

raycasting from the mouse out isnt needed you just need mouse.hit.Position

I tried that but it causes mouse.Hit.Position to collide with previewBuildable creating a very ugly scene.

Hmm i see use mouse.TargetFilter

mouse.TargetFilter = previewBuildable
1 Like

oh wow, I wasn’t aware that was a thing thank you.

No problem, happy to help! :slight_smile:

1 Like