- Home /
Don't move unless in BoxCollider2D (C#)
I made a box collider that fits the screen, and follows the character. I don't want any enemies to move unless they are in the screen collider. I have them working fine if I start 'AI' in 'void Start', but they work in AND outside the screen. (I'm fairly new to C#)
using UnityEngine;
using System.Collections;
public class EnemyAI_Aktamin : MonoBehaviour {
protected Animator animator;
public static int Move = Random.Range(1, 4);
void Start()
{
animator = GetComponent<Animator>();
}
**void OnTriggerEnter2D(Collision2D Screen)
{
if (Screen.collider.tag == "Screen")
{
StartCoroutine(AI()); //If on screen, begin move process
}
else
{
StopCoroutine(AI()); //If off screen, pause
}
}**
IEnumerator AI()
{
if (Move > 0 && Move <2) //Best I could think of for 3 if statements since bool is 2
{
animator.SetBool("Walking", true);
StartCoroutine(Right()); //move right, works
}
if (Move > 1 && Move <3)
{
animator.SetBool("Walking", true);
StartCoroutine(Left());
}
if (Move > 2 && Move <4)
{ //stand still
}
yield return new WaitForSeconds (1.0f);
animator.SetBool("Walking", false);
Move = Random.Range(1, 4); //randomize next direction to move
StartCoroutine(AI());
StopCoroutine(Right());
StopCoroutine(Left());
}
etc. . . .
The way this is written is because thats the way that best made sense to me, and the easiest I can personally think of. I made this one by myself, hairflip, but I'm sure there are many issues otherwise. xD
The screen collider is a trigger, and I've run out of ideas. If you have any tips at all for the whole script, please suggest those too. :) Thank you!
I tried to bold the code I need help with, but it just made double asterisks. :P
Answer by HarshadK · Dec 01, 2014 at 11:45 AM
You should pass Collider2D for argument to your OnTriggerEnter2D. Also you need to check if the character went out of the trigger to make him stop.
void OnTriggerEnter2D(Collider2D Screen)
{
if (Screen.collider.tag == "Screen")
{
StartCoroutine(AI()); //If on screen, begin move process
}
}
void OnTriggerExit2D(Collider2D Screen)
{
if (Screen.collider.tag == "Screen")
{
StopCoroutine(AI()); //If off screen, pause
}
}
The enemy is still not moving. I understand what you are saying, though. I've put him in a position in the screen, and off, and tried switching back and forth in-game. He still just idles at me and doesn't move. :/
Your answer
![](https://koobas.hobune.stream/wayback/20220613172841im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
[Answered] Level Complete? 1 Answer
How to use Physics2D.IgnoreCollision2D in Unity 5 to cancel a trigger 0 Answers
Trigger only one collider? 1 Answer
Can't click gameobject when over another trigger? 1 Answer
Collision with renderer.enabled? 0 Answers