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);
}
}
}