The :Raycast method has 3 arguments.
- Origin (positional) Vector 3
- Direction (directional, unit) Vector 3
- Other Parameters in form of RaycastParams (which can be used to exclude certain things)
If you look closely into your code, you can see that for your positional origin vector, you chose the look vector. The lookvector is a vector that could look like this: Vector3.new(1, 0, 0). It describes the direction that the front face of the part is looking in.
Therefore the first argument should be: mouse.Origin.Position
The second argument is also wrong. In that case we have to use a directional vector (so something like seen above) and multiply it by a max length of the raycast
Therefore the second argument should be: mouse.Origin.LookVector*10
The third argument is optional but I advise you to ignore the player’s character by doing the following:
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Exclude
params.FilterDescendantsInstances = {player.Character}
Here are all of my changes in one script:
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Exclude
params.FilterDescendantsInstances = {player.Character}
local function raycast()
local result = workspace:Raycast(mouse.Origin.Position, mouse.Origin.LookVector*200, params)
return result
end
And here is your updated version (I highly advise you to still read the rest of my post if you haven’t):
local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse()
local tool = script.Parent
local selectedPart = workspace:WaitForChild("SelectedPart")
local maxDistance = 15 --in studs
local equipped = false
---------------------
local function raycast()
local result = workspace:Raycast(mouse.Origin.Position, mouse.Origin.LookVector*maxDistance, params)
return result
end
---------------------
mouse.Move:Connect(function()
if equipped then
local raycast = raycast()
if raycast == nil then return end
if raycast.Instance.Name == "Ground" then --only runs when raycast isn't nil
selectedPart.Position = raycast.Position
end
end
end)
tool.Activated:Connect(function()
local raycast = raycast()
if raycast == nil then return end
if raycast.Instance.Name == "Ground" and raycast.Instance.Color == Color3.fromRGB(71, 101, 15) then
raycast.Instance.Color = Color3.fromRGB(72, 64, 35)
end
end)
tool.Equipped:Connect(function()
selectedPart.SurfaceGui.Frame.Visible = true
equipped = true
end)
tool.Unequipped:Connect(function()
selectedPart.SurfaceGui.Frame.Visible = false
equipped = false
end)
---------------------