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.
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
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
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.