Search code examples
c#unity-game-enginegame-physics

Why doesn't the object bounce correctly at lower speeds in Unity 2D?


P.S. I have already seen this question asked here, but this applies to Unity 3D, whereas I am working in Unity 2D.

My main issue is that a ball in my Unity 2D game doesn't bounce correctly when the speed is set to a lower value but works fine at faster velocities. Note that I have already tried to change the bounce threshold in Project Settings, but it does not do anything to solve my issue. I have applied a Rigidbody2D component, BoxCollider2D, and a Physics Material 2D that is supposed to make the ball bouncy.

Here are some of my current settings (if that helps):

Rigidbody2D Settings:

  • Body Type: Dynamic
  • Material: Bouncy (name of my physics material)
  • Simulated: True
  • Use Auto Mass: False
  • Mass: 1
  • Linear Drag: 0
  • Angular Drag: 0
  • Gravity Scale: 0
  • Collision Detection: Discrete
  • Sleeping Mode: Start Awake
  • Interpolate: None

Physics Material 2D Settings:

  • Friction: 0
  • Bounciness: 1

Here is some of the initialization code that runs when the game loads to start the movement of the ball:

float x = Random.value < 0.5f ? -0.75f : 0.75f;
float y = Random.value < 0.5f ? Random.Range(-0.75f, -0.5f) : Random.Range(0.5f, 0.75f);

Vector2 direction = new Vector2(x, y);
rb.AddForce(direction * speed);

Note: This code is inside a custom class (inherits MonoBehavior) I made for the ball object to manage the physics actions.

For additional information, refer to this video to see how the game responds.

The slower speed for the ball is necessary for my game, and I would really appreciate it if I could get some help on this issue.


Solution

  • The Unity physics system is non-deterministic and does not make promises of conservation of energy, or other features. if you want to fine-tune your physics system to such a degree you may want to consider using other means of controlling the ball's velocity.

    But if you do want to continue using the built-in physics engine anyway, you could consider using faster velocities and lowering the timescale to compensate.

    For example:

    float x = Random.value < 0.5f ? -3f : 3f; 
    float y = Random.value < 0.5f ? Random.Range(-3f, -2f) : Random.Range(2f, 3f); 
    

    and somewhere in Start or Awake

    Time.timeScale = 0.25f;
    

    and you'll probably want to increase the velocities of your paddles as well to compensate for the timescale change.


    Another option is using faster velocities and increasing the size of everything and making the camera view larger to make everything appear the same size. Requires fewer code changes but potentially many more scene/component changes.