Hi
I am in the process of making a 2d platformer and have got a simple enemy sprite who I have managed to get moving back and forth, but I am really having issues with getting the sprite to flip when going the other direction.
I have tried various different ways but I have a feeling that the movement script I am using makes it difficult.
I have spent the last 4 hours trying to get this to work and have become very frustrated!
This is the script I am using to move him and I have tried adding a flip function but the sprite goes crazy when he reaches the point where he should flip.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GroundEnemyMove : MonoBehaviour
{
private Vector3 posA;
private Vector3 posB;
private Vector3 nextpos;
public bool facingLeft;
[SerializeField]
public float speed;
[SerializeField]
private Transform Enemy;
[SerializeField]
private Transform transformB;
// Use this for initialization
void Start()
{
posA = Enemy.localPosition;
posB = transformB.localPosition;
nextpos = posB;
}
// Update is called once per frame
void Update()
{
Move();
}
void Flip()
{
facingLeft = !facingLeft;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
private void Move()
{
Enemy.localPosition = Vector3.MoveTowards(Enemy.localPosition, nextpos, speed * Time.deltaTime);
if (Vector3.Distance(Enemy.localPosition, nextpos) <= 0.1)
{
ChangeDestination();
}
}
private void ChangeDestination()
{
nextpos = nextpos != posA ? posA : posB;
transform.position = nextpos;
Flip();
}
}