Need help figured out what's wrong with this Code

This line of code is meant to see what a player is looking at and give me the name of that item but it keeps saying “No Part Was Hit” do any of you guys know what I did wrong?

local player = game.Players.LocalPlayer
local camera = workspace.CurrentCamera
local playerPosition = camera.CFrame.Position
local playerDirection = camera.CFrame.LookVector

local ray = Ray.new(playerPosition, playerDirection * 100)  -- Create a ray
local hitPart = workspace:FindPartOnRay(ray)  -- Perform the raycast
while wait(2) do
if hitPart then
	print("Hit part name: " .. hitPart.Name)
	-- Additional actions based on the hit part can be performed here
else
	print("No part was hit.")
end
end
1 Like

I see. The issue is that the raycast is being performed only once outside the loop. Therefore it doesn’t update as the player’s view changes. You should move the raycast inside the loop to keep checking what the player is looking at. Updated version >>>>


local player = game.Players.LocalPlayer
local camera = workspace.CurrentCamera

while wait(2) do
    local playerPosition = camera.CFrame.Position
    local playerDirection = camera.CFrame.LookVector

    local ray = Ray.new(playerPosition, playerDirection * 100)  -- Create a ray
    local hitPart = workspace:FindPartOnRay(ray)  -- Perform the raycast

    if hitPart then
        print("Hit part name: " .. hitPart.Name)
        -- Additional actions based on the hit part can be performed here
    else
        print("No part was hit.")
    end
end

This will check every 2 seconds what the player is looking at and print the name of the hit part if any. If no part is hit it will print “No part was hit.”

2 Likes

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