#Raycast sometimes returns nil

8 messages · Page 1 of 1 (latest)

urban stump
#

then the raycast didnt hit anything

verbal hornet
#
local gun = script.Parent
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local camera = game.Workspace.CurrentCamera

local damage = 10
local rayLength = 500 -- Extend the ray length

local function Shoot()
    local block = gun:FindFirstChild("block") -- Ensure the block part is correctly referenced
    if not block then
        return
    end
    
    local target = mouse.Hit
    local direction = (target.Position - block.Position).Unit * rayLength

    local rayParams = RaycastParams.new()
    rayParams.FilterDescendantsInstances = {gun} -- Optional: Add gun to the filter to ignore it
    rayParams.FilterType = Enum.RaycastFilterType.Blacklist

    local raycast = workspace:Raycast(block.Position, direction, rayParams)
    
    if raycast then
        print("Raycast hit: ", raycast.Instance.Name)
        local hitInstance = raycast.Instance
        local humanoid = hitInstance.Parent:FindFirstChild("Humanoid") or hitInstance.Parent.Parent:FindFirstChild("Humanoid")
        
        if humanoid then
            humanoid:TakeDamage(damage)
        else
            print("Hit but no humanoid found")
        end
    else
        print("Raycast did not hit anything")
    end
end

mouse.Button1Down:Connect(Shoot)

Try this

#

I think your problem is the distance of the raycast

#

and you also didnt define any parameters for it

#

define the raycast parameters

strange daggerBOT
#

studio** You are now Level 5! **studio

verbal hornet
#

mb its exclude now

#

aight gl