Help with block placing math

I am trying to make a little system where, I have a frame that is located where the mouse is, and when I click the button, it places a block.

The blocks are 4x4 and aligned with the grid on the baseplate of a new place in studio.

image

The problem is when the cursor moves over an already placed block.
I am raycasting, and so the raycast detects edge of the block the cursor is on.

However, due to the math, if the cursor touches the Back, Top, or Right of the block, it correctly places the frame to place a new block
image
image
image

But if the cursor touches the Front, Bottom, or Left of the block, it calculates the location to be where the current block is, placing the cursor ON the SAME location as the block
image

So, is there anything I need to adjust with my math to account for this?

The raycast gives an instance value, so I could always detect which direction from the center of the hit instance, is the hit position, but I figured that might be a bit hacky if there is a more mathematical solution.

There is the code for this little project

local mouse = game.Players.LocalPlayer:GetMouse()
local BlockPos = Vector3.new(0,0,0)
local GridPos = Vector3.new(0,0,0)


mouse.Button1Down:Connect(function()
	local p = part:Clone()
	p:PivotTo(CFrame.new(BlockPos))
	p.Parent = workspace
end)


function DoRayCast()
	local ray = mouse.UnitRay
	
	local rayOrigin = ray.Origin
	local rayDirection = ray.Direction * 500

	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {script.Parent,marker}
	raycastParams.FilterType = Enum.RaycastFilterType.Exclude
	raycastParams.IgnoreWater = true

	local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
	if raycastResult then
		local pos = raycastResult.Position
		GridPos = Vector3.new(math.floor(pos.x/4),math.floor(pos.y/4),math.floor(pos.z/4))
		BlockPos = Vector3.new((GridPos.X*4)+2,(GridPos.Y*4)+2,(GridPos.Z*4)+2)
		marker.CFrame = CFrame.new(BlockPos)
	end
end

while true do
	DoRayCast()
	task.wait()
end

Any help is appreciated, thanks.

1 Like

I know nothing about raycasting- so would it be a good idea to create your own custom grid that restricts the blocks to x stud distances?

I sort of get what you are saying…
It got me to thinking, no matter the ‘shape’ of the block, each block needs to occupy a 4x4x4 space. So I really don’t need to be casting against the visual image of the block, but rather an invisible ‘hit box’ .

So I tried that, and by making the hit box slightly larger than the block size 4.01 in all dimensions, this seems to work.

Thanks for your input.

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