1
\$\begingroup\$

I am making a Atari Breakout game with unitys 2d tools and I need to get the ball to bounce of colliders in the scene. If you havent played the game before how it works is if the ball hits the wall at 45 degrees it will bounce of the wall at the same angle (diagram bellow)

enter image description here

How can I get the ball to move at a continues speed and when it hits a collider to bounce back the way the image shows?

\$\endgroup\$
2
  • \$\begingroup\$ @Byte56 I don't think this is a duplicate because this one is about unity \$\endgroup\$
    – Qwertie
    Feb 12, 2014 at 20:52
  • \$\begingroup\$ The technique is the same. Applying the same technique to Unity is your job as a developer. \$\endgroup\$
    – House
    Feb 12, 2014 at 20:54

4 Answers 4

2
\$\begingroup\$

What you need to do is two things: One, the ball has to have a rigidbody2d attached (the walls don't) and then create a PhysicsMaterial2d and experiment with the two values (I think you want friction: 0, bounciness: 1).

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You say "you could either create..." then only list one option. \$\endgroup\$
    – House
    Feb 12, 2014 at 15:28
  • \$\begingroup\$ Ah, that was because I was going to list the option that OriginalDaemon posted, then decided against it. I've edited the answer accordingly. \$\endgroup\$ Feb 12, 2014 at 20:02
2
\$\begingroup\$

It depends if you want realistic physics or not. If realistic then like Garan said.

If not, and you want it to bounce exactly as it was and in the same speed:

Give the ball a 2D collider, and the wall a 2D collider. Make them both triggers. In OnTriggerEnter2D(Collider2D collider) inside the ball script, bounce the ball manually. Reverse the horizontal speed, and give it the same vertical speed (or the other way around depending on your orientation).

\$\endgroup\$
1
\$\begingroup\$

What you are looking to do here is reflect the velocity vector in the normal of the surface the ball has collided with. See here.

The equation is as follows;

Vnew = -2*(V dot N)*N + V

As pat mentioned you will need to make the wall and the ball a 2D collider and do this reflection in the OnTriggerEnter2D method. The normal of the collision will be defined as the direction from the ball center to the collision point.

Somethign like;

N = collider.contacts[0] - ballPosition.

\$\endgroup\$
1
\$\begingroup\$

Since all the surfaces are parallel/perpendicular, you just invert the x-direction when hitting a vertical surface (or y-direction when hitting a horizontal surface)

However, note that this is not the way bouncing off the paddle works in Breakout - the outgoing angle is determined by where on the paddle the ball hits, not what the incoming angle was.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .