0

# How do I use Region3 efficiently to see if there are any parts connecting with a part?

I'm trying to figure out an accurate way to determine if an Anchored part is touching any other part. Here is the function I have written so far.

function checkCollisions(part)
local pos = part.Position
local size = part.Size
local startpos = Vector3.new(pos.x-size.x/2,pos.y-size.y/2,pos.z-size.z/2)
local endpos = Vector3.new(pos.x+size.x/2,pos.y+size.y/2,pos.z+size.z/2)
local REG3 = Region3.new(Vector3.new(MIN(startpos.X,endpos.X),MIN(startpos.Y,endpos.Y),MIN(startpos.Z,endpos.Z)),Vector3.new(MAX(startpos.X,endpos.X),MAX(startpos.Y,endpos.Y),MAX(startpos.Z,endpos.Z)))
local partsinREG3 = game.Workspace:FindPartsInRegion3(REG3,nil,1)
if #partsinREG3 > 0 and partsinREG3[1].Transparency == 0 then
return partsinREG3[1]
elseif #partsinREG3 < 1 then
print(part.Name..' is not colliding with any other object.')
return false
end
end


It seems fine, but for some reason, it bugs out and sometimes says that their is a part in range when there isn't.

0
BlueTaslem 18071
9 years ago

You are assuming that the part is rotated with the default orientation.

If it's rotated by 90 degrees, you'll be a bit off. If it's rotated by anything else, that a Region3 will only be an approximation, so keep that in mind.

Basically, that just means we need to recalculate startpos and endpos correctly.

We can to :pointToWorldSpace to accomplish this:

    local startpos = part.CFrame:pointToWorldSpace( -size / 2 )
local endpos = part.CFrame:pointToWorldSpace( size / 2 )

-- (from what you had before,
-- You probably should have had pos - size / 2
-- instead of listing out the whole thing)


Again, if the parts are rotated arbitrarily, the above is only an approximation -- it isn't even the bounding box in particular, just an approximation of the bounding box.