#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

# 3D Collision Detection

Posts: 104

Is there anyway to accurately detect if a rigidbody has collided with another rigidbody?? If so, what would be the smartest thing to code?

• Mod
Posts: 9,441

I don’t think there’s a collision function like in 2D, at least I haven’t seen one. But you can calculate the distance between 2 bodies, subtract their size to see if they’re colliding.

• Mod
edited September 5 Posts: 9,441

Here’s one way of doing it.

``````viewer.mode=STANDARD

function setup()
assert(OrbitViewer, "Please include Cameras (not Camera) as a dependency")
size=1
fill(255)
scene = craft.scene()
skyMaterial=scene.sky.material
skyMaterial.sky=color(0, 62, 255, 255)
skyMaterial.horizon=color(99, 255, 0, 255)
scene.sun.rotation=quat.eulerAngles(20,45,-30)
createObjects()
end

function createObjects()
sphere1=scene:entity()
s1.restitution=1
sphere1.position=vec3(0,5,0)
sphere1.model = craft.model.icosphere(size,2)
sphere1.material = craft.material(asset.builtin.Materials.Specular)
sphere1.material.diffuse=color(255,0,0)

sphere2=scene:entity()
s2.restitution=1
sphere2.position=vec3(0,-5,0)
sphere2.model = craft.model.icosphere(size,2)
sphere2.material = craft.material(asset.builtin.Materials.Specular)
sphere2.material.diffuse=color(0,0,255)
end

function draw()
update(DeltaTime)
scene:draw()
calc()
end

function update(dt)
scene:update(dt)
end

function calc()
x=math.abs(sphere1.position.x-sphere2.position.x)
y=math.abs(sphere1.position.y-sphere2.position.y)
z=math.abs(sphere1.position.z-sphere2.position.z)
if x<2 and y<2 and z<2 then
print("hit")
end
end
``````