Hey again. This isn’t meant to be one of my bigger posts with an extremely useful resource, but I was bored and made this, and thought I should at least share it.
This module aids in helping you create a constraint-based worm using parts that are connected together. You can edit the module to your liking to change the parts, color, etc.
Of course I should note that this can be pretty laggy with more segments, but thats just how roblox parts are when you have a lot of them constrainted together. I’m not going to try and optimize this because I’m not really experienced in that field.
Model Link:
Picture:
Example Code:
local Worm = require(game:GetService("ServerScriptService"):WaitForChild("Worm")) -- require module
local myWorm = Worm.new(Vector3.new(0, 8, 0), 5) -- position: Vector3, segments: number
myWorm:Rebuild() -- Build worm body
Full Module Code:
local Worm = {}
Worm.__index = Worm
local function att(segment: BasePart, pos: number)
local att = Instance.new("Attachment")
att.Parent = segment
att.Position = Vector3.new(pos, 0, 0)
return att
end
function Worm.new(spawnPos: Vector3, segments: number)
return setmetatable({
SpawnPos = spawnPos,
Segments = segments,
WormModel = nil
}, Worm)
end
function Worm:Rebuild()
if self.WormModel ~= nil then
self.WormModel:Destroy()
end
local m = Instance.new("Model")
m.Name = "Worm"
local cache = {}
for x = 1, self.Segments do
local segment = Instance.new("Part")
segment.Anchored = false
segment.CanCollide = true
segment.Position = self.SpawnPos + Vector3.new(4.2, 0, 0)
local doBack = false
local doFront = false
local backAtt = nil
local frontAtt = nil
if x == 1 then
doBack = false
doFront = true
elseif x == self.Segments then
doBack = true
doFront = false
else
doBack = true
doFront = true
end
if doBack then
backAtt = att(segment, -2)
table.insert(cache, backAtt)
end
if doFront then
frontAtt = att(segment, 2)
table.insert(cache, frontAtt)
end
segment.Parent = m
end
local db = false
for index, att in ipairs(cache) do
db = not db
if not db then
local con = Instance.new("BallSocketConstraint")
con.Attachment0 = cache[index - 1]
con.Attachment1 = att
con.Parent = con.Attachment0
end
end
m.Parent = workspace
self.WormModel = m
end
return Worm