So I gave the “stop the ball from going super slow” challenge a go and would like to share the result. Took me more time then I thought but it works pretty good for me. The ball has a constant velocity now with random tweaking the direction.
In ball.cs:
private void OnCollisionEnter2D(Collision2D collision)
{
if(hasStarted)
{
AudioClip clip = ballSounds[Random.Range(0, ballSounds.Length)];
myAudioSource.PlayOneShot(clip);
TweakVelocity();
}
}
private void TweakVelocity()
{
var totalPush = xPush + yPush;
var xIsNegative = false;
var yIsNegative = false;
// Get the current velocity
Vector2 myVelocity = myRigidbody2D.velocity;
Debug.Log($"Velo CURRENT : {myVelocity} = {Mathf.Abs(myVelocity.x) + Mathf.Abs(myVelocity.y)}");
// Change negative velocity to positive
if(myVelocity.x < 0)
{
xIsNegative = true;
myVelocity.x *= -1;
}
if(myVelocity.y < 0)
{
yIsNegative = true;
myVelocity.y *= -1;
}
// Tweak velocity using a Random number from range
Vector2 velocityTweak = new Vector2(Random.Range(0f, randomFactor),
Random.Range(0f, randomFactor));
myVelocity += velocityTweak;
Debug.Log($"Velo TWEAK : {velocityTweak}");
// Adjust velocity so it stays the same as the initial push
var velocityAdjustment = totalPush / (myVelocity.x + myVelocity.y);
myVelocity.x *= velocityAdjustment;
myVelocity.y *= velocityAdjustment;
Debug.Log($"Velo ADJUSTMENT : {velocityAdjustment}");
// Change back velocity that was negative
if(xIsNegative)
{
myVelocity.x *= -1;
}
if(yIsNegative)
{
myVelocity.y *= -1;
}
Debug.Log($"Velo NEW : {myVelocity} = {Mathf.Abs(myVelocity.x) + Mathf.Abs(myVelocity.y)}");
// Set the new velocity
myRigidbody2D.velocity = myVelocity;
Debug.Log("-------------------------------");
}