Block placement sometimes goes inside another block

I’m making a basic block system thing. my code is just

block.CFrame = CFrame.new(2+(math.floor(pos.x/4))*4, 2+(math.floor(pos.y/4))*4, 2+(math.floor(pos.z/4))*4)

This works for the most part but sometimes when I click on another block, the block does spawn, but it spawns inside the block I clicked on, what can I do? This mostly happens when I click a block from the side, not the top.

Post more of your code so we can have a look! :slight_smile:

I’m guessing pos is just the 3D position of the mouse, i.e. mouse.Hit.p? In that case, rounding the position will sometimes put it inside the block that was just clicked. You can force it to be offset from where you clicked kind of like this:

local normal = mouse.Target.CFrame:VectorToWorldSpace( Vector3.FromNormalId(mouse.TargetSurface) )
local pos = mouse.Hit.p
--then round the pos like you did before
pos += normal * BLOCK_SIZE

If you think about it, you never actually want to place the block where you clicked the mouse. You want to place the block next to the block that was clicked, depending on which face of the block was clicked.


One thing to keep in mind is that this still doesn’t really prevent someone from placing a block inside another block, if it’s still possible in any way to click the face of a block that’s already occupied. You will need to do some kind of logic to check if there’s already a block in a given spot, and not allow a block to be placed at all in that case.

3 Likes

Late response but I found an alternative to what I was doing, thanks for trying to help though!

1 Like

Sorry to bump this but how did you do it? I’m trying to fix the same issue and I can’t find anything.

1 Like

I asked another friend, and what he did is that is that he used the Mouse.TargetSurface thing to check the surface of the block the mouse was on, and then place it at the block’s position and offset it depending on what surface the mouse clicked on.

1 Like