- Home /
How do I flip my enemy... One scrpit works, however it shrinks my enemy aswell... The other ones i've commented out tend to make the enemy flip multiple times
public float speed;
public float stoppingDistance;
public Animator anim;
//public Transform enemyGFX;
private Rigidbody2D rb;
public int damage = 100;
private bool m_FacingRight = true;
private Transform target;
public float lookRadius = 10f;
// Start is called before the first frame update
void Start()
{
target = PlayerManager.instance.player.transform;
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float distance = Vector2.Distance(target.position, transform.position);
if (distance > stoppingDistance)
{
if (distance <= lookRadius)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
anim.SetBool("isWalking", true);
/*if (rb.velocity.x >= 0.01f)
{
enemyGFX.localScale = new Vector3(-1f, 1f, 1f);
}
else if (rb.velocity.x <= -0.01f)
{
enemyGFX.localScale = new Vector3(1f, 1f, 1f);
}*/
if (target.position.x > transform.position.x)
{
transform.localScale = new Vector3(-1, 1, 1);
}
else if (target.position.x < transform.position.x)
{
transform.localScale = new Vector3(1, 1, 1);
}
}
}
}
/*private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
transform.Rotate(0f, 180f, 0f);
}*/
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, lookRadius);
}
You say it shrinks your enemy as well... when look at your enemy in the inspector normally, does it have different scale values than 1,1,1? If so you could do something like transform.localScale = new Vector3($$anonymous$$athf.Abs(transform.localScale.x)*-1, transform.localScale.y,, transform.localScale.z);
you can use a bool to keep track of the flipping so it doesn't flip multiple times
bool isFacingRight;
if(player.position.x > transform.position.x){
//face right
if(!isFacingRight){
transform.localScale = new Vector3(transform.localScale.x*-1,transform.localScale.y,transform.localScale.z);
isFacingRight=true;
}
}
else if(player.position.x < transform.position.x){
//face left
if(isFacingRight){
transform.localScale = new Vector3(transform.localScale.x*-1,transform.localScale.y,transform.localScale.z);
isFacingRight=false;
}
}
Answer by LiamColee · Feb 05, 2020 at 11:12 PM
is it shrinking because you have the scale of the enemy set to something higher than 1 in the editor? if that is the case, try vector3(-transform.localscale.x,transform.localscale.y,transform.localscale.z).
Thank you very much, I didn't use the code but ins$$anonymous$$d I decided to use an empty Gameobject and put the enemy as a child... Then i rescaled the Gameobject