Hello. I am currently trying to program an enemy's movement across a platform. When it reaches the end of the platform, it supposed to turn around and walk to the other side of the platform. But when I test the game, the enemy only turns around the first time. When it starts walking and approaches the right side, it switches and starts moving to the left, but when it approaches the left side it just walks off.
Here's my code:
public float speed;
public bool movingLeft;
public bool grounded = false;
public Transform groundedEnd;
Rigidbody2D enemyBody;
// Use this for initialization
void Start () {
enemyBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
Raycasting ();
flipEnemy ();
enemyMovement ();
}
//check if enemy is grounded
void Raycasting(){
Debug.DrawLine (this.transform.position, groundedEnd.position, Color.green);
grounded = Physics2D.Linecast (this.transform.position, groundedEnd.position, 1 << LayerMask.NameToLayer("Ground"));
}
//flip enemy before falling off the edge
void flipEnemy(){
if(!grounded && movingLeft){
Vector2 localScale = gameObject.transform.localScale;
localScale.x *= -1;
transform.localScale = localScale;
movingLeft = false;
}
if(!grounded && !movingLeft){
Vector2 localScale = gameObject.transform.localScale;
localScale.x *= -1;
transform.localScale = localScale;
movingLeft = true;
}
}
//what direction the enemy is facing/walking
void enemyMovement(){
if (movingLeft) {
enemyBody.velocity = new Vector2 (-speed, enemyBody.velocity.y);
}
if (!movingLeft) {
enemyBody.velocity = new Vector2 (speed, enemyBody.velocity.y);
}
}
}