- Home /
How to monitor the movment speed of a 2D sprite
I am trying to get an enemy to follow the player when he gets to close, but I need him to flip between left and right but my only problem is I don't know how to monitor the speed of the enemy so I don't know when to tell it to flip, can someone please help me? here is my code: I do have a rigidbody2D attached to it so you can also use that.
public class FlyingEnemy : MonoBehaviour {
private PlayerController player;
public float moveSpeed;
public float playerRange;
public GameObject deathAffect;
public int pointsOnDeath;
public LayerMask playerLayer;
private bool playerInRange;
private Rigidbody2D RB;
// Use this for initialization
void Start ()
{
player = FindObjectOfType<PlayerController>();
RB = FindObjectOfType<Rigidbody2D>();
}
// Update is called once per frame
void Update ()
{
playerInRange = Physics2D.OverlapCircle(transform.position, playerRange, playerLayer);
if (playerInRange)
{
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, moveSpeed * Time.deltaTime);
}
if (RB.velocity.magnitude < 0)
{
transform.localScale = new Vector3(1f, 1f, 1f);
Debug.Log("moving left");
}
if(RB.velocity.magnitude > 0)
{
transform.localScale = new Vector3(-1f, 1f, 1f);
Debug.Log("moving right");
}
Comment