This post contains all the code that’s been written in this YouTube video.
AiScript.cs
using UnityEngine;
public class AiScript : MonoBehaviour {
public float MaxMovementSpeed;
private Rigidbody2D rb;
private Vector2 startingPosition;
public Rigidbody2D Puck;
public Transform PlayerBoundaryHolder;
private Boundary playerBoundary;
public Transform PuckBoundaryHolder;
private Boundary puckBoundary;
private Vector2 targetPosition;
private bool isFirstTimeInOpponentsHalf = true;
private float offsetXFromTarget;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
startingPosition = rb.position;
playerBoundary = new Boundary(PlayerBoundaryHolder.GetChild(0).position.y,
PlayerBoundaryHolder.GetChild(1).position.y,
PlayerBoundaryHolder.GetChild(2).position.x,
PlayerBoundaryHolder.GetChild(3).position.x);
puckBoundary = new Boundary(PuckBoundaryHolder.GetChild(0).position.y,
PuckBoundaryHolder.GetChild(1).position.y,
PuckBoundaryHolder.GetChild(2).position.x,
PuckBoundaryHolder.GetChild(3).position.x);
}
private void FixedUpdate()
{
float movementSpeed;
if (Puck.position.y < puckBoundary.Down)
{
if (isFirstTimeInOpponentsHalf)
{
isFirstTimeInOpponentsHalf = false;
offsetXFromTarget = Random.Range(-1f, 1f);
}
movementSpeed = MaxMovementSpeed * Random.Range(0.1f, 0.3f);
targetPosition = new Vector2(Mathf.Clamp(Puck.position.x + offsetXFromTarget, playerBoundary.Left,
playerBoundary.Right),
startingPosition.y);
}
else
{
isFirstTimeInOpponentsHalf = true;
movementSpeed = Random.Range(MaxMovementSpeed * 0.4f, MaxMovementSpeed);
targetPosition = new Vector2(Mathf.Clamp(Puck.position.x, playerBoundary.Left,
playerBoundary.Right),
Mathf.Clamp(Puck.position.y, playerBoundary.Down,
playerBoundary.Up));
}
rb.MovePosition(Vector2.MoveTowards(rb.position, targetPosition,
movementSpeed * Time.fixedDeltaTime));
}
}
Boundary.cs
struct Boundary
{
public float Up, Down, Left, Right;
public Boundary(float up, float down, float left, float right)
{
Up = up; Down = down; Left = left; Right = right;
}
}

Assets/Scripts/AiScript.cs(12,50): error CS0723: `AiScript.playerBoundary’: cannot declare variables of static types
Assets/Scripts/AiScript.cs(12,50): error CS0723: `AiScript.puckBoundary’: cannot declare variables of static types
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://www.binance.com/uk-UA/register?ref=W0BCQMF1
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://accounts.binance.com/register-person?ref=P9L9FQKY
Your article helped me a lot, is there any more related content? Thanks! https://www.binance.info/register?ref=IHJUI7TF