Hi guys!
I have created a Pong game that has an AI that is almost beatable, changing the speed of the AI can make it ridiculously easy or hard depending on the way you go about it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ComputerMovement : MonoBehaviour {
private float speed;
private float reAdjustSpeed = 1f;
private Rigidbody2D computer2d;
public static bool isTwoPlayer;
GameObject theBall;
Rigidbody2D rb2d;
void Start() {
computer2d = GetComponent<Rigidbody2D> ();
}
void FixedUpdate() {
if (isTwoPlayer == true) {
speed = 5f;
if (Input.GetKey (KeyCode.W)) {
computer2d.position += Vector2.up * speed * Time.deltaTime;
}
if (Input.GetKey (KeyCode.S)) {
computer2d.position += Vector2.down * speed * Time.deltaTime;
}
}
if (isTwoPlayer == false) {
speed = 3f;
if (theBall == null) {
theBall = GameObject.FindGameObjectWithTag ("Ball");
}
rb2d = theBall.GetComponent<Rigidbody2D> ();
//Is the ball going left or right
if (rb2d.velocity.x > 0) {
if (rb2d.velocity.y > 0) {
if (rb2d.position.y > computer2d.position.y) {
MoveUp ();
}
if (rb2d.position.y < computer2d.position.y) {
MoveDown ();
}
}
if (rb2d.velocity.y < 0) {
if (rb2d.position.y > computer2d.position.y) {
MoveUp ();
}
if (rb2d.position.y < computer2d.position.y) {
MoveDown ();
}
}
}
//Whilst it's not moving at the paddle, let it gain a slight reset by moving with the ball at a slower pace.
if (rb2d.velocity.x < 0) {
if (computer2d.position.y < 0) {
computer2d.position += Vector2.up * reAdjustSpeed * Time.deltaTime;
}
if (computer2d.position.y > 0) {
computer2d.position += Vector2.down * reAdjustSpeed * Time.deltaTime;
}
}
}
}
void MoveDown() {
if (Mathf.Abs(rb2d.velocity.y) > speed) {
computer2d.position += Vector2.down * speed * Time.deltaTime;
} else {
computer2d.position += Vector2.down * speed * Time.deltaTime;
}
}
void MoveUp() {
if (Mathf.Abs (rb2d.velocity.y) > speed) {
computer2d.position += Vector2.up * speed * Time.deltaTime;
} else {
computer2d.position += Vector2.up * speed * Time.deltaTime;
}
}
}
I have looked up several posts across many different forums in order to create a much better AI. Most of the posts recommend that I use Raycasts to find out exactly where the ball might hit the paddle. I have looked up how to use them and I'm just completely lost, do raycasts consider collisions and go on infinitely or once they hit a wall, that's where it'll end up? Would anyone be able to help me understand raycasts a little better?
If you have another solution that enables me to calculate exactly where the ball will end up on the opponents side, I am more than willing to hear it
Thanks again if you read this!