Search code examples
c#unity-game-enginephysicsbounce

Bouncing all gets magnitude and velocity 0 after a while and stops


Im trying to simply get a ball to bounce with constant speed and without any infinite bounces. To avoid infinite bouncing I have added some drifting on each bounce in the collision event like this:

private void OnCollisionEnter2D(Collision2D collision)
{
    Vector2 veclocityTweak = new Vector2(Random.Range(0f, 0.2f), Random.Range(0f, 0.2f));
    rigigidBody2D.velocity += veclocityTweak;
}

I have also rotated the colliders (the ball is bouncing within this box) enter image description here

This works ok. not perfect. But my real problem is that the ball suddenly stops and the rigidBody2D.velocity sets to (0.0, 0.0) as well as the magnitude.

I tried to prevent this by this function running in the update function checking the velocity. The idea is that it should prevent the ball to go to 0 in velocity but still that happens after a while:

private void checkVelocity()
{
     Vector2 vel = rigigidBody2D.velocity;

     float minSpeed = 0.8f;
     if (vel.magnitude < minSpeed)
     {
         float multipl = Random.Range(-1.0f, 1.0f);
         rigigidBody2D.velocity = vel.normalized * multipl;
     }
}

Here is my settings in the Project Settings: enter image description here

And I have set the material for the ball to: enter image description here

How can I prevent the ball from stopping?


Solution

  • I would recomend doing this:

    float minVelocity = 10;
    float maxTurn = 10;
    
    void OnCollisionEnter2D (Collision2D collision)
    {
        Quaternion randomRotation = Quaternion.Euler(0, 0, Random.Range(-maxTurn, maxTurn));
        rb.velocity = randomRotation * (rb.velocity.normalized * minVelocity);
    }
    

    This code will set the velocity of the ball to its previous velocity, but with a magnitude of minVelocity. It will also rotate that vector a random amount of degrees to make it bounce in different directions.