Skip to content

Instantly share code, notes, and snippets.

@philronan
Last active December 13, 2019 00:20
Show Gist options
  • Save philronan/6fdf6a4151a3be5e06acb07f5dc34ec2 to your computer and use it in GitHub Desktop.
Save philronan/6fdf6a4151a3be5e06acb07f5dc34ec2 to your computer and use it in GitHub Desktop.
Arkanoid style games get rather boring in Unity 2D physics if the ball ends up stuck in a horizontal or vertical bounce loop. Here's a quick fix:
[Range(7.0f,15.0f)] [SerializeField] float pushSpeed = 12.0f;
[Range(0.2f, 0.9f)] [SerializeField] float bounceFudge = 0.4f;
private void OnCollisionExit2D(Collision2D collision)
{
// Prevent ball from following paths that are too close to horizontal
// or vertical (to prevent boring loops)
// Get the ball's velocity (after a bounce)
Vector2 ballVector = myRigidBody2D.velocity;
// Calculate the angle (in radians)
float ballAngle = Mathf.Atan2(ballVector.y, ballVector.x);
if (ballAngle >= 0.0f && ballAngle < bounceFudge) {
ballAngle = bounceFudge;
}
else if (ballAngle <= Mathf.PI * 0.5f && ballAngle > Mathf.PI * 0.5f - bounceFudge) {
ballAngle = Mathf.PI * 0.5f - bounceFudge;
}
else if (ballAngle > Mathf.PI * 0.5f && ballAngle < Mathf.PI * 0.5f + bounceFudge) {
ballAngle = Mathf.PI * 0.5f + bounceFudge;
}
else if (ballAngle <= Mathf.PI && ballAngle > Mathf.PI - bounceFudge) {
ballAngle = Mathf.PI - bounceFudge;
}
else if (ballAngle < bounceFudge - Mathf.PI) {
ballAngle = bounceFudge - Mathf.PI;
}
else if (ballAngle <= -Mathf.PI * 0.5f && ballAngle > -bounceFudge - Mathf.PI * 0.5f) {
ballAngle = -bounceFudge - Mathf.PI * 0.5f;
}
else if (ballAngle > -Mathf.PI * 0.5f && ballAngle < bounceFudge - Mathf.PI * 0.5f) {
ballAngle = bounceFudge - Mathf.PI * 0.5f;
}
else if (ballAngle < 0.0f && ballAngle > -bounceFudge) {
ballAngle = -bounceFudge;
}
// NOTE: Also constrain the ball's velocity to its initial value
// to avoid unexpected changes of speed
ballVector.x = Mathf.Cos(ballAngle) * pushSpeed;
ballVector.y = Mathf.Sin(ballAngle) * pushSpeed;
myRigidBody2D.velocity = ballVector;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment