Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class EnemyMovement : MonoBehaviour
- {
- [SerializeField] private float speed;
- [SerializeField] private float rotationSpeed;
- [SerializeField] private float screenBorder;
- private Rigidbody2D rigidbody;
- private PlayerAwarenessController playerAwarenessController;
- private Vector2 targetDirection;
- private float changeDirectionCooldown;
- private Camera camera;
- private void Awake()
- {
- rigidbody = GetComponent<Rigidbody2D>();
- playerAwarenessController = GetComponent<PlayerAwarenessController>();
- targetDirection = transform.up;
- camera = Camera.main;
- }
- private void FixedUpdate()
- {
- UpdateTargetDirection();
- RotateTowardsTarget();
- SetVelocity();
- }
- private void UpdateTargetDirection()
- {
- HandleRandomDirectionChange();
- HandlePlayerTargeting();
- HandleEnemyOffScreen();
- }
- private void HandleRandomDirectionChange()
- {
- changeDirectionCooldown -= Time.deltaTime;
- if (changeDirectionCooldown <= 0)
- {
- float angleChange = Random.Range(-90f, 90f);
- UnityEngine.Quaternion rotation = UnityEngine.Quaternion.Euler(0, 0, angleChange);
- targetDirection = rotation * targetDirection;
- changeDirectionCooldown = Random.Range(1f, 5f);
- }
- }
- private void HandlePlayerTargeting()
- {
- if (playerAwarenessController.AwareOfPlayer)
- {
- targetDirection = playerAwarenessController.DirectionTopPlayer;
- }
- }
- private void HandleEnemyOffScreen()
- {
- UnityEngine.Vector2 screenPosition = camera.WorldToScreenPoint(transform.position);
- if ((screenPosition.x < screenBorder && targetDirection.x < 0) || (screenPosition.x > camera.pixelWidth - screenBorder && targetDirection.x > 0))
- {
- targetDirection = new UnityEngine.Vector2(-targetDirection.x, targetDirection.y);
- }
- if ((screenPosition.y < screenBorder && targetDirection.y < 0) || (screenPosition.y > camera.pixelHeight - screenBorder && targetDirection.y > 0))
- {
- targetDirection = new UnityEngine.Vector2(targetDirection.x, -targetDirection.y);
- }
- }
- private void RotateTowardsTarget()
- {
- float angle = Mathf.Atan2(targetDirection.y, targetDirection.x) * Mathf.Rad2Deg - 90f;
- UnityEngine.Quaternion targetRotation = UnityEngine.Quaternion.Euler(0, 0, angle);
- rigidbody.MoveRotation(Mathf.LerpAngle(rigidbody.rotation, targetRotation.eulerAngles.z, rotationSpeed * Time.deltaTime));
- }
- private void SetVelocity()
- {
- rigidbody.velocity = targetDirection * speed;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement