I have coded it so that the enemy turns around when it hits the WallLeft, but for some reason it won’t turn around when it hits WallRight.
This .GIF shows the situation.
using UnityEngine;
/// <summary>
/// Simply moves the current game object
/// </summary>
public class MoveScript : MonoBehaviour
{
// 1 - Designer variables
/// <summary>
/// Object speed
/// </summary>
public Vector2 speed = new Vector2(5, 5);
bool touchingWallLeft = false;
bool touchingWallRight = false;
public Transform wallCheckLeft;
public Transform wallCheckRight;
float wallTouchRadius = 0.5f;
public LayerMask whatIsWallLeft;
public LayerMask whatIsWallRight;
/// <summary>
/// Moving direction
/// </summary>
public Vector2 direction = new Vector2(-1, 0);
public Vector2 movement;
void Update()
{
}
void FixedUpdate()
{
// 2 - Movement
movement = new Vector2(
speed.x * direction.x,
speed.y * direction.y);
// Apply movement to the rigidbody
rigidbody2D.velocity = movement;
touchingWallLeft = Physics2D.OverlapCircle(wallCheckLeft.position, wallTouchRadius, whatIsWallLeft);
touchingWallRight = Physics2D.OverlapCircle(wallCheckRight.position, wallTouchRadius, whatIsWallRight);
if (touchingWallLeft)
{
speed.x = -5;
direction.x = -1;
// 2 - Movement
}
else if (touchingWallRight) {
speed.x = 5;
direction.x = 1;
}
}
}