Hi everyone,
I’m trying to make a MoveTowards movement to be interrupted, when moving object enters in a trigger area.
The MoveTowards function in triggered by a first trigger when player is approaching enemy. Then, when enemy is close to player, a second trigger plays an animation. And I want the MoveTowards movement to be interrupted when enemy is inside 2nd trigger area.
Here is the code of my script attached to enemy :
public class HitBoxPlayer : MonoBehaviour
{
public Animator animator;
public Transform stopPosition;
private EnemyAI triggeredBool;
void Start()
{
animator = GetComponent<Animator>();
stopPosition = GetComponent<Transform>();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.GetComponent<Collider2D>().tag == "PlayerHitBox")
{
animator.SetTrigger("Push");
}
}
void OnTriggerStay2D(Collider2D other)
{
if (other.GetComponent<Collider2D>().tag == "PlayerHitBox")
{
animator.SetFloat("Moving", 0);
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.GetComponent<Collider2D>().tag == "PlayerHitBox")
{
animator.ResetTrigger("Push");
}
}
void Update()
{
}
}
And here is the code for enemy movement :
public class EnemyAI : MonoBehaviour
{
public float speed;
public Transform target;
public Animator animator;
public bool triggered = false;
private bool facingRight = false;
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
void OnTriggerStay2D(Collider2D other)
{
if (other.GetComponent<Collider2D>().tag == "Player")
{
triggered = true;
if (triggered == true)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
animator.SetFloat("Moving", Mathf.Abs(speed));
}
}
}
void Update()
{
if (target.transform.position.x < gameObject.transform.position.x && facingRight)
Flip();
if (target.transform.position.x > gameObject.transform.position.x && !facingRight)
Flip();
}
void Flip() //function used to make enemy flip left/right
{
facingRight = !facingRight;
Vector3 tmpScale = gameObject.transform.localScale;
tmpScale.x *= -1;
gameObject.transform.localScale = tmpScale;
}
void OnTriggerExit2D(Collider2D other)
{
if (other.GetComponent<Collider2D>().tag == "Player")
{
animator.SetFloat("Moving", 0);
triggered = false;
}
}
}
I tried to make triggered function false by calling it inside HitBoxPlayer, but nothing so far. Also tried to get enemy position and T instant and to make a transform.position with thoses data, neither.
Thanks to anyone who can find out an answer.