2 using Controllers.Player;
4 using Random = UnityEngine.Random;
8 [RequireComponent(typeof(Rigidbody2D))]
9 [RequireComponent(typeof(BoxCollider2D))]
10 public class AIController : MonoBehaviour
12 [SerializeField] private float speed;
15 [SerializeField] private Leg leftLeg;
16 [SerializeField] private Leg rightLeg;
17 [SerializeField] private float maxLegAngle;
18 [SerializeField] private float legSpeed;
20 [Header("References")]
21 [SerializeField] private GameController game;
22 [SerializeField] private PlayerController player;
24 public Rigidbody2D Rigidbody => _rigidbody != null ? _rigidbody : _rigidbody = GetComponent<Rigidbody2D>();
25 private Rigidbody2D _rigidbody;
27 private float animationStep;
29 public BoxCollider2D BoxCollider => _boxCollider != null ? _boxCollider : _boxCollider = GetComponent<BoxCollider2D>();
30 private BoxCollider2D _boxCollider;
34 // Try to grab (steal) the ball every n seconds.
35 InvokeRepeating(nameof(GrabBall), 0, 0.5f);
38 private void GrabBall()
40 // Grab from the middle, and the bottom.
41 if (!game.player.HasBall || Random.Range(0, 100) > 70) // 30% chance of them grabbing the ball from the player.
43 game.enemy.GrabBall(transform.position);
44 game.enemy.GrabBall(transform.position + new Vector3(0f, BoxCollider.size.y / 2, 0f));
50 var movement = transform.position;
52 if (!game.enemy.HasBall) // Move towards the ball to grab it.
54 if (Vector2.Distance(player.root.transform.position, transform.position) < 2f) // Repel from the player if they get too close.
56 // transform.position += new Vector3(-(player.transform.position - transform.position).normalized.x, 0, 0) * (Time.deltaTime * speed / 2f);
57 transform.position = new Vector2(Vector2.MoveTowards(transform.position, player.root.transform.position, -1.5f * speed * Time.deltaTime).x, transform.position.y);
61 // transform.position += new Vector3(game.ball.transform.position.x - transform.position.x, 0f, 0f).normalized * (Time.deltaTime * speed);
62 transform.position = new Vector2(Vector2.MoveTowards(transform.position, game.ball.transform.position, speed * Time.deltaTime).x, transform.position.y);
65 else // Otherwise, move toward the basket, and then once we get within range, take the shot.
69 movement -= transform.position;
71 game.enemy.Move(transform.position + new Vector3(0f, BoxCollider.size.y / 2, 0f));
73 leftLeg.top.transform.localRotation = Quaternion.Euler(0, 0, maxLegAngle * Mathf.Sin(animationStep * legSpeed));
74 leftLeg.bottom.transform.localRotation = Quaternion.Euler(0, 0, maxLegAngle + maxLegAngle * Mathf.Sin(animationStep * legSpeed));
75 rightLeg.top.transform.localRotation = Quaternion.Euler(0, 0, maxLegAngle * Mathf.Sin(animationStep * -legSpeed));
76 rightLeg.bottom.transform.localRotation = Quaternion.Euler(0, 0, maxLegAngle + maxLegAngle * Mathf.Sin(animationStep * -legSpeed));
78 animationStep += Time.deltaTime * Mathf.Abs(movement.x);
84 public GameObject top;
85 public GameObject bottom;