Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I get the center CFrame of a model?

Asked by 5 years ago

In my game, players are allowed to add various parts to their pets which can extend side ways, up and down as well as back and fourth, the problem is with this is that if a player adds an item that significantly extends forwards or below, it could over lap with the players shoulders or the floor respectively. I went about this by dividing the the Pet size by 2 and adding it onto the original position which is about 3 studs back, 2 studs high and 2 studs to the right. And it works relatively okay, but the limitation is that the part that makes that contains the BodyPosition to make the Pet float is no longer in the center. I was planning to do some fancy calculations by comparing the CFrame of the model to the CFrame of the part that holds the BodyPosition.

Would anyone else do this any differently?

1 answer

Log in to vote
1
Answered by
fredfishy 833 Moderation Voter
5 years ago
Edited 5 years ago

After ROBLOX very cleverly deprecated :GetModelCFrame without providing an actual alternative, the answer here is the undocumented function :GetBoundingBox()

boxCFrame, boxSize = model:GetBoundingBox()

Using this you should be able to work out exactly what you want to know.

Here's an example of spawning a bunch of random bricks, and then creating a part representing the bounding box of all of them.

function ran(range)
    return (math.random() * 2 - 1) * range
end

parent = Instance.new("Model", workspace)

for i = 1, 25 do
    local p = Instance.new("Part")
    p.Size = Vector3.new(2, 2, 2)
    p.Anchored = true
    p.CFrame = CFrame.new(ran(10), ran(10), ran(10))
             * CFrame.Angles(ran(math.pi), ran(math.pi), ran(math.pi))
    p.Parent = parent
end

modelCFrame, modelSize = parent:GetBoundingBox()

boxSize = parent:GetExtentsSize()
box = Instance.new("Part")
box.Transparency = 0.8
box.Size = modelSize
box.Anchored = true
box.CFrame = modelCFrame
box.Parent = workspace

Obviously since this function is undocumented I'd be careful about it's use, and don't expect it to stay consistent in future. However, at present time it seems to be the best thing available, and it isn't deprecated.

Also from reading some stuff on the ROBLOX dev forums, it looks like it might be an O(n^3) operation, so use it sparingly. I'd store the result every time you update the pet, and then reuse it, rather than trying to recalculate it in a while loop or something.

Example of executed script here

1
Lovely explanation thanks so much! Marmalados 193 — 5y
Ad

Answer this question