- Home /
transform.position not executed with OnTrigger2D
Hello everyone. I'm trying to script enemies AI, by using triggers. My goal is to use a transform.position when player enters inside enemy trigger.
Here is my code (my game is 2D with top-down movement just like beat'em up games) :
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class EnemyAI : MonoBehaviour
 {
   
     public float speed;
     public Transform target;
     bool triggered = false;
 
     void Start()
     {
        target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
     }
 
     void Update()
     {
         if (triggered == true)
         {
             transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
             Debug.Log(triggered); //I used this debug.log to see if function changes to true
         }
     }
 
     void OnTriggerEnter2D(Collider2D other)
     {
         if (other.gameObject.tag == "Player")
         {
            // Debug.Log("Hello");
         }
     }
 
     void OnTriggerStay2D(Collider2D other)
     {
         if (other.gameObject.tag == "Player")
         {
             Debug.Log("Going to hit you");
             triggered = true;
         }
     }
 
     void OnTriggerExit2D(Collider2D other)
     {
         if (other.gameObject.tag == "Player")
         {
             Debug.Log("bye");
             triggered = false;
         }
     }
 }
With debug.log messages I managed to test my boolean triggered, it triggers with messages displayed inside console, but my enemy does not want to move.
I also tried to put the transform.position directly inside void update, once I hit play enemy begins to move towards me.
Where is the problem ?
Many thanks to anyone who can find out.
Is it a 2D game or a 3D game? I just ask because you have 2D trigger colliders, but it appears your movement is in 3D with Vector3.$$anonymous$$oveTowards
It's a 2D game, but the movement works when looped inside void update() without any boolean. I do not think it's a part of issue.
Ok, but you can change Vector3.$$anonymous$$oveTowards to Vector2.$$anonymous$$oveTowards. I can't see anything else wrong with your code. I'll take a look at your project if you want to send a zip folder
Answer by Neferlem · Mar 21, 2019 at 10:26 PM
Find a solution ! Attached a Rigibody to both Player and Enemy, with Kinematic as Body Type and "Never Sleep" as Sleeping mode. Then I changed OnTriggerEnter2D to OnTriggerStay2D and it's working !
Your answer
 
 
             Follow this Question
Related Questions
trigger is not working 0 Answers
How to find a transform with name in prefab 2 Answers
OnTriggerEnter2D not working 2 Answers
Trigger won't read my Bool change 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                