45 lines
1.5 KiB
C#
45 lines
1.5 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class EnemyMovementMelee : MonoBehaviour
|
|
{
|
|
public GameObject player;
|
|
public EnemyStats enemyStats;
|
|
public float targetDistance;
|
|
|
|
private float distance;
|
|
|
|
// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
enemyStats = GetComponent<EnemyStats>();
|
|
}
|
|
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
if(player != null){
|
|
// Calculate the distance between the enemy and the player
|
|
distance = Vector2.Distance(transform.position, player.transform.position);
|
|
|
|
// Get the direction to the player by subtracting the enemy's position from the player's position
|
|
Vector2 direction = player.transform.position - transform.position;
|
|
direction.Normalize(); // Normalize the direction vector
|
|
|
|
// Calculate the angle to rotate the enemy to face the player
|
|
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
|
|
|
|
// If the player is within a certain range, move towards them
|
|
if (distance < targetDistance)
|
|
{
|
|
// Move the enemy towards the player's position
|
|
transform.position = Vector2.MoveTowards(transform.position, player.transform.position, enemyStats.speed * Time.deltaTime);
|
|
|
|
// Rotate the enemy to face the player
|
|
transform.rotation = Quaternion.Euler(Vector3.forward * angle);
|
|
}
|
|
}
|
|
}
|
|
}
|