Ball disappers from screen inspite of giving bounceoff(edges)

Hi!

Regarding the bounceOff behavior: bounceOff is meant to recreate a strong repelling behavior, like a basketball bouncing off the floor. It makes the most sense to think of this with moving object bouncing off a stationary object, but the behavior gets complicated when you have multiple moving objects. This link shows some different examples of how bounceOff behaves (the animation at the bottom with the note and the guitar). Behind the scenes, the general behavior is: if you have sprite1.bounceOff(sprite2), then sprite1 will keep it’s same velocity and add twice sprite2's velocity to it. You can see this behavior in the link above. If you wanted the velocities to all stay the same but just change direction, try using bounce instead of bounceOff.

Regarding disappearing objects: this has to do with how velocity and collisions work behind-the-scenes. velocity is really just the counter pattern - whenever you put sprite1.velocityX = 10, GameLab secretly translates this into sprite1.x = sprite1.x + 10 at the top of the game loop you can see that in this video here.

Similarly, when we type ball1.bounceOff(edges), GameLab secretly translates that into an if-statement that looks something like

if (ball1.isTouching(edges)) {
  //bounce off
}

So, the heart of the problem is: what happens when the counter pattern updates so much that the ball moves past the edge without ever touching it?

In this example, the velocity is so high that the counter-pattern makes the ball goes completely beyond the edge without ever touching it, which means the if-statement with isTouching never becomes true. Fun fact: this is also how glitches in modern video games happen too where your character can get “stuck” in the environment or access secret areas they’re not supposed to. Here’s an example from an old video game - you can see the character try and activate the glitch by going ‘so fast’ that the game doesn’t detect that it hit the water.

There are several ways to fix this:
Option 1: Make the ball bigger so it has a greater chance of impacting the wall:

Option 2: Don’t use the default edges in GameLab and instead made your own with a wider width so they’re more likely to detect collisions. You can still place these just outside the visible area so players won’t see them.

Option 3: Add an if-statement to your code to check the velocity values for your objects, and make sure they never go above a certain amount. This makes sure you never reach a speed that’s “too fast” and can glitch your game.

This was fun - thanks for asking this question.

Dan - Code Curriculum Writer

1 Like