[SOLVED] How to simulate collision *response*? (codepen included)

Hello, I’ve been scratching my head for weeks trying to figure this out.
I’ve created this codepen based on the Three.js OBB example: https://codepen.io/accrobat/pen/rNOKNyg?editors=0010

I have:

  • random green elements, fixed.
  • blue element that moves with the mouse
  • working collision detection based on OBBs between the blue and green elements
  • ideally, it should work even if the blue element itself rotates

How do I code the response to the collision? i.e. the blue element should not penetrate the green elements and should be blocked by them. The green elements are fixed so there is no need for a reaction from them or any complex physics.

Anyone can help with an updated codepen?

Thanks!

I never used your approach to do it, so I don’t know :confused:

But I can show you how I would do it using physics (@enable3d/ammo-physics).

// initialize physics without gravity
const physics = new AmmoPhysics({ gravity: { x:0, y:0, z:0 } })

// add the static green boxes
physics.add.existing( greenBoxMesh , { mass:0, collisionFlags:1 })

// add the dynamic blue box
// (it can't be kinematic since kinematic and static objects do not collide)
physics.add.existing( blueBoxMesh , { collisionFlags:0 })

// now add velocity to the blue box depending on your mouse inputs
blueBoxMesh.body.setVelocity( X, Y, Z )

Hope this helps :slight_smile:

Thanks a lot, this is very helpful :slight_smile:

But I’m trying to avoid adding a physics engine overhead for this particular application.

I will try figuring out how OBB.clampPoint works.

For a simple solution you could iteratively move the blue box towards the cursor (target location) at a fixed step multiple times per frame and if it intersects a green box then you could stop it. If it intersects you could also have an adjustment phase where you try to more precisely find where the first intersection point should be. Note that this wouldn’t handle rotation, though.

1 Like

Thanks for the suggestion. I think I figured it out.

The trick was to check for intersection using OBB.clampPoint and don’t update the moving part position when the distance between the hand and the clampPoint is smaller than the distance when it first hits. It does “tunnel” through if you keep moving, but that’s fine for my needs.

Leaving a new codepen here if someone else finds it useful: https://codepen.io/accrobat/pen/ExVeymO