How to Fire a Raycast from the Direction of a Players Head?

Hey there other devs,

I’ve been searching through the Forum a bit, but most of the information on there is outdated about raycasting from the head.

I wanted it so when a Player presses the key F there would be a raycast that comes from the direction of the camera, and then checking to see if it hits an object in the workspace.

Thanks a lot!

Local script because user input service

local UserInputService = game:GetService("UserInputService")

UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
    if gameProcessedEvent then return end
    if input.KeyCode == Enum.KeyCode.F then
        fireRaycast()
    end
end)

Ray Cast main part

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")

function fireRaycast()
    local player = Players.LocalPlayer
    local camera = Workspace.CurrentCamera
    local cameraPosition = camera.CFrame.Position
    local mousePosition = player:GetMouse().Hit.p
    local direction = (mousePosition - cameraPosition).unit * 500 -- Change 500 to your desired ray length

    local raycastParams = RaycastParams.new()
    raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
    raycastParams.FilterDescendantsInstances = {player.Character} -- Ensures the ray doesn't hit the player's own character

    local raycastResult = Workspace:Raycast(cameraPosition, direction, raycastParams)
    if raycastResult then
        print("Hit: ", raycastResult.Instance.Name)
        -- You can do something with the object hit here
    end
end
1 Like

it says blacklist is deprecated
image

oh nvm it works mb thanks a lot

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.