How to determine if an Enemy is moving left or right?
First, here's the code
using UnityEngine;
using System.Collections;
public class BMoveAI : MonoBehaviour
{
public Vector2 pos1;
public Vector2 pos2;
public float speed;
void Update()
{
transform.position = Vector3.Lerp (pos1, pos2, Mathf.PingPong (Time.time * speed, 1.0f));
}
}
So what I'm trying to do is make my Enemy's sprite flip depending on whether he is moving left or right. So my question is how I would detect moving left or right?
Answer by Zee-Play · Feb 22, 2017 at 04:07 AM
You could store your character's Y position in a variable, and then in the next frame check whether the new position is smaller or greater than the last one. (Assuming Y axis is your horizontal, and it's that way ->) You might need to swap left and right depending on what your sprite looks like.
using UnityEngine;
using System.Collections;
private float oldPosition = 0.0f
public class BMoveAI : MonoBehaviour
{
public Vector2 pos1;
public Vector2 pos2;
public float speed;
void Start()
{
oldPosition = transform.position.y;
}
void Update()
{
transform.position = Vector3.Lerp (pos1, pos2, Mathf.PingPong (Time.time * speed, 1.0f));
if (transform.position.y > oldPosition) // he's looking right
{
transform.localRotation = Quaternion.Euler(0, 0, 0);
}
if (transform.position.y < oldPosition) // he's looking left
{
transform.localRotation = Quaternion.Euler(0, 180, 0);
}
oldPosition = transform.position.y; // update the variable with the new position so we can chack against it next frame
}
}
Thank you for the answer! However now when I start the game: The sprite just flips and then doesn't change... Any help is appreciated. :)
Try this, tested and it works
using UnityEngine;
using System.Collections;
public class B$$anonymous$$oveAI : $$anonymous$$onoBehaviour
{
public Vector2 pos1;
public Vector2 pos2;
public float speed;
private float oldPosition = 0.0f;
void Start()
{
oldPosition = transform.position.x;
}
void Update()
{
transform.position = Vector3.Lerp(pos1, pos2, $$anonymous$$athf.PingPong(Time.time * speed, 1.0f));
if (transform.position.x > oldPosition) // he's looking right
{
transform.localRotation = Quaternion.Euler(0, 0, 0);
}
if (transform.position.x < oldPosition) // he's looking left
{
transform.localRotation = Quaternion.Euler(0, 180, 0);
}
oldPosition = transform.position.x; // update the variable with the new position so we can chack against it next frame
}
}
Yes! It works! Thank you for your help Zee-Play. :)
Answer by asim15566 · Sep 05, 2021 at 09:28 AM
You can also try this one
public float oldPosition;
public bool movingRight = false;
public bool movingLeft = false;
void LateUpdate(){
oldPosition = transform.position.x;
}
void Update () {
if (transform.position.x > oldPosition) {
movingRight = true;
movingLeft = false;
}
if (transform.position.x < oldPosition) {
movingRight = false;
movingLeft = true;
}