Why doesn't my code work?

The red block should fill between the walls using raycast. Something with my math is wrong im pretty certain…

local part = script.Parent

	
local origin = part.Position

local hitPositions = {}

local directions = {
	Vector3.new(-10,0,0); -- left
	Vector3.new(10,0,0); -- right
	Vector3.new(0,0,10); -- top
	Vector3.new(0,0,-10); -- bottom
}

for _,direction in ipairs(directions) do
	local result = workspace:Raycast(origin, direction*2)
	local hitPosition = (result and result.Position) or origin + direction*2
	table.insert(hitPositions,hitPosition)
	local t = Instance.new("Part",workspace)
	t.Position = hitPosition
	t.Anchored = true
	t.CanCollide = false
	t.CanQuery = false
	t.Size = Vector3.new(2,2,2)
	game.Debris:AddItem(t,.03)
end



local sizeX = hitPositions[2].X - hitPositions[1].X
local sizeZ = hitPositions[3].Z - hitPositions[4].Z

local pos = (hitPositions[1] + hitPositions[2] + hitPositions[3] + hitPositions[4])/4

part.Size = Vector3.new(sizeX,0,sizeZ)
part.Position = pos

I ended up figuring this out with



local part = script.Parent

local hitPositions = {}
local origin = part.Position

local directions = {
	Vector3.new(-10,0,0); -- bottom
	Vector3.new(10,0,0); -- top
	Vector3.new(0,0,10); -- right
	Vector3.new(0,0,-10); -- left
}

for i,direction in ipairs(directions) do
	local result = workspace:Raycast(origin, direction)
	local hitPosition = (result and result.Position) or origin + direction
	if i == 1 or i == 2 then
		table.insert(hitPositions,hitPosition.X)
	else
		table.insert(hitPositions,hitPosition.Z)
	end
end

local sizeX = (hitPositions[2] - hitPositions[1])
local sizeZ = (hitPositions[3] - hitPositions[4])

local posX = (hitPositions[2] + hitPositions[1])/2
local posZ = (hitPositions[3] + hitPositions[4])/2


part.Size = Vector3.new(sizeX,0,sizeZ)
part.Position = Vector3.new(posX,0,posZ)
	

2 Likes