- Home /
My enemy character is not facing the player correctly!
My enemy character does face the player, but it's the wrong side of the enemy. I want it to be the front of the enemy, but I don't know how it works.
Enemy script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float enemySpeed;
public float stoppingDistance;
public float retreatDistance;
private float timeBTWShots;
public float startTimeBTWShots;
public int maxEnemyHealth = 100;
public GameObject enemyProjectile;
private Rigidbody2D rb;
private Transform player;
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
player = GameObject.FindGameObjectWithTag("Player").transform;
timeBTWShots = startTimeBTWShots;
}
void Update()
{
if(Vector2.Distance(transform.position, player.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards
(transform.position, player.position, enemySpeed * Time.deltaTime);
}
else if(Vector2.Distance(transform.position, player.position) < stoppingDistance
&& Vector2.Distance(transform.position, player.position) > retreatDistance)
{
transform.position = this.transform.position;
}
else if(Vector2.Distance(transform.position, player.position) < retreatDistance)
{
transform.position = Vector3.MoveTowards
(transform.position, player.position, -enemySpeed * Time.deltaTime);
}
//Enemy sprite rotation
Vector3 direction = player.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rb.rotation = angle;
direction.Normalize();
if(timeBTWShots <= 0)
{
Instantiate(enemyProjectile, transform.position, Quaternion.identity);
AudioManager.PlaySound("laserShoot");
timeBTWShots = startTimeBTWShots;
}
else
{
timeBTWShots -= Time.deltaTime;
}
}
public void TakeDamage(int damage)
{
maxEnemyHealth -= damage;
if(maxEnemyHealth <= 0)
{
Destroy(gameObject);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
How can I make the EnemyBullet go further than my target? 0 Answers
Player Move-Rotation 0 Answers
orienting player in one direction 1 Answer
Help with rotating a sprite with mouse. 2 Answers