I am trying to make a tool with a base attachment point and a free-floating attachment point, where the free-floating attachment takes the CFrame returned by the ray cast from the base attachment to the mouse location. I am trying to follow a Roblox tutorial (https://create.roblox.com/docs/tutorials/scripting/intermediate-scripting/hit-detection-with-lasers#toolcontroller) to get an idea of how to make the tool and raycast functions work, but I am only getting a print message that the initial ray cast hit nothing.
My code is pasted here:
local runService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local tweenservice = game:GetService("TweenService")
local tool = script.Parent
local maxmouse = 1000
local maxbeam = 500
local soundservice = game.SoundService
local Equip = soundservice["Boom (SFX)"]
local rayattachment = tool:FindFirstChild("AttachmentRaycast")
local movingattachment = tool:FindFirstChild("AttachmentBeam")
--Tracker
local function getWorldMousePosition()
local mouselocation = UserInputService:GetMouseLocation()
local rayorigin = workspace.CurrentCamera:ViewportPointToRay(mouselocation.X, mouselocation.Y)
local rayorient = rayorigin.Direction * maxmouse
local raycastresult = workspace:Raycast(rayorigin.Origin, rayorient)
if raycastresult then
print("I hit something")
return raycastresult.Position
else
print("I hit nothing")
return rayorigin.Origin + rayorient
end
end
local function findattachmentpoint()
local mousefinal = getWorldMousePosition()
local targetDirection = (mousefinal - tool.Handle.Position).Unit
local attachvector = targetDirection * maxbeam
local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {Players.LocalPlayer.Character, tool}
local finalraycastresult = workspace:Raycast(tool.Handle.Position, attachvector, raycastParams)
if finalraycastresult then
return finalraycastresult.CFrame
else
return tool.Handle.Position + attachvector
end
end
local function scanray()
local finalraycast = findattachmentpoint()
local waittime = 0.1
local tweeninfo = TweenInfo.new(waittime)
local tweentable = {CFrame = movingattachment.CFrame + Vector3.new(finalraycast.CFrame.X, finalraycastresult.CFrame.Y, finalraycastresult.CFrame.Z)}
tweenservice:Create(movingattachment, tweeninfo,tweentable)
:Play()
task.wait(waittime) do
end
end
local function toolEquipped()
active = true
Equip:Play()
while active == true do
wait()
getWorldMousePosition()
end
end
local function toolUnequipped()
active = false
end
I am honestly completely unsure (as a very amateur coder) as to why the first raycast is never hitting anything, any input is greatly appreciated!