- Home /
How to make a Pong AI
I am making a simple Pong game. I have been trying to make the other paddle controlled by AI and I am running to some problems. My current solution just makes the paddle flicker and not move at all. This is what my code looks like:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RedPaddle : MonoBehaviour {
private Ball ball;
[SerializeField] float movementSpeed = 0.1f;
void Start ()
{
ball = FindObjectOfType<Ball>();
}
void Update ()
{
Vector3 ballPosition = ball.transform.position;
Vector3 paddlePosition = this.transform.position;
if(paddlePosition.y > ballPosition.y)
{
paddlePosition.y -= movementSpeed;
}
else if(paddlePosition.y < ballPosition.y)
{
paddlePosition.y += movementSpeed;
}
transform.position = paddlePosition;
}
}
Answer by SlowCircuit · Jun 15, 2018 at 05:16 AM
Make sure you only have one object with the Ball component on it. Otherwise it might be getting the wrong one.
Maybe try increasing movement speed and see if that changes anything?
Make sure nothing else is changing the position of the AI paddle. If it's flickering then it's possibly it's being moved and moved back really fast.
If it's none of those things then post a screenshot of both the ball and AI paddle inspector. Also post a GIF/video of what the AI paddle does.
Answer by Plapatine · Jun 16, 2018 at 03:43 AM
@thetomfinch
I think I am getting the right one because when I try checking whether not the if/else if statements can trigger or not by printing the console they can.
I have tried a lot of different values but none of them seem have to any different effect
I feel like this might be the problem but unfortunately I have no idea how this could be solved
I couldn't figure out a way to get the video small enough to attach it here but here are the pictures from the inspector anyway (The first one is the red paddle on the right and the other is the ball)
Your answer
![](https://koobas.hobune.stream/wayback/20220612164815im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Pong AI/Paddle controller help 1 Answer
AI Field of vision 1 Answer
My Boss wont work 0 Answers
Artificial intelligence of multiple objects 1 Answer
AI will complete patrolling and wait for 5 seconds 2 Answers