Breakout Clone: How to Change Direction of Ball

I’m making a breakout clone for a tutorial I’m writing, and I don’t know how to make the ball change direction based on where it hits on the paddle. Like for example, I want it to change angle a bit to the left if it hits the center-left of the paddle, or way to the left if it his the left end of the paddle.

How would one achieve this? For the record, I move the ball by setting the rb’s velocity in start, so I would assume I just have to change the rotation.

Thanks in advance.

Setting .velocity on a Rigidbody is in world coordinates so the rotation of the RB doesn’t matter.

The way Breakout worked was to compare the ball’s lateral position to the lateral position of the center of the paddle and based on how far left or right on the paddle you hit, set the reflect velocity accordingly.

You might want to always ensure the ball has a certain amount of lateral velocity (as a fraction of vertical velocity) to prevent a good player from capturing the ball perfectly in the center of the paddle and making the game very easy for himself by bouncing it straight up every time and only moving it over slightly.

1 Like

Oh, I think I got it. So maybe something like…

void OnCollisionEnter(collider col){
float x = Random.Range(-.5f,.5f);
Vector2 velocity = new Vector2((transform.position.x - col.transform.position.x) + x, transform.position.y - col.transform.position.y);
rb.velocity = velocity.normalized * speed;
}

I typed this on the fly, not in visual studio so don’t mind the formatting issues lol

Ah, I don’t know why I posted that instead of checking it out myself haha. I just tested it, and it works amazingly! Thanks for the advice. I just lowered the x float to -.05f and .05f

1 Like

You can also use a circle collider on the paddle instead of a box collider, and stretch it out horizontally so it fits the box (more or less). The roundedness of the ellipse will change the bounce direction just as it would in real life (in all those breakout games we play in real life haha).

That said, visually it might look a bit strange though, as it will “dip into” the block a bit. No reason you couldn’t have a rounded paddle though.