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?
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;
}
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
}
}