Skip to content
Advertisement

THREE.js collision detection and stop/move again

I have a rounded ground and there is a ball on it. trying to move the ball inside the ground with using smartphone orientation. no problem with that part. the ball is moving and make the ball stop at the edge by using three.js intersectsSphere. but couldn’t manage the move the ball again if the orientation points opposite direction. here is the working sample.

https://codesandbox.io/s/jovial-mirzakhani-f50p2l?file=/src/App.vue

sample code below;

JavaScript

Advertisement

Answer

Think about the very moment when the ball goes out of intersection, which is the moment when ground_bounding.intersectsSphere(ball_bounding) returns true for the last time, what happens exactly? Let’s take some time to ponder about it:

  1. ground_bounding.intersectsSphere(ball_bounding) returns true
  2. so you feel comfortable to move the ball ball.position.x += x
  3. next round animate(), ground_bounding.intersectsSphere(ball_bounding) returns false
  4. at this point, the ball is already moved (in the previous round) to a position where ground_bounding.intersectsSphere(ball_bounding) always returns false, we’re stuck in the state forever.

Mistake is made at step 2, the ball SHOULDN’T be moved even though step 1 says true. Because if moved, next round it will definitely say false, and got stuck there forever.

Solution is to make a dummy clone of ball_bounding, then move the dummy first, and do intersection test against the dummy. If dummy is still within intersection after moved, that means it’s also safe to move the ball.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement