I've been focusing on other games recently but it annoyed me that I skipped the AI part of making my pong game a 1 player game too. I have found out how to RayCast but am struggling with being able to make a path to predict where the ball will end up on the computer side. I have managed to get the first ray to work but in the second if-statement from the code below, it's somehow a loop. If anyone is able to help me, I would be extremely grateful!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RaycastTest : MonoBehaviour {
private Rigidbody2D rb2d;
private RaycastHit2D hit;
private Vector2 predictedCollision;
private Vector2 collisionPoint;
private int numberOfCollisions;
void Start () {
rb2d = GetComponent<Rigidbody2D> ();
numberOfCollisions = 0;
}
void FixedUpdate () {
//Directions of the ball (normalized)
Vector3 forward3 = new Vector3 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y, 0) * 20;
Vector2 forward2 = new Vector2 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y);
// If the ball has just hit the player paddle
if (BallMovement.isOnPath == true) {
if (numberOfCollisions == 0) {
//make sure we have the correct initial collision point from another script
collisionPoint = BallMovement.collisionPoint;
//draw and cast a ray to detect the next point of collision
Debug.DrawRay (collisionPoint, forward3, Color.red, 20f);
hit = Physics2D.Raycast (collisionPoint, forward2, Mathf.Infinity);
//print the name of the object that has been hit
print (hit.collider.name);
//change the initial collision point to the new one
collisionPoint = new Vector2 (hit.point.x, hit.point.y);
print (collisionPoint);
//add on to the number of collisions
numberOfCollisions += 1;
print (numberOfCollisions);
}
//if we still haven't reached the HitArea we need to do another bounce
if (hit.collider.name != "HitArea") {
//make sure we get the velocity after impact and reverse the direction of the y velocity.
forward2 = new Vector2(rb2d.velocity.normalized.x, rb2d.velocity.normalized.y * -1f);
forward3 = new Vector3 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y * -1f, 0) * 20;
//draw and cast a ray to detect the next point of collision
hit = Physics2D.Raycast(collisionPoint, forward2, Mathf.Infinity);
Debug.DrawRay(collisionPoint, forward3, Color.red, 20f);
//change the initial collision point to the new one
collisionPoint = hit.point;
print (collisionPoint);
//add on to the number of collisions
numberOfCollisions += 1;
}
//If we've hit the HitArea, we reset everything so it stops looping and we've got our predicted point of collision on the computer side.
if (hit.collider.name == "HitArea") {
predictedCollision = hit.point;
numberOfCollisions = 0;
BallMovement.isOnPath = false;
}
}
}
}