This simple code isn't working

Pretty straight forward, I cast a ray to detect a part, it should print clear if theres nothing and print the part name if there is something

…but its detecting nothing

Code-

--setup ray
local rayPars = RaycastParams.new()
    rayPars.FilterType = Enum.RaycastFilterType.Whitelist
    rayPars.FilterDescendantsInstances = {workspace.STRUCTURES}
    local ray = workspace:Raycast(hrp.Position, Vector3.new(cf.Position.X, hrp.Position.Y, cf.Position.Z), rayPars)
    local pos = Vector3.new(cf.Position.X, hrp.Position.Y, cf.Position.Z)
    local origin = hrp.Position
    local distance = (origin - pos).Magnitude

    --create a test part
    local p = Instance.new("Part", workspace)
    p.Anchored = true
    p.CanCollide = false
    p.Transparency = 0.5
    p.Material = Enum.Material.Neon
    p.Color = Color3.new(0, 1, 0)
    p.Size = Vector3.new(3, 3, distance)
    p.CFrame = CFrame.lookAt(origin, pos)*CFrame.new(0, 0, -distance/2)
    
    -- detect the ray
    if ray then
        if ray.Instance then
            print(ray.Instance.Name)
            rayed(ray.Instance)
        else
            default()
        end
    else
        print("clear")
        default()
    end

Visual-

Similar problem

In your code the second parameter uses position values, and position is not equal to direction which raycast needs.

1 Like

Thank you so, so much, I can’t believe I never payed attention to this in all my years of programming, this will help me out more than you know.

local goal = Vector3.new(cf.Position.X, hrp.Position.Y, cf.Position.Z)
local unit = (hrp.Position - goal).Unit --a unit vector is a directional vector with a magnitude of 1 (1 stud)
local direction = unit * 200 --200 represents range (distance in studs), this maintains the vector's direction but increases its magnitude

local ray = workspace:Raycast(hrp.Position, direction, rayPars)

This is how you would go about achieving that solution.