I’ve been trying to raycast to detect when a NPC is approaching a wall within 5 studs. Does this look like the proper way to do it? I have an additional script that involves changing the NPCs walking direction to avoid walls, but for now it’s not seeming to work, and i’d like to know if the problem lies here.
That’s probably because you’re doing it wrong. Ray accepts two Vector values; an origin and a direction. You simply need to assign the first value as the HumanoidRootPart’s (not the Torso) position and the second value as 5 studs on the… I think X or Z axis, can’t remember.
I believe that each argument is handled in object space as opposed to world space.
local ray = Ray.new(script.Parent.HumanoidRootPart.Position, Vector3.new(0,0,-5))
--Create a ray that goes 5 studs in front of the character
local Part, Position = game.Workspace:FindPartOnRay(ray, script.Parent)
--Finds if there's a part hit, and where the ray ends, while ignoring the character
if Part then
--do your stuff here
end
Here is the remainder of the code. The NPC always follows a part called FollowPart, which is normally located behind and to the side of a player’s torso (Acts like a sidekick to a real player.) When a zombie gets nearby, the sidekick runs directly away from the zombie, which can be see in right below the section “if hit == nil” The code in the else, which should be running when the ray detects a wall should be placing the follow part in a location that makes the sidekick turn. I know that the math in that section is correct because I tested it out with a visible part myself.
It appears that you’re doing your raycasting right and the math for running away shall the raycast’s hit be nil. But the math for the turning is incorrect. Sadly, I’m not very experienced with this kind of math so I probably can’t help you further.