How to reflect the ball at an angle?

Here’s the full code:

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?

You flip the sign of the velocity.

For 2D:

If your ball is moving with velocity <a,b> and you hit a left or right wall, then it becomes <-a,b>

Flip the other component for the top or bottom wall.

it doesn’t give an angle.

What does ‘at an angle’ mean to you?

A ball with velocity <1,1> hitting a wall and changing velocity to <-1,1> has a 90* angle in its path of travel.

Adding velocity due to a moving paddle is a different question

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.

doesn’t work. I’ve tried it.

It does work. Your ball hitting the wall at a 90* angle means it will bounce back at the same angle.

Like I said, making the ball move in a different direction because the paddle/bat is moving is a different thing.

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.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.