I have a simple basketball shooting game built in Phaser 3. It has a ball, a rim with a point on each side where the ball can bounce off of, and a zone underneath the rim that I use to track for scoring if the ball passes through it. The game is 2D.
I come across specific situations where if I launch the ball with just enough velocity so that it basically collides with the rim at the very peak of its launch and hardly bounces since the velocity is so low at that point, in a sense just sitting on the rim for a bit. It will very shortly after disappear completely. Turning debug mode on and checking the velocity, position, and angle, they all show up as NaN.
Here’s the relevant code for the collision detection:
event.pairs.forEach((pair) => {
const { bodyA, bodyB } = pair;
const ballBody = this.throwable.body;
if (
(bodyA.label === 'leftGoalBound' ||
bodyA.label === 'rightGoalBound') &&
bodyB === ballBody
) {
console.log('hit a rim');
const ballBottom =
ballBody.position.y + ballBody.circleRadius;
console.log('ball bottom');
if (
ballBody.velocity.y > 0 &&
ballBottom <= this.leftGoalBound.position.y - 10
) {
debugger;
console.log('pair is active');
pair.isActive = true;
} else {
console.log('pair is inactive');
pair.isActive = false;
}
}
if (bodyA.label === 'goalSensor' && bodyB === ballBody) {
console.log('hit goal sensor');
const ballBottom =
ballBody.position.y + ballBody.circleRadius;
const ballX = ballBody.position.x;
const leftRimX = this.leftGoalBound.position.x;
const rightRimX = this.rightGoalBound.position.x;
if (
ballBody.velocity.y > 0 &&
ballBottom <= this.goalSensor.position.y &&
ballX > leftRimX &&
ballX < rightRimX &&
!this.hasScored
) {
this.handleHoopScore();
}
}
const didBallHitGround =
bodyA.label === 'ground' && bodyB === ballBody;
if (didBallHitGround) {
this.resetBall(this.throwable);
}
});
});
I’ve tried setting the rim and ball to have more bounce, but this starts to ruin gameplay as they get too touchy. I haven’t really found any good documentation on what can lead to NaN values during a collision – I’ve been warned of the typical ‘divide by 0’, but I don’t do any such arithmetic here. I’m rather lost as to what is causing this.
Jimmy Blundell is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.