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
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.”