terminalCode Example
NPC Ragdoll Creation with Clothing Preservation
NPC Ragdoll Creation with Clothing
Pattern for creating ragdolls from NPCs including clothing preservation and bone merging.
CSHARP
[Rpc.Broadcast(NetFlags.HostOnly)]
protected void CreateRagdoll(Vector3 velocity, Vector3 origin, float duration = 30)
{
if (!Renderer.IsValid()) return;
var go = new GameObject(true, "Ragdoll");
go.Tags.Add("ragdoll");
go.WorldTransform = WorldTransform;
var mainBody = go.Components.Create<SkinnedModelRenderer>();
mainBody.CopyFrom(Renderer);
mainBody.UseAnimGraph = false;
// Copy clothing with bone merge
foreach (var clothing in Renderer.GameObject.Children
.SelectMany(x => x.Components.GetAll<SkinnedModelRenderer>()))
{
if (!clothing.IsValid()) continue;
var newClothing = new GameObject(true, clothing.GameObject.Name);
newClothing.Parent = go;
var item = newClothing.Components.Create<SkinnedModelRenderer>();
item.CopyFrom(clothing);
item.BoneMergeTarget = mainBody;
}
var physics = go.Components.Create<ModelPhysics>();
physics.Model = mainBody.Model;
physics.Renderer = mainBody;
physics.CopyBonesFrom(Renderer, true);
ApplyRagdollForce(physics, velocity, origin);
// Cleanup after duration
mainBody.Invoke(duration, mainBody.DestroyGameObject);
}Key APIs
- SkinnedModelRenderer.CopyFrom() — copies model, materials, and settings from another renderer
- BoneMergeTarget — attaches clothing to the ragdoll's skeleton
- ModelPhysics.CopyBonesFrom() — transfers bone poses from the live renderer to the ragdoll
- Invoke(duration, callback) — schedules cleanup after the ragdoll lifetime expires
Was this helpful?