- Home /
How can I make my Enemy look/flip towards my player (2D TOP-DOWN)
MY ENEMY SCRIPT:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Enemy : MonoBehaviour {
// Public Variables
public float speed;
public GameObject effect;
// Private Variables
private Transform playerPos;
private Player player;
private Shake shake;
// Functions
private void Start()
{
shake = GameObject.FindGameObjectWithTag("ScreenShake").GetComponent<Shake>();
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
playerPos = GameObject.FindGameObjectWithTag("Player").transform;
}
private void Update()
{
transform.position = Vector2.MoveTowards(transform.position, playerPos.position, speed * Time.deltaTime);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
shake.CamShake();
Instantiate(effect, transform.position, Quaternion.identity);
player.health--;
Destroy(gameObject);
}
if (other.CompareTag("Projectile"))
{
shake.CamShake();
Instantiate(effect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
}
Answer by badadam · Jan 13, 2019 at 01:54 PM
First create emptyobject and add your enemy script to it. Add the enemy sprite object as a child to this empty object. Your empty object has to be (0,0,0) rotation values.
And your child sprite object must look at green up arrow of parent empty object. Right part of your sprite must look at red arrow of your parent empty object.
And use this codes in Update Method of enemy scripts.
Vector3 direction = player.position - transform.position;
direction.z = -100000;//if enemy look at opposite direction try 100000
transform.rotation = Quaternion.LookRotation(direction,Vector3.forward);
NOTE: Z POSITIONS OF ALL GAME OBJECTS MUST BE BETWEEN -100000 AND 100000 NOT EQUAL
Your answer
Follow this Question
Related Questions
How can I make my enemy always look/flip towards my player (2D top-down)? 1 Answer
How I make my enemy face the player or flip towards player (top-down game)? 0 Answers
Flipping enemy 2d character to the side he is walking? 1 Answer
How to flip parent without flipping child game object? 0 Answers
2D game unity player flip problems 1 Answer