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

How do I align a part against another part?

Asked by 3 years ago

Hi, I'm trying to create a little building system for me to experiment with. I've got the mouse and everything working, but for example when I move the 'ghost part' against the ground or against another part it kind of goes inside. Here is my code:

--this is just a test for the part preview
--i know i havent added anything for when you unequip the tool, ignore that please
--localscript
script.Parent.Equipped:Connect(function()
    local plr = game.Players.LocalPlayer
    local mouse = plr:GetMouse()
    local tool = script.Parent
    local selectionpart = Instance.new("Part", game.Workspace.SelectionPart)
    selectionpart.Anchored = true
    selectionpart.CanCollide = false
    selectionpart.Transparency = 0.5
    selectionpart.CFrame = CFrame.new(mouse.Hit.Position)
    mouse.TargetFilter = game.Workspace.SelectionPart
    mouse.Move:Connect(function(p)
        selectionpart.CFrame = CFrame.new(mouse.Hit.Position)
    end)

end)

Another small question if it isn't too much, how would I also go about making the part move on an increment (e.g it only moves 1 stud) Thanks!

1 answer

Log in to vote
1
Answered by
imKirda 4491 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago

Your issue happens because .Position represents center position of the part, your solution is to move the part by half on some axis, which one? -> mouse.TargetSurface, Vector3.fromNormalId will return you unit vector that represents direction into given NormalId which in hooman words is surface:

selectionpart.CFrame = CFrame.new(mouse.Hit.Position)
  + Vector3.fromNormalId(mouse.TargetSurface) * selectionpart.Size / 2

Note that mouse.Hit might be nil if you are moving mouse on the sky, you should probably add an if statement checking if it exists:

if mouse.Hit then
    [...]
end

You may notice that your part can still go into parts on other axeses, whatever, I don't know how to fix that. >wO

Nor do I know how to snap to grid UwU Ow< but here is some math professor who knows what he is talking about https://devforum.roblox.com/t/snapping-to-grid/286899

0
Thanks for taking the time to answer, I'll try it out and also refer to the devforum post you linked at the bottom :) HauntedDestroyer 106 — 3y
Ad

Answer this question