This post contains all the code that’s been written in this YouTube video.
AiScript.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
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
1 2 3 4 5 6 7 8 9 |
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