Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Raycast not detecting player?

In this script, I have an NPC who shoots out raycasts from his head in a radius to see if any players are in that radius. However, in texting the player is only detected if really close. What am I doing wrong?

local fov = 20 
local dist = 100 
local monster = script.Parent.Head 

function MakeRay(startPos, endPos, show) 
        local ray = Ray.new(startPos, endPos)
        local obj, endPoint = workspace:FindPartOnRay(ray)
        if show then 
            local rayPart = Instance.new("Part", workspace)
            rayPart.Name          = "RayPart"
            rayPart.BrickColor    = BrickColor.new("Bright red")
            rayPart.Transparency  = 0.5
            rayPart.Anchored      = true
            rayPart.CanCollide    = false
            rayPart.TopSurface    = Enum.SurfaceType.Smooth
            rayPart.BottomSurface = Enum.SurfaceType.Smooth
            rayPart.formFactor    = Enum.FormFactor.Custom
            rayPart.Size          = Vector3.new(0.2, 0.2, dist)
            rayPart.CFrame        = CFrame.new(startPos, Vector3.new(endPos.x,1.5,endPos.z)) * CFrame.new(0, 0, -dist/2)
			
            game.Debris:AddItem(rayPart, 0.1) 
        end
        return obj 
end

while true do

    local start = -180-(fov/2) 
    for t = start, start+fov, 5 do 
        local target = monster.CFrame 

                    * CFrame.new(dist*math.sin(math.rad(t)), monster.Position.Y, dist*math.cos(math.rad(t))) 
                    * monster.CFrame.lookVector 
	
        local hit = MakeRay(monster.CFrame.p, target, true) 
        if hit then 
            if hit.Parent:FindFirstChild("Humanoid") then 
                print("Humanoid in sight")
            end
        end

    end
    game:GetService("RunService").RenderStepped:wait()
end

Thanks!

2 answers

Try using this:

while wait(5) do
for i,v in pairs(game.Players:GetChildren()) do
local dis = math.floor((script.Parent.HumanoidRootPart.Position - v.Character.HumanoidRootPart.Position).magnitude )--Assuming that the script is in the character of the NPC..
if dis <= [DISTANCE HERE] then
--Shoot the player here.
end
end
end

I haven't tested any of this but what this script should do is calculate the distance of a player every 5 seconds.

1 comment

0

P.S. The while wait(5) loop MIGHT take some CPU usage so, if you want, use other method. Hope I helped.

This discussion is preserved as it was. New answers, comments, and votes are closed.