- Home /
OnTriggerEnter2D not detecting
Hello! Its my first time here so i hope i can get help!, Im making an endless runner, i add the "infinite" background, and im adding also buildings, randomly positioned, and if one overlap with other, it recalculate his position, but does not work. I dont know where's the fail so... here we go
using UnityEngine;
using System.Collections;
public class Buildings : MonoBehaviour {
public float speed = -4.3f;
void Update () {
transform.Translate (speed * Time.deltaTime, 0, 0);
if (transform.position.x < -18) {
transform.Translate (Random.Range(35, 130), 0, 0);
}
}
void OnTriggerEnter2D(Collider2D coll){
if (coll.gameObject.tag == "build") {
transform.Translate (Random.Range (35, 130), 0, 0);
}
}
}
All the buildings have a box collider2d as a trigger, this code and the tag "build"
hi
I am not familiar with 2D collision but maybe try this function.
Answer by screenname_taken · May 30, 2014 at 02:23 PM
Hi. As far as i can tell, (at least with the 3D colliders i'm working with...) OnTriggerEnter (...) actually works only when something is entering the trigger when you run the game. So if something just pops/instantiates in the scene instead of waltz in, it won't register. Same with OnTriggerExit. Why i'm saying that? I'm making a game and has vanishing platforms. And when the platform vanished, OnTriggerExit didn't trigger to tell to the ball that it vanished.
So perhaps you can check with OnTriggerStay ? as that check to see if there is something in the trigger already instead of if it walked in.
Also, i think that unless you disable this code or check if the building is planted already and not being planted now, both buildings that touch each other might move away instead of the one coming in now.
What to try is to make all buildings take the same amount of space so that you have just a fixed value for distance. Save the place that the previous one was placed, and just add that fixed distance value to the transform of the new building that is to get placed.
How do the buildings react btw? do both buildings try to move, or just the one that gets placed at that time?