When a ball collides with bat or walls, I want the ball to be reflected with an angle, how do I do it?
I suspect there’s lots of physics to it. So, should I stop this project here? I’d have to probably build a part of game engine…Can anyone help here?
A simple idea is starting the ball at an angle, so it starts with an X and Y direction. If I’m reading your code correctly the ball direction currently starts by falling straight down with { x: 0 , y: -1}. Starting with a direction of {x: 1, y: -1} would start the ball falling down and to the right (or x: -1 for left movement).
With the ball already moving diagonally it should maintain that 90degree angle when it hits a wall or the bat.
Looking at the moveBall() function I see some things that are odd.
First, the ‘translate’ seems to favor the y axis by 20 px. That would explain why the ball doesn’t appear to move diagonally when x=1.
Second, when the ball bounces off the top, bottom or the bat it looks like it is hard coded to straight up and down <x=0, y=-1>. When I tested it, after the ball bounced off the top of the box it still went straight up and down.
Lastly, in the moveBall() function I didn’t see any parameters for bouncing off the side walls. I don’t know if that was intentional but I figured I’d mention it.