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

How can I make a player able to pass through a walking NPC?

I'm creating an RPG in which players fight monsters. These monsters are player-like NPCs, so they have humanoids, animations, etc. If this was just a standing NPC, I could easily use a BodyGyro and make all their limbs CanCollide, but how would I accomplish this if the NPC were, say, walking?

I've taken a look at this script for how to make players pass through one another, but I have no idea how to apply it to NPCs. Script

2 comments

1

When do you create the NPC's or are they already in the world? Ideally you would want to add them to another CollisionGroup whenever you create them just like the link you gave.

1

learning how to adapt related code made by others for your own use is an important skill

1 answer

✓ Accepted answer

Solution


The easiest and most efficient way to achieve this would be using collision groups.

Physics service


Most things involving collision groups use the Physics service, which can create collision groups and disable/enable collision between collision groups.

For the purpose of disabling NPC to NPC collision, the :CreateCollisionGroup() function and the :CollisionGroupSetCollidable() function can be used. The former creates a collision group with a given name and the latter enables/disables collisions between two groups or members of the same group

Application


With all said, time to put the functions into effect :3

step 1: reference the physics service

step 2: create an NPC collision group

step 3: disable collisions for members of that group

step 4: add all bodyparts of the NPCs to the NPC collision group

local PS = game:GetService("PhysicsService")--1
local NPCs = workspace.NPCs

local CollisionGroupName = "NPCs"

PS:CreateCollisionGroup(CollisionGroupName)--2
PS:CollisionGroupSetCollidable(CollisionGroupName, CollisionGroupName, false)--3

local function SetCGRecursive (object)
	if object:IsA("BasePart") then
		PS:SetPartCollisionGroup(object, CollisionGroupName)--4
	end
	for _,child in next, object:GetChildren() do
		SetCGRecursive(child)
	end
end

for _,NPC in pairs(NPCs:GetChildren()) do
	SetCGRecursive(NPC)
end

Additional things


Also, as you are making an RPG which probably involves combat, you can use the ChildAdded function to see when something has been parented to another object

Ex:

NPCs.ChildAdded:Connect(function(child)
	SetCGRecursive(child)
end)

A couple of reference links:

tutorial for disabling player-player collisions

Physics Service

Generic for loops

Generic for loops 2

recursive functions

child added

Hopefully this helped and have a great day!

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