How can you check if an entities bounding box is within a sphere?

Basically, I want to check if an entity is near another entity.

If I use ent:GetPos(), it checks for the origin, since the origin for the player is the bottom, I thought of doing something this to get the center of the entity I want to check.
[lua]
local dist = self.Entity:GetPos():DistToSqr(ent:LocalToWorld(ent:OBBCenter()) ) --Using Squared Distance cuz optimization.
–MsgN(dist)
if dist > 3136 then --3136 is 56^2
–Do stuff
end
[/lua]

I ran into another problem when I realized that this won’t work well with bigger entities, such as the 4x4 PHX metal prop.

So, my question is, how do I check if the Bounding Box of an entity is within a spherical distance of my entity?

if you’re just checking if it’s near another entity, does it really need to be so exact?

What do you mean? I just want to see if an entities bounding box is within the spherical distance of another entity

Not sure what the context is but you could use FindInSphere in a loop.

[lua]
for k, v in pairs( ents.FindInSphere( self.Entity:GetPos(), 3136 ) ) do
if v == ent then
– Do stuff
end
end
[/lua]

Context:
I’m trying to make the portals work “Better”.

Pesudo code:
[lua]
local nearents = ents.FindInSphere(self.Entity:GetPos(),largeradius)
for k,v in pairs(nearents) do – I actually have this written to check in reverse order, but in the sake of simple explaining… oh well
if !CustomIsValidFunction(v) then
table.remove(nearents,k)
end
end
if #nearents == 0 then self:NextRefresh(CurTime() + 0.5) return end
local dist = self.Entity:GetPos():DistToSqr(ent:LocalToWorld(ent:OBBCenter()) )
if dist > smallerradius then
–Teleport
end
[/lua]

You can check out http://wiki.garrysmod.com/page/PhysObj/GetMeshConvexes . I don’t know how meshes are handled, but I would think you could check the distance from each point of the mesh.

Dude, no.

Just have something that checks the distance of each bounding box corner (so 8 checks per entity, which is still a ton) to the center of the sphere.


if ent:NearestPoint( sphere_origin ):Distance( sphere_origin ) <= sphere_radius then
  --Inside sphere
end

Entity.NearestPoint

Maybe?

Whoop whoop I think we found our winner.

let me plug this in the code and see if it works

[editline]14th October 2013[/editline]

Works like a charm! Thank you!