- Home /
Flip enemy based on player direction Unity 2D
Hey there. So what I want is fairly simple I believe. So I have a 2D enemy, and I want it to flip based on where the player is. I simply want the enemy to flip either left or right.
If the player is to the right of the enemy, the enemy should be looking right. If the player is on the left of the enemy, the enemy should be looking left. I would prefer this on the scale and not rotation. In this case, I want the snail to face the direction of the character in the X-axis, either left or right depending on where the player is.
Thank you.
PS: Would prefer it in C#.
Answer by SirPaddow · Jun 04, 2019 at 06:20 AM
The SpriteRenderer of your snail has a "flipX" attribute that you can check to flip the sprite, so your code should look something like:
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class SnailFacePlayer : MonoBehaviour
{
public Transform playerCharacter;
private SpriteRenderer spriteRenderer;
public void Awake()
{
this.spriteRenderer = this.GetComponent<SpriteRenderer>();
}
public void Update()
{
this.spriteRenderer.flipX = playerCharacter.transform.position.x < this.transform.position.x;
}
}
It friggin worked! Thanks. I'm definitely putting you in the credits of my game, that's if you'd like lol. Seriously though, thank you. It would have taken me forever to figure that out.
using System.Collections; using System.Collections.Generic; using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))] public class copfaceplayer : MonoBehaviour {
public Transform playerCharacter;
private SpriteRenderer spriteRenderer;
public void Awake()
{
this.spriteRenderer = this.GetComponent<SpriteRenderer>();
}
public void Update()
{
this.spriteRenderer.flipX = playerCharacter.transform.position.x < this.transform.position.x;
{
if (playerCharacter == null) playerCharacter = GameObject.FindGameObjectWithTag("Player").transform; }
}
}
Just exactly what i was looking for my pet that follows my player, thanks!
I managed to flip my characters toward player, but faced a problem the character keeps flipping if it is in the same position of the player, I managed to fix that problem but with so many steps and colliders :(
It's been more than a year now making my game trying to find a fix for that until I found this magic line of @SirPaddow which saved my life. Thank you so much
this.spriteRenderer.flipX = playerCharacter.transform.position.x < this.transform.position.x;
my best regards,,
Your answer
![](https://koobas.hobune.stream/wayback/20220612202603im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rotate/Flip Image in Unity 2d using Virtual Joystick 1 Answer
Sprite flip movement script not working! HELP! 0 Answers
My sprite is teleporting when I change my scale to -1 to flip it 1 Answer
How to Convert each 2D Array to GameObject 2 Answers
Top down 2d character controller sometimes walking backwards 1 Answer