Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Raycast not detecting NPC properly?

Asked by 2 years ago
Edited 2 years ago

Hello.

I've been working with raycasts for a little bit, but not that long, however never in my raycast practice have I run into a problem like this.

I'm trying to create a raycast from the character, pointing forward with CFrame.LookVector. The raycast does fire, however the detection for the NPC is the issue. I've attempted to use the Raycast Whitelist, and it does allow me to only detect the NPC, however the detection is still incredibly poor.

What happens is when I'm looking at this NPC, 90% of the time it will not detect any descendant instances of the NPC, and when it does, it's usually on a weird angle or only on one side.

This is the code I'm working with so far:

local NPC = script:WaitForChild("NPC").Value
local Player = game:GetService("Players").LocalPlayer

local Character = Player.Character or Player.CharacterAdded:Wait()
local HumanoidRootPart = Character:WaitForChild("HumanoidRootPart")

local function DetectNPC()
    local StartPosition = HumanoidRootPart.Position
    local TargetPosition = HumanoidRootPart.Position + HumanoidRootPart.CFrame.LookVector * 10

    local RaycastParameters = RaycastParams.new()
    RaycastParameters.FilterType = Enum.RaycastFilterType.Whitelist
    RaycastParameters.FilterDescendantsInstances = {
        NPC
    }

    local RaycastResult = workspace:Raycast(StartPosition, TargetPosition, RaycastParameters)

    if (RaycastResult) then
        local DetectedNPC = RaycastResult.Instance

        if (DetectedNPC) then
            local RealNPC = DetectedNPC:FindFirstAncestorOfClass("Model")

            print(RealNPC.Name)
        end
    end
end

while (task.wait()) do DetectNPC() end

There aren't any other scripts interfering with this script, and I've also found that at random times, waiting about 5 seconds only then will the raycast start detecting the NPC. I've tried to add a hitbox but it's the same story.

For anybody wondering, this script is located inside the Character, which is why the NPC is fetched through an ObjectValue, and this script is only ran once cloned from ReplicatedStorage to the Character.

If I could get help with this, it'd be great as I'm very lost with this at the moment. Thanks!

1 answer

Log in to vote
1
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
2 years ago

Humanoid.Position + is skewing the direction of your ray. Remove it.

0
Worked, thanks! RazzyPlayz 497 — 2y
Ad

Answer this question