So I am trying to make a game where I detect where the player is looking towards. I have decided to use RayCasts but I’ve ran into some issues. Whenever I run my code, It doesnt always come out the way I expect it. Heres my code:
wait(2)
local character = game.Players.LocalPlayer.Character
local Head = character.Head
local MyRayCast = Ray.new(Head.CFrame.p, Head.CFrame.LookVector * 100)
while wait() do
local part = workspace:FindPartOnRay(MyRayCast)
if part then
print(part.Name)
end
end
The problem with the code above is that even though I am looking directly at a part, it still wont print it. Please help.
You have to raycast per frame, in this case you’re only raycasting once when the script runs. Put the ray constructor inside the while loop.
while wait() do
local MyRayCast = Ray.new(Head.CFrame.p, Head.CFrame.LookVector * 100)
local part = workspace:FindPartOnRay(MyRayCast)
if part then
print(part.Name)
end
end
Are you using a script? If so, then you can’t directly access the player by using game.Players.LocalPlayer, you will have to use the PlayerAdded event and get the plr/character from there.
So probably like:
game.Players.PlayerAdded:Connect(function(player)
character = player.Character or player.CharacterAdded:Wait()
end)
local Head = character.Head
while wait() do
local MyRayCast = Ray.new(Head.CFrame.p, Head.CFrame.LookVector * 100)
local part = workspace:FindPartOnRay(MyRayCast)
if part then
print(part.Name)
end
end