I'm trying to program AI for a pong game and i'm trying to make the paddle game object follow the y co-ordinate movement of the ball game object.
The problem is that the paddle ends up just moving up and down and not actually following the ball.
This is the script i used to make it follow.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AIMove : MonoBehaviour {
public int speed;
public bool validUp = true;
public bool validDown = true;
void Awake()
{
}
void Update()
{
GameObject sphere = GameObject.Find("Sphere");
Transform spherePosition = sphere.GetComponent<Transform>();
float spherePos = spherePosition.position.y;
if (spherePos < (0) && validUp == (true))
{
transform.Translate(Vector3.up * speed * Time.deltaTime);
}
else if (spherePos > (0) && validDown == (true))
{
transform.Translate(Vector3.down * speed * Time.deltaTime);
}
if (transform.position.y >= (2.3F))
{
validUp = false;
}
else if (transform.position.y <= (-2.3F))
{
validDown = false;
}
else
{
validUp = true;
validDown = true;
}
}
}