Home > database >  How to make ball bounce
How to make ball bounce

Time:05-21

I have a game where u bounce a ball with platform and u have to destroy all boxes but my code for bounceing ball its not working like I want.

It works like a real ball bounce but I want the ball to bounce like a ball in pong where ball don't fall down until it touches wall or platfotm but my ball goes in real life curve.

What I thing with curve is like when u kick a ball in the air and goes in curve but I want it to go unlimitly in flat line to the wall andbounce in a random direction.

Someone have any code ideas?

CodePudding user response:

Pong/breakout style physics is simpler than you might think. The balls have no gravity applied to them, so all you need to do is apply a constant velocity to the ball. When it collides with an object, you would flip the velocity on the axis it collided.

For example: ball is travelling up at 60px/sec, and horizontally at 120px/sec, at 60fps. You add (60/60)=1 pixels vertically every frame, and (120/60)=2 horizontally. It hits a wall, so you flip the horizontal velocity to -120px/sec. Now it's still going up, but in the opposite direction horizontally. If it hits a ceiling, same thing but flip the vertical velocity component.

If you'd rather it go in a random direction:

  • calculate the magnitude of the ball's velocity sqrt(vx^2 vy^2)
  • find the angle the wall is facing
  • pick a random angle within 180 degrees of that angle
  • use trigonometry to get the x/y components of that angle, and multiply by the magnitude.

Don't subtract/add a constant value to the velocity every frame, because then you'd be applying gravity, which isn't what you're looking for.

CodePudding user response:

Make a physics material like the one below and place it on any surface that bounces. It is enough for your ball to have a Rigidbody with drag 0.

enter image description here


Also uncheck gravity to get the following result:

enter image description here

  • Related