- Home /
How to detect a character is leaving a 3D world?
I have an open world 3D game where my character will run around and if he gets too close to the edges he will hear a geiger counter, his eyes will start to close & eventually start to die from the radiation. My problem is I don't know how to enclose my world in a "ring" collider to trigger my code to do this. I have seen suggestions to use ProBuilder Basic but I would hate to bring in yet another whole new asset just to solve this.
Answer by toddisarockstar · Jul 19, 2017 at 09:38 PM
all you need to do is check the distance of the player from the center of the level. here is a 2D distance function:
public bool die;
public Vector3 center = Vector3.zero;//<-center of level here
public float ringsize = 20;//<-size of ring
float timer = 0;
void Update(){
timer += Time.deltaTime;
if(timer>1){timer-=1;
die=false;
if (distance (transform.position, center) < ringsize) {
die=true;
}}}
public float distance (Vector3 v1, Vector3 v2){
float f1 = v1.x - v2.x;
float f2 = v1.z - v2.z;
f1 *= f1;f2 *= f2;
return Mathf.Sqrt(f1+f2);}
@toddisarockstar I guess that seems simple enough. There is a Distance function between two Vectors I think. Looking at @hexagonius answer, would it be more efficient to wrap the whole thing in a sphere a check for OnTriggerExit
then start to kill him ins$$anonymous$$d of doing a check every second?
i adjusted the script to check every second and change a bool for you. this certainly wont cause any preformance issues. just put this on your player and your done! ...That easy!
unity has a vector three distance function but it checks 3d distance. i gave you one for 2d. its just a bit faster to calculate distance with 2 vectors which is all you need and it will check in a ring shape ins$$anonymous$$d of a dome/sphere shape...just incase you end up with high places in your level! .
Answer by hexagonius · Jul 19, 2017 at 09:03 PM
The easiest would be to use a giant sphere and react to it on OnTriggerEnter and OnTriggerExit. Or you just check the distance of the character each or every other frame from the center.