using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/* What I’m trying to do: I have a top-down shooter game with a simple circle that can move around, and I’m working on this enemy that will rotate itself to face the player, wait and then dash in that direction at a capped range. Then wait and repeat. I have so many problems I don’t even know where to begin. The enemy smoothly rotates to the player, dashes once, and then jitters around */
// Save the players location, slowly rotate until the enemy is facing the player’s direction
// Then wait for a second and lunge at that saved location (The location where the player was a
// second ago) with a capped range
// Wait a second Then Repeat
/
public class EnemyDasher : MonoBehaviour
{
[Header(“Attack”)]
[SerializeField] float dashSpeed = 4f;
[SerializeField] float maxDashDistance = 6f;
[SerializeField] float rotationSpeed = 2f;
[SerializeField] float timeToRotate = 2f;
[SerializeField] float delayAfterRotate = 1f;
[SerializeField] float delayAfterDash = 1f;
[Header("Others")]
Transform playerTransform;
Vector2 playerLateLocation;
float angle = 0f;
float distanceToPlayer = 0f;
Quaternion targetRotation;
Vector2 newPlayerPosition;
bool canRotateToPlayer;
bool canCheckPlayerPos;
bool canDashToPlayer;
void Start()
{
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update()
{
StartCoroutine(MoveAll());
//RotateToPlayer();
DashToPlayer();
}
void GetPlayersLocation()
{
playerLateLocation = playerTransform.position;
}
IEnumerator RotateToPlayer()
{
// if(canRotateToPlayer)
{
GetPlayersLocation();
angle = Mathf.Atan2(playerLateLocation.y - transform.position.y, playerLateLocation.x - transform.position.x) * Mathf.Rad2Deg;
targetRotation = Quaternion.Euler(new Vector3(0, 0, angle));
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
yield return new WaitForSecondsRealtime(timeToRotate);
}
}
void CalculatePlayerMoveTo()
{
canRotateToPlayer = false;
distanceToPlayer = Vector2.Distance(transform.position, playerLateLocation);
if (distanceToPlayer < maxDashDistance)
{
distanceToPlayer = maxDashDistance;
}
float x = distanceToPlayer * Mathf.Cos(angle * Mathf.Deg2Rad);
float y = distanceToPlayer * Mathf.Sin(angle * Mathf.Deg2Rad);
newPlayerPosition = new Vector2(x, y);
}
void DashToPlayer()
{
if(canDashToPlayer)
{
transform.position = Vector2.MoveTowards(transform.position, newPlayerPosition, dashSpeed * Time.deltaTime);
}
}
IEnumerator MoveAll()
{
StartCoroutine(RotateToPlayer());
yield return new WaitForSecondsRealtime(delayAfterRotate);
CalculatePlayerMoveTo();
canDashToPlayer = true;
yield return new WaitForSecondsRealtime(distanceToPlayer / dashSpeed);
canDashToPlayer = false;
}
}