- Home /
How do I flip an enemy that's automatically walking and targeting the player?
My player is able to jump over the enemies. They are able to target the enemy, but when he jumps over them. the enemies do not face the player when they are running after it again.
The way I have it causes this glitch Youtube-Game Glitch Video
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Opossum : MonoBehaviour
{
public float movespeed;
private Rigidbody2D posbody;
private Transform TPlayer;
private bool facingleft = true; //faceplacment
void Awake()
{
posbody = GetComponent<Rigidbody2D>();
}
// Start is called before the first frame update
void Start()
{
TPlayer = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
Flip();
transform.position = Vector2.MoveTowards(transform.position, TPlayer.position, movespeed * Time.deltaTime);
}
void Flip()
{
if (facingleft = !facingleft)
{
Vector3 oposcale = transform.localScale;
oposcale.x *= -1;
transform.localScale = oposcale;
}
}//Flip
}//Opossum
if(facingLeft = !facingLeft) should produce an error.. you need to use == operator, but in this case you can simply use if(!facingLeft)
Answer by highpockets · Mar 19, 2019 at 08:08 AM
I don’t think you need that facingLeft variable at all. You can just test like so:
if(enemy.transform.position.x >= player.transform.position.x){
//face left
}else
{
//face right
}
I put //face left and //face right because I don’t know which x direction is positive 1 or -1 for your sprite, but a simple test will sort that out
It still glitches out when I put in that code. $$anonymous$$y enemy sprite starts out facing left so it starts at 5. (enemy is to the right of me. That is why his X-axis is higher than $$anonymous$$e atm) so my first if statement is saying if enemy.x is greater than player.x *-1 so -5 X -1 = 5 which should face it to the right. I checked in the inspection manager and I can see it constantly flipping between -5 and 5.... When I make my player.x higher than the enemy is when the enemy grows a 2nd face to face my player character.
void Flip()
{
if (posbody.transform.position.x >= TPlayer.transform.position.x)
{
Vector3 oposcale = transform.localScale;
oposcale.x *= -1;
transform.localScale = oposcale;
} /*else if (posbody.transform.position.x <= TPlayer.transform.position.x) {
Vector3 oposcale = transform.localScale;
oposcale.x *= -1;
transform.localScale = oposcale;
}*/
}//Flip
Ok, you want to send me a zip of your project??
If the enemy x scale is 5 when he starts out and you know he faces left, it should be as simple as this (I reintroduced your faceLeft variable as a float):
float faceLeft;
void Start(){
faceLeft = enemy.transform.localScale.x;
}
void Update(){
if(enemy.transform.position.x >= player.transform.position.x){
enemy.transform.localScale.x = faceLeft;
}else
{
enemy.transform.localScale.x = -faceLeft;
}
}