First I declare three variables, that will be maaximum and minimum velocity of the ball. They will be measured with an amplitude respecting the initial velocity.
[SerializeField] float amplitude = 2f;
float minVelocity;
float maxVelocity;
Then I initialize these variables just after ball is launched (in Update() method).
if(!hasStarted)
{
LockBallToPaddle();
LaunchOnMouseClick();
minVelocity = myRigidbody2D.velocity.y - amplitude;
maxVelocity = myRigidbody2D.velocity.y + amplitude;
}
Finally I create this methods for having a consistent velocity on the ball.
private void OnCollisionExit2D(Collision2D collision)
{
CorrectXVelocity();
CorrectYVelocity();
}
private void OnCollisionExit2D(Collision2D collision)
{
CorrectXVelocity();
CorrectYVelocity();
}
private void CorrectXVelocity()
{
int xSign = Math.Sign(myRigidbody2D.velocity.x);
float absXVelocity = Math.Abs(myRigidbody2D.velocity.x);
if (absXVelocity < minVelocity)
{
myRigidbody2D.velocity += new Vector2((minVelocity - absXVelocity) * xSign, 0f);
}
if (absXVelocity > maxVelocity)
{
myRigidbody2D.velocity -= new Vector2((absXVelocity - maxVelocity) * xSign, 0f);
}
}
private void CorrectYVelocity()
{
int ySign = Math.Sign(myRigidbody2D.velocity.y);
float absYVelocity = Math.Abs(myRigidbody2D.velocity.y);
if (absYVelocity < minVelocity)
{
myRigidbody2D.velocity += new Vector2(0f, (minVelocity - absYVelocity) * ySign);
}
if (absYVelocity > maxVelocity)
{
myRigidbody2D.velocity -= new Vector2(0f, (absYVelocity - maxVelocity) * ySign);
}
}