I handled this challenge of checking if there is a wall by using the raycast2D like this:
void Update()
{
onDrawGizmos();
wallInFront();
endOfTerrain();
myRigidbody2D.velocity = new Vector2(movementSpeed, 0f);
}
private void wallInFront(){
Vector2 position = transform.position;
Vector2 direction = new Vector2(transform.localScale.x, 0f);
RaycastHit2D hit = Physics2D.Raycast(position, direction, frontRayDistance, LayerMask.GetMask("Ground"));
if (hit.collider != null) {
transform.localScale = new Vector3(-transform.localScale.x,1,1);
movementSpeed *= -1;
}
}
private void endOfTerrain(){
Vector2 position = transform.position;
Vector2 direction = new Vector2(transform.localScale.x, -transform.localScale.y);
RaycastHit2D hit = Physics2D.Raycast(position, direction, diagonalRayDistance, LayerMask.GetMask("Ground"));
if (hit.collider == null) {
transform.localScale = new Vector3(-transform.localScale.x,1,1);
movementSpeed *= -1;
}
}
private void onDrawGizmos(){
Vector2 frontDirection = new Vector2(frontRayDistance * transform.localScale.x, 0f);
Vector2 diagonalDirection = new Vector2(diagonalRayDistance * transform.localScale.x, diagonalRayDistance * -transform.localScale.y);
Debug.DrawRay (transform.position, frontDirection, Color.blue);
Debug.DrawRay (transform.position, diagonalDirection, Color.red);
}
Hope that can help anyone in other ways.