Bounceoff Question

Could someone tell me what I am missing in my student’s code? Bounceoff here will not go diagonally.

This is a great start! It looks to me that the function ballphysics needs to show what to do with the X & Y velocity most likely with a random number. I’ve included my own remix of it. I hope it helps!

Hmm. Thanks for the response. Maybe I am misunderstanding the collision functions. I didn’t think you should use the collision functions in a conditional. I thought that you just put sprite.bouceOff (sprite2), and it would handle the collision. That is what the example in the documentation seems to show. The apple in the example will bounce off at an angle if on the edge of the paddle. I did a console.log on the velocityY for the ball, and it never changes when bouncing off of the players. Otherwise, I would have to check whether I am at the top or the bottom of the player paddle to know what range of randomNumbers would be appropriate.


If the initial velocity is only either X or Y, and it bounces off a wall or a paddle, it will bounce at 180 degrees from the direction it was traveling. In your case, it will bounce back and forth from left to right on the screen.

If you don’t give it at least a slight Y velocity, there is nothing that can change its direction other than a direct reflection.

Now, perhaps that’s overly simplistic … you could possibly code some trigonometric functions dealing with the part of the paddle it hits, etc. but a simple BounceOff won’t pay attention to the size or speed of the paddle. If it hits, it will reflect 180 degrees.

As @edavis suggests, if you start it with even a slight random velocityY, it will start at a slight angle and then further bounces will most likely create the effect you are after. I would probably make it a random VelocityY (even a very small random range), but you could keep the same velocityX as you have now.

You could do it either inside or outside of conditionals, but it may be cleaner without conditionals.

Let us know if this still isn’t quite working as you would like it to.


Thanks for the explanation. That is not quite what I thought it did, but I guess that makes sense. I guess I was expecting a bit too much behind the scenes.