This site requires JavaScript, please enable it in your browser!
Greenfoot back
Conmore
Conmore wrote ...

2012/12/7

How to make ball bouce off paddle at different angles?

Conmore Conmore

2012/12/7

#
I'm trying to make Breakout, and I'm trying to make the ball bounce off the paddle at different angles based on where it hits the paddle. Can anyone tell me if there's a method for this and how to use it?
danpost danpost

2012/12/7

#
You could take the difference in the x-coordinates of the ball and the paddle and use a ratio of that with half the sum of the length of the paddle and the diameter of the ball as a base to determine a change in the reflected angle. That is:
double factor=(ball.getX()-paddle.getX())/((ball.getImage().getWidth()+paddle.getImage().getWidth())/2);
The value for 'factor' will end up between negative one and positive one. You could simply use 'factor*n' as the amount of change in the angle, where 'n' is the maximum amount of change allowed. The angle of approach of the ball toward the paddle can be used to limit the value of 'n' so that the ball will always bounce in an upward direction. I have coded ball-on-block and ball-on-ball bouncing, but have not tried it with changing angles as you want here. I can get a perfect bounce with ball-on-ball bouncing; I can also get perfect ball-on-block bounce anywhere on the block (even the corners) as long as the block is not rotated (the block's rotation must be zero); but once the block is no longer at zero rotation, the bounce is so much harder to calculate. At any rate, the suggestion above should be the basis of what you need.
cxthleen cxthleen

2016/2/3

#
where do i enter this code? in the paddle actor or ball actor? thanks!
danpost danpost

2016/2/3

#
cxthleen wrote...
where do i enter this code? in the paddle actor or ball actor? thanks!
The line of code given above was only to show how to create a factor to use in altering the bounce back angle. It is not exactly written to be in one class or another. It would need to be slightly adjusted, depending on the class you actually put it in.
You need to login to post a reply.