 # Improved boring play protection

So I noticed a problem with the code in this section. You are always adding positive values when the velocities may in fact be negative. Meaning if your ball has a Y velocity of -2f and you add a value of 2f, the Y velocity is now 0, thus you are actually slowing the ball down.

I modified the code a little bit and came up with my own solution (note that this is also coded in Unity 5):

``````    if (Mathf.Abs(GetComponent<Rigidbody2D>().velocity.x) < 1.5f)
{
// Copy the current values into a new Vector2 to make it possible to modify individual values directly
Vector2 tweak = GetComponent<Rigidbody2D>().velocity;
// Randomly generate a float between 1-2, then multiply it by 1 if the current velocity is positive or -1 if the current velocity is negative, then add it.
tweak.x += (Random.Range(1.0f, 2.0f) * Mathf.Sign(tweak.x));
// Set the ball's velocity to the new value
GetComponent<Rigidbody2D>().velocity = tweak;
}

if (Mathf.Abs(GetComponent<Rigidbody2D>().velocity.y) < 1.5f)
{
Vector2 tweak = GetComponent<Rigidbody2D>().velocity;
tweak.y += (Random.Range(1.0f, 2.0f) * Mathf.Sign(tweak.y));
GetComponent<Rigidbody2D>().velocity = tweak;
}

if (Mathf.Abs(GetComponent<Rigidbody2D>().velocity.x) + Mathf.Abs(GetComponent<Rigidbody2D>().velocity.y) <= 5.0f)
{
Vector2 tweak = GetComponent<Rigidbody2D>().velocity;
tweak.x *= Random.Range(1.3f, 1.5f);
tweak.y *= Random.Range(1.3f, 1.5f);
GetComponent<Rigidbody2D>().velocity = tweak;
}
``````

Essentially what this does is:

1. Check to see if the absolute value of the X velocity of the ball is < 1.5. This gives us a range of velocity from -1.5 to 1.5. If the velocity of the ball is in this range, then we find a tweak value between 1-2, and add it to the velocity if it’s positive or subtract it from the velocity if it’s negative. This basically means you’re always moving the velocity of the ball farther away from 0.

2. Do the same for the Y velocity of the ball.

3. If the total combined absolute value of the velocity is still less than 5 then we multiply both x and y values by a range from 1.3-1.5. These are arbitrary values I found to work well. This keeps the ball moving at a good pace and prevents gameplay loops where the ball is staying very vertical or horizontal.

It’s not perfect, but it avoids the problem I mentioned at the start and I’m pretty happy with it after some play testing.

5 Likes

Nice work. Thanks for sharing this tip.

1 Like