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

Copy part directly on top of itself? [Math heavy]

Asked by 4 years ago

Hello! I've been working on recreating the classic roblox copy tool and I wanted it to be able to copy a part and place that copy directly on top of the original part, as close as it can be without intersecting it. I noticed that when turning Collisions on from roblox studio, pressing Ctrl + D while selecting a part reproduces the desired functionality, as shown in the following pictures:

Before copying

After copying

I then tried to recreate that with the following script placed inside game.Workspace:

local part = game.Workspace.Part -- The part to be copied
local newPart = part:Clone()
newPart.Parent = game.Workspace
newPart.BrickColor = BrickColor.new("Pastel yellow")
local maxCos = part.Size.Y/math.sqrt(part.Size.X^2+part.Size.Y^2)

while true do
    local a = part.CFrame.UpVector
    local b = Vector3.new(0,1,0)
    local cross = math.abs(a:Dot(b))
    if cross >= maxCos then
        newPart.CFrame = part.CFrame + Vector3.new(0,part.Size.Y/cross,0)
    else
        cross = math.sqrt(1-cross^2)
        newPart.CFrame = part.CFrame + Vector3.new(0,part.Size.X/cross,0)
    end
    wait()
end

The previous script works fine as long as it's used on a part rotated along the X or Y axis, as show in the following gifs:

Along the X axis

Along the Y axis

However, undesired results arise when trying to run the script on parts rotated along the Z axis:

Along the Z axis

How can I fix the script for it to work on parts rotated in any direction? Any form of documentation about the subject, even if it does not directly answer my question, would be greatly appreciated.

Answer this question