So when the enemy hits the wall the enemy ends up turning around and then turning around again by the same block leaving my enemy in a loop
code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
[SerializeField] float moveSpeed = 1f;
Rigidbody2D myRigidBody;
// Use this for initialization
void Start()
{
myRigidBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (IsFacingRight())
{
myRigidBody.velocity = new Vector2(moveSpeed, 0f);
}
else
{
myRigidBody.velocity = new Vector2(-moveSpeed, 0f);
}
}
bool IsFacingRight()
{
return transform.localScale.x > 0;
}
private void OnTriggerExit2D(Collider2D collision)
{
transform.localScale = new Vector2(-(Mathf.Sign(myRigidBody.velocity.x)), 1f);
}
}
Please start your game, then pause it. Go to the scene view and zoom in so you can see the enemy’s collider. Then click on the button next to the Pause button. Do that multiple times until the enemy hits the wall. Click again until the enemy turns around, then click until it turns around again. Observe the collider the whole time.
Did you notice anything which does not seem to be correct?
After looking in closely it is triggered once the enemy has fully entered the ground meaning his full collider is in the ground he turns and turns again once the enemy has left the ground with his full collider and this cycle repeats forever