Search code examples
c#unity-game-enginetransformscale

getting my 2d sprite flip to work depending on a Transform's location from it


So, this code just isn't responding for whatever reason. I have an enemy that I'm trying to get to face the player at all times (The enemy swoops over the player's head back and forth periodically). But other than making a flip happen whenever a timer hits 0, which doesn't really work all that well, I can't get the Flip function to work. I know the Flipper function is fine; I already tested it out and everything. I'm just not sure how to tell the enemy that when the player is to the left of it, to turn, and vice versa.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class dragoonDetection : MonoBehaviour {

private Rigidbody2D rb;
private Animator anim;
public Transform Player;
private bool facingRight = true;

void Start ()
{
    rb = GetComponent<Rigidbody2D> ();
    anim = GetComponent<Animator> ();
}

void Update()
{
    Flip();
}

    void Flip()
{
    if (Player.transform.localScale.x > 0) {
        transform.localScale = new Vector3 (1.69f, 1.54f, 1f);
    }
        if (Player.transform.localScale.x < 0) {
            transform.localScale = new Vector3 (-1.69f, 1.54f, 1f);
    }
}

void Flipper()
{
    facingRight = !facingRight;
    Vector2 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}
}

Got any ideas? I'd rather avoid using FindGameObject because it's not actually looking for the player script. It's looking for a child transform with no script attached to the player. And because I have two different player GameObjects that you can switch to anytime in the game, it wouldn't really work for me in that regard.


Solution

  • You will need to perform a check of some sort against the players position with the bird position if you want it to face the player at all times. A barebones method would just be to compare the x-positions of the two objects and change the scale accordingly.

    void Update()
    {
         transform.localScale = new Vector3(getDir()*1.69f, 1.54f, 1);
    }
    
    private int getDir()
    {
        if (player.transform.position.x < transform.position.x)
            return -1;
        else 
            return 1;
    }
    

    You should throw some additional checks in here to keep it from updating the scale every frame when there is no change.