I need help with Raycasting. I have a script that is supposed to raycast and stop exactly at whatever part your mouse is on, and create a beam between the character and the object, like ODM gear from Attack on Titan, but this ends up happening:
While my mouse is aiming and it should raycast to the wall, it raycasts on some weird offset on my screen. and sometimes at certain angles it does go where I want it to, but in the second picture you can see it doesnt stop at the wall, and goes straight through it:
Heres the script:
local UserInputService = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local camera = workspace.CurrentCamera
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Blacklist
params.FilterDescendantsInstances = {}
local function rayResult()
local mouseUnitRay = mouse.UnitRay
return workspace:Raycast(mouseUnitRay.Origin, mouseUnitRay.Direction * 300, params)
end
local startRay = false
local currentRay = {}
UserInputService.InputBegan:Connect(function(key, isGameInput)
if isGameInput then return end
if key.KeyCode == Enum.KeyCode.E then
if not startRay then
print("StartRay")
startRay = true
local mousePos = mouse.Origin
local r = rayResult()
print(r)
local att1 = Instance.new("Attachment")
att1.Position = r.Position
att1.Parent = r.Instance
local beam = Instance.new("Beam")
beam.Attachment0 = game.Players.LocalPlayer.Character.ODM.Root.MidPoint
beam.Attachment1 = att1
beam.Color = ColorSequence.new({
ColorSequenceKeypoint.new(0, Color3.fromRGB(0,0,0)),
ColorSequenceKeypoint.new(1, Color3.fromRGB(0,0,0))
})
beam.Transparency = NumberSequence.new({
NumberSequenceKeypoint.new(0, 0),
NumberSequenceKeypoint.new(1, 0)
})
beam.Width0 = 0.1
beam.Width1 = 0.1
beam.Parent = beam.Attachment0
currentRay.Beam = beam
currentRay.Att0 = beam.Attachment0
currentRay.Att1 = beam.Attachment1
end
end
end)
UserInputService.InputEnded:Connect(function(key, isGameInput)
if isGameInput then return end
if startRay then
startRay = false
currentRay.Beam:Destroy()
currentRay.Att1:Destroy()
currentRay.Beam = nil
currentRay.Att0 = nil
currentRay.Att1 = nil
end
end)
I’ve never worked with Rays much before, so I’m probably doing something wrong. I tried to find topics on this on the devforum but I couldn’t really find any good information. Appreciate any help.