I wrote a little function to make this easier, because I position new parts a lot, and I needed a universal tool.
This function will cover all your displacement scenarios.
You will need to write a bit more code to add any rotation though.
It’s may not be that clear how it works by reading the code, so here’s the gist:
Let’s just consider placement along the X-axis for simplicity.
You have a parent block and a child block.
Here are the parameters you need to consider:
- Do you want the offset distance to be measured from the parent’s left edge or right edge?
- Do you want the offset distance to be measured to the child’s left edge or right edge?
Example:
Suppose you have a parent part, and you want the child to be positioned to the right of the parent, but offset by 3 studs.
This means you want to measure 3 studs from the parent’s right edge, and position the child’s left edge there. (I will just assume you want to the Y and Z faces of the parent and child to be aligned on their edges closest to the origin.)
Here’s how to use my function to position your child part:
(1 means true, -1 means false)
childPart.CFrame = setCFrameFromDesiredEdgeOffset(
{
parent = parentPart,
child = childPart,
offsetConfig = {
useParentNearEdge = Vector3.new(1, -1, -1), -- the 1 here means measure from the X edge farthest from the origin
useChildNearEdge = Vector3.new(-1, -1, -1),
offsetAdder = Vector3.new(-3, 0, 0)
}
})
And here is my function
function setCFrameFromDesiredEdgeOffset(props)
local parent = props.parent
local child = props.child
local offsetConfig = props.offsetConfig
local defaultOffsetAdder = Vector3.new(0, 0, 0)
local defaultOffsetConfig = {
useParentNearEdge = Vector3.new(0, 1, -1),
useChildNearEdge = Vector3.new(0, -1, 1),
offsetAdder = defaultOffsetAdder
}
offsetConfig = offsetConfig or defaultOffsetConfig
local offset = (offsetConfig.useParentNearEdge * parent.Size -
offsetConfig.useChildNearEdge * child.Size) / 2 +
(offsetConfig.offsetAdder or defaultOffsetAdder)
local newCFrame = CFrame.new(offset)
return parent.CFrame:ToWorldSpace(newCFrame)
end