Finetuning the AI racket movement in Pong

For the simple Pong racket CPU AI I’m using below script. It works but there is still a noticeable staggering when the CPU paddle is moving long distance. When the ball is travelling from one corner it doesn’t track it exactly at a constant rate but it will go a certain distance, slow down and then repeat. To go from the bottom to the top it will repeat this pattern 3/4 times. Any ideas on what settings I can change to make it smooth?

Also, there is a small amount of stuttering when the ball is approaching straight on.

using UnityEngine;

public class Racket_CPU : Racket
{
    public Rigidbody2D ball;
    public float lerpSpeed = 1f;

    private void FixedUpdate()
    {
        if (ball.transform.position.y > transform.position.y)
        {
            if (rb.velocity.y < 0) rb.velocity = Vector2.zero;
            rb.velocity = Vector2.Lerp(rb.velocity, Vector2.up * speed, lerpSpeed * Time.deltaTime);
        }
        else if (ball.transform.position.y < transform.position.y)
        {
            if (rb.velocity.y > 0) rb.velocity = Vector2.zero;
            rb.velocity = Vector2.Lerp(rb.velocity, Vector2.down * speed, lerpSpeed * Time.deltaTime);
        }
        else
        {
            rb.velocity = Vector2.Lerp(rb.velocity, Vector2.zero * speed, lerpSpeed * Time.deltaTime);
        }
    }
}

Lerp isn’t really appropriate. Why not use Vector2.MoveTowards() instead?

Then it’s a simple case of knowing where to move (eg, the Y position of the ball) and moving towards it.

No if/else or any noise like that. It would just be this pattern:

Smoothing movement between any two particular values:

You have currentQuantity and desiredQuantity.

  • only set desiredQuantity
  • the code always moves currentQuantity towards desiredQuantity
  • read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

The code: SmoothMovement.cs · GitHub

I continue to have issues with this, I’ve simplified the CPU code, it now uses Mathf.MoveTowards (as I only need to move on one axis). It works but there are issues that I can see.

  1. Racket is now ignoring the collision with bottom and top walls (Collision detection = Continuous)

  2. There is some weird transformations on width and height of the racket.

using UnityEngine;

public class Racket_CPU : Racket
{
    [SerializeField] GameObject ball;
    private float y;
    private float dist;

    private void FixedUpdate()
    {
        {
            dist = Mathf.Abs((ball.transform.position - transform.position).y);
            if (dist > 0.0005)
            {
                y = Mathf.MoveTowards(y, ball.transform.position.y, speed * Time.deltaTime);
                transform.position = new Vector2(transform.position.x, y);
            }
        }
    }
}

8225895--1074519--Unity_0cW1GIlQOK.gif

Rather than trying to play 21 questions between the state of your code with the four (4) deficiencies you list above, why don’t you go do three or four pong tutorials off Youtube, and identify in each case the mechanism that corrects the deficiencies you list?

Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

How to do tutorials properly, two (2) simple steps to success:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That’s how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

Fortunately this is the easiest part to get right: Be a robot. Don’t make any mistakes.
BE PERFECT IN EVERYTHING YOU DO HERE!!

If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there’s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

I appreciate your comment, I really do. However it’s not relevant. I’m not trying to learn how to make pong, I’m trying to finetune the AI of the CPU racket, it happens to be that it’s for pong and I have specific questions. The biggest one being the collision with the top and bottom walls for the CPU racket.

For the collision this is what I’ve checked:

Rackets
Both rackets have RigidBody2D applied, Collision Detection is set to Continuous and the size of the BoxCollider2D is correct. Body Type = Dynamic

Walls
Both have BoxCollider 2D applied, correct size (even larger than necessary)

Layer Collision Matrix
AFAIK set up correctly

Collisions
The collisions are registered correctly, just sometimes they don’t work.

If there is more things I need to check then I’m open to suggestions.