So as I have a flat paddle I’ve added the following code to my paddle so that depending on where the ball hits the paddle it will bounce in that direction (e.g. if the ball hits the right side of the paddle it will bounce right)
The relevant function is here:
private void RouteBall(Collision2D collision)
{
Ball collidedBall = collision.gameObject.GetComponent<Ball>();
if(collidedBall.State == BallState.WAITING_FOR_LAUNCH)
{
return;
}
Vector2 velocity = Vector2.zero;
float xCollisionPoint = collision.GetContact(0).point.x;
float xPadCenter = transform.position.x;
float absDistance = Mathf.Clamp(Mathf.Abs(xPadCenter - xCollisionPoint), 0f, 1f);
velocity.y = maxForces.y;
if (xCollisionPoint > xPadCenter)
{
velocity.x = maxForces.x * absDistance;
}
else if (xCollisionPoint < xPadCenter)
{
velocity.x = -maxForces.x * absDistance;
}
collidedBall.SetVelocity(velocity);
}
With this in place, if I add autoplay functionality with the paddle following the ball’s x position, it will meet the ball at the exact middle of the paddle which will send the ball straight up into an endless loop. If I add a fixed offset to the paddle position then the ball will enter a loop at the corner of the playfield. If I try to randomize the offset then the paddle twitches. And if I try to instead change the offset sign when the paddle reaches the wall, it doesn’t work as the paddle can’t interact with the wall (I’ve even made a separate gameobject with a wider block collider than paddle and added it as a child of paddle to act as a wall sensor but it never registered a collision with the walls) so I’m stuck there.
I’ve also forgone the random velocity tweak for a loop detection where I store the previous collision and then check if the current collision is a wall or an unbreakable block and if the two collisions have a similar x or y position then I add a force to that axis to break the loop.
I did all that in order for the ball movement to be more predictable and more enjoyable.
However due to all these changes I’m now stuck with implementing autoplay. Does anyone have any suggestion as to how I can make the paddle not quite follow the ball’s x position exactly but still follow the ball and avoid linear loops?