How to go about scaling meshes based on the size of a part?

In my game, I want players to be able to load in any mesh that they want. The problem is that all meshes are sized differently, and some can be really huge when inserted. I want to be able to size large meshes down based on the size of the part they are being applied to. Say the part is 4x4x4 studs, the mesh being applied to the part should be scaled down to fit within those dimensions.

How would I go about doing this? Assuming I can access the mesh size (through MeshPart.MeshSize) and knowing the size of the part the mesh is being applied to. The solution is probably some sort of mathematical calculation based on the MeshSize and PartSize. Any ideas on how to do this? The mesh will eventually be applied as a SpecialMesh to the part (meaning it’s not a MeshPart), so I would imagine the solution to this would also involve adjusting the scale of the SpecialMesh too?

If you copy the size, insert the new mesh then put the size back in it should go back to the size you had it at. Looks like I tired scaling at some point but scraped it. I left myself this script… Not sure if it is fully working.

local function scaleMeshToFit(part, mesh)
    local partSize = part.Size
    local meshSize = mesh.MeshSize

    local scaleFactorX = partSize.X / meshSize.X
    local scaleFactorY = partSize.Y / meshSize.Y
    local scaleFactorZ = partSize.Z / meshSize.Z

    local scaleFactor = math.min(scaleFactorX, scaleFactorY, scaleFactorZ)
    mesh.Scale = Vector3.new(scaleFactor, scaleFactor, scaleFactor)
end

local part = workspace.Part -- apply mesh to part
local specialMesh = Instance.new("SpecialMesh", part)
specialMesh.MeshId = "rbxassetid://123456789"
specialMesh.MeshSize = Vector3.new(10, 15, 5) 

scaleMeshToFit(part, specialMesh)

This is perfect! Thanks so much, I just couldn’t wrap my brain around the math but it’s exactly what I needed!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.