- Home /
How to read the movment speed of sprite and flip basied upon it
I am trying to get an enemy to follow the player when he get's 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");
}
}
Answer by CptKen · Oct 18, 2017 at 04:20 AM
RB.velocity.magnitude will always return a positive number so you cannot use that to check the direction of travel instead just check the x component of the velocity.
if(RB.velocity.x > Mathf.Epsilon)
{
//Moving Right
}
else if(RB.velocity.x < -Mathf.Epsilon)
{
//Moving Left
}
else
{
//Not moving left or right
}
Since you are comparing floats I suggest using Mathf.Epsilon instead of 0 because it's unlikely for a float to ever == 0 exactly due to floating point errors.
@Cpt$$anonymous$$en O$$anonymous$$, but one weird thing about it is that it take the enemy a good 3 seconds before he flips, Is my computer slow? is there a problem with the way I'm flipping the enemy, or is there another problem? (By the way I am now using transform.localRotation = Quaternion.Euler(0, 180, 0); to flip the enemy)
Your answer
Follow this Question
Related Questions
How to get the speed of an object? 3 Answers
How to increase and decrease the animation speed? 1 Answer
Slow down Rigidbody's speed to a stop 2 Answers