The idea here is that the raycast shoots downwards from an empty game object and when it detects that there is no ground below it the character should bounce back and walk the other way. When I get to the edge of my platform the character just gets stuck in place and keeps rotating on the Y axis.
public class npcAI : MonoBehaviour
{
public float speed;
public float distance;
private bool movingRight = true;
public Transform groundDetection; //raycast goes downward from this point
private Vector2 movementDirection;
void Start()
{
//Initialise direction
movementDirection = Vector2.right;
}
void Update()
{
transform.Translate(movementDirection * speed * Time.deltaTime);
RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, distance);
if (groundInfo.collider == false)
{
if (movingRight)
{
movingRight = false;
movementDirection = Vector2.left;
transform.localScale -= new Vector3(0.30F, 0, 0);
}
else
{
movingRight = true;
movementDirection = Vector2.right;
transform.localScale += new Vector3(0.30F, 0, 0);
}
}
}
The code above was edited to reflect the answer below. If you find yourself attempting to do the same thing and need to flip your sprite when you reach the edge change 0.30F to whatever double the X value of your sprite is in order to flip it. My sprites scale was (0.15, 0.15, 0) so I used 0.30F to flip my sprite. Be mindful of when you should use -= and when you should use +=.