Make enemy face left or right depending on player position
In my top down 2d game i have a script to make my enemy always face the player however if the player is directly above or below the enemy the enemy becomes super thin and cant be seen, so instead i want the enemy to flip on the x axis depending on which side the player is on, so if the player is on his left he faces left but if the player on on his right he faces right. My current script is here
public float moveSpeed;
Transform target;
public float minDistance;
private float range;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
target = GameObject.FindWithTag("Player").transform;
range = Vector2.Distance(transform.position, target.position);
transform.LookAt(target.position);
transform.Rotate(new Vector3(0, 90, 0), Space.Self);
if (range < minDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, moveSpeed * Time.deltaTime);
}
}
}
Answer by Kishotta · May 21, 2017 at 03:12 PM
change:
transform.LookAt (target.position);
to:
transform.LookAt (target.position, Vector3.back);
This will ensure the enemy uses the world's "back" direction (towards your 2D camera) as it's own "up" direction. Your enemy was getting "thinner" because it was rotating in the 3rd dimension. Set your Scene view to 3D when you play your game and you'll see the actual rotation.
Also, for the sake of performance, put
target = GameObject.FindWithTag("Player").transform;
into the Start function, if possible. ( Awake()
would be even better)
Thanks mate! This does help, only problem is my wolf sprite is a side view so using this the wolf goes upside down, i can easily just get a top down wolf sprite which would actually suit my game a bit more haha. But thats why i ask to just make him flip left or right, probs better off just using a top down wolf sprite though. But this did help so thanks! :)
No problem! I guess I misunderstood your question. To answer THAT question though, you could do a dot product of the wolf's forward vector (the left of right that it is facing) and the vector between the wolf and the target. If that dot product is negative, you need to flip the wolf, if not, it's already facing the right way.