- Home /
Detecting a string of collisions
I'm making a game, where if 4 balls of a certain colour touch, they all get destroyed. I know how to use OnCollisionEnter() for 2 of the balls touching, or even 3. But if you imagine a line of 4 balls touching
OOOO
1 2 3 4
The first ball and the last ball arn't touching so OnCollisionEnter() won't work. Any advice would be apprechiated. Many thanks,
Burnleyboy101
Try checking the collisions between the separate balls. I mean check if 1 and 2 are the same color if touching, then check if 2 and 3 are the same and then 3 and 4.
Something that I might suggest is to just have an array that you can go through ins$$anonymous$$d of using OnCollisionEnter() unless the collision is really important. I can imagine that function using a bit more resources than a simple for loop, but I might be wrong on that.
Are all the balls of the same size? If yes, then you can simply check the bounding box of the "n" balls.
If (boundingbox.volume <= ball.boundingbox.volume * n) then all of them hitting each other
Answer by Jamora · Sep 04, 2013 at 09:10 AM
You should create a class that describes a collision (say, MyCollisionClass)of multiple objects. Most easily implemented by maintaining a list of GameObject with functions to add and remove objects from the collision.
Now, each object will know which collision they're a part of, so any new colliders can just add themselves to that collision in OnCollisionEnter(). I set the collision class to null when exiting the collision, but a better design decision would be to use the null object pattern.
public MyCollisionClass{
/*
This class contains the list of GameObjects currently
engaged in the collision. There should also be a way to
add/remove GameObjects from the list. I suggest making a
wrapper for the normal list functions.
*/
}
public class MyCollider : MonoBehaviour{
MyCollisionClass currentCollision = null
void OnCollisionEnter(Collision col){
//you'll need null checks here too
currentCollision = col.gameObject.GetComponent< MyCollider >().currentCollision
currentCollision.Add(this.gameObject);
}
void OnCollisionExit(Collision col){
currentCollision.Remove(this.gameObject);
currentCollision = null;
}
}
You don't really explain your use case, but this will allow you, for example, to count how many objects are in a collision or gain access to each individual object that makes up that collision. If you need to know each collision, I would make a private static list of MyCollisionClass
es inside MyCollisionClass
in which each currently active collision is kept.
Your answer
Follow this Question
Related Questions
Collisions with CharacterController? 0 Answers
Collision problem Ignorecollision 2 Answers
Sequencing Spawning for Multiplayer 1 Answer
Allow one object to pass through another whilst keeping collisions. 1 Answer
Tree collisions do not work 2 Answers