How to make an npc stick to walls

How do I make an npc walk on walls?

  1. Create your own pathfinding system.
  2. Set the CFrame of the NPC to equal the correct orientation of walking on the wall.

Yes… how…
30char30char30char30char

A custom pathfinding system isn’t easy to quickly type up, and will require quite a bit of research on your end.
The CFrame orientation on the other hand is very basic math with CFrame operations.

How do I get the correct CFrame you are not explaining it to me

That would depend on your pathfinding system.
Walking, turning its body, etc. is entirely dictated to the pathfinding.

Well, to get the correct CFrame I would guess that you’d have to find the normal of the surface/wall and do some calculations and plug the values into the cframe function to get your desired rotation and position on the wall. I suggest doing some research on this, I may be wrong but it seems like you’re bordering the line of getting spoonfed and I doubt you’d get far if we just give you the solution.

You can get the Normal from a RaycastResult.

Ray Cast
https://developer.roblox.com/en-us/api-reference/function/WorldRoot/Raycast

RayCastResult

The normal will tell you the Face that the ray hit.
You can plug the result into a Vector3 using the FromNormalId function to return a pointing director (vec3).

If you want that in Cframe format, add it to the second parameter of Cframe.new( pos, dir )

local npc = script.Parent --let’s just say this script inside your Npc model

local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Whitelist
raycastParams.FilterDescendantsInstances = {npc} -- ignore the Npc when casting the Ray
raycastParams.IgnoreWater = true
 
-- Cast the ray from the Npc ahead of them for 5 Studs
local part = npc.HumanoidRootPart
local raycastResult = workspace:Raycast(part.Position, part.CFrame.LookVector*5, raycastParams)


if raycastResult ~= nil then
   local normal = raycastResult.Normal
   local faceDirection = Vector3.FromNormalId(normal)
   local cframe = CFrame.new(part.Position, part.Position + faceDirection)
   -- continue to plug this faceDirection in to some medium that will cause the npc to stick to the wall such as a BodyGyro
end

The tricky thing you’re going to find is the pathfinder.

Theoretically you could take the wall your npc is walking on, copy it, hide it, rotate it so it becomes a plain, and run Roblox’s pathfinding solution on it if you didn’t want to develop your own PF solution, and then find some way of translating that path across the real wall, but that’s a lot of math that is out of my scope of knowledge.

https://developer.roblox.com/en-us/articles/Pathfinding

Have fun, good luck.

2 Likes