Hi all,
I’m building a 2D brick breaker game and I’m using PhysicsMaterial2D in the ball. Friction is set to 0 and bounciness is set to 1. The ball has a circle collider and a dynamic rigidbody with continuous collision detection.
The bricks are static rigidbodies with a box collider. The behavior that I want for the collision is to preserve the ball’s rigidbody velocity and invert its X or Y depending if the ball collided with sides or top/bottom of the brick.
The issue is that I’m getting weird angles when the ball hits the edge of the bricks or between two bricks. Here’s a video: PhysicsMaterial2D - Brick Breaker - Ball Bounciness Issue.mp4 - Google Drive
Here’s the code I’m using to debug this:
void Update()
{
GetVelocity();
if (brickCollisions > 0)
brickCollisions = 0;
}
void GetVelocity()
{
lastFrameVelocity = rb.velocity;
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Common Brick")
{
brickCollisions++;
Debug.Log("Brick collisions: " + brickCollisions + " / " + "Velocity before collision: " + lastFrameVelocity + " / " + "Velocity after collision: " + rb.velocity);
}
}
And here’s an example (not the same as video) of what’s happening when the ball hits edges:
Brick collisions: 1 / Velocity before collision: (2.0, 2.0) / Velocity after collision: (2.0, -2.0)
Brick collisions: 1 / Velocity before collision: (2.0, -2.0) / Velocity after collision: (2.0, 2.0)
Brick collisions: 1 / Velocity before collision: (2.0, 2.0) / Velocity after collision: (0.2, -2.8)
Brick collisions: 1 / Velocity before collision: (0.2, -2.8) / Velocity after collision: (-0.9, 2.7)
Brick collisions: 1 / Velocity before collision: (-0.9, 2.7) / Velocity after collision: (-0.9, -2.7)
And this is when the ball hits between two bricks (which can very well be the same issue as above):
Brick collisions: 1 / Velocity before collision: (2.0, 2.0) / Velocity after collision: (2.0, -2.0)
Brick collisions: 1 / Velocity before collision: (2.0, -2.0) / Velocity after collision: (2.0, 2.0)
Brick collisions: 1 / Velocity before collision: (2.0, 2.0) / Velocity after collision: (2.0, -2.0)
Brick collisions: 1 / Velocity before collision: (2.0, -2.0) / Velocity after collision: (-0.9, 2.7)
Brick collisions: 2 / Velocity before collision: (2.0, -2.0) / Velocity after collision: (-0.9, 2.7)