- Home /
store unique variable on first OnTriggerEnter
This is a 2D game:
||
|| `BC`
|| `Big Cirle`
|| <--- `Big Circle`
|| Big Circle`
|| `BC`
||
||
||
So Imagine the 'stick' on the left is a network of 9 cubes all stuck together. The 'Big Circle' is a sphere collider. Essentially the big sphere collider is the range of an auto-gun. When the cubes are in range I want the auto-gun to take out the first one that comes in range and that one only.
I also want it to take about a second, which I think can be done with a simple yield statement. After that second I want the autogun to start firing on the next closest cube(not exactly sure which one that is yet)...maybe they're already is an Algorithm for this.
In the trigger function you can get the first cube and store it in a var, but also wrap that part of the trigger code with a
if(enemyCube==null)enemyCube=collision.gameObject;
this way you will only fire at the one cube until it is destroyed(becomes null), then it will store the next cube and fire at that one. To add a delay, you should run a function straight after getting the enemyCube and add a yield WaitForSeconds(1); at the top of that function. You will need that function to then pass the enemyCube var to the autogun so it knows what to fire at.
You can add a range as well using the distance between the 2 objects, and just add the if condition for the range
On autoguns script
var dist=enemyCube.transform.position-transform.position;
if(dist.magnitude<=range)Fire();
use
if(dist.sqr$$anonymous$$agnitude<=range*range)Fire();
if you want to save performance, since the Sqrt() function that is used to calculate the exact magnitude is a lot more costly than a simple multiplication on the other side.
Good to know, ive never used sqr$$anonymous$$ag b4...thanks for the explanation as well.
How would you go about storing the first cube in a variable?
hey hijinxbassist can you do a little explanation on your first code sample (if(enemyCube==null)enemyCube=collision.gameObject;)? Is this supposed to be attatched to the cube script? the autogun script? Any help understanding would be greatly appreciated. Thanks.
Answer by wknight92 · May 17, 2012 at 09:19 PM
Hey hijinx, that works great but for my purposes I was trying to do something a little different.
function OnTriggerEnter (other : Collider){
if (other.tag == "enemyCube"){
yield Fire(other.gameObject);
}
}
function Fire (cube : GameObject){
yield WaitForSeconds (1.0);
Destroy(cube);
}
The pros of this : the cubes get destroyed in the order that they entered the 'range' of the collider(I want this to happen)
Cons: OnTriggerEnter is being called about every 10 milliseconds because of the speed of the Big Circle collider. So what ends up happening is the first cube is destroyed after the delay of 1 second and then all the other ones get destroyed almost instantly after that.
I want the collider to enter the cube network and destroy one cube per 1 second(for example). The order of cubes is important.