Scripting Helpers is winding down operations and is now read-only. More info→
Log in to vote

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

Asked by 9 years ago

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 MIN,MAX,RAN,RAD,FLOOR,ROOF = math.min,math.max,math.random,math.rad,math.floor,math.ceil
    local pos = part.Position
    local size = part.Size
    local startpos =,pos.y-size.y/2,pos.z-size.z/2)
    local endpos =,pos.y+size.y/2,pos.z+size.z/2)
    local REG3 =,endpos.X),MIN(startpos.Y,endpos.Y),MIN(startpos.Z,endpos.Z)),,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

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

1 answer

Log in to vote
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
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.


Answer this question