Showing posts with label bowling. Show all posts
Showing posts with label bowling. Show all posts

Sunday, 19 May 2013

How to find all objects that are in collision with specified object.

While scripting bowling system I had to solve problem to monitor amount of ball in the arm, and control new ball providing.





Every time, when on the upper arm there is less than three ball I want to provide new ball. To find out how many balls is actually on arm, I was searching in unity for something like getListOfObjectsInWhichImInCollision(). What I found is Physics.OverlapSphere which "Returns an array with all colliders touching or inside the sphere." The point is, that sphere is not the shape that I could use for my problem so I made class for arm and override functions OnCollisionEnter/OnCollisionExit.
 class UpperArm extends MonoBehaviour {  
   private var ballAmount : int = 0;  
   private var ballTag = "Ball";  
   function OnCollisionEnter(c : Collision) {  
     if (itsBall(c)) {  
       ballAmount++;  
     }  
   }  
   function OnCollisionExit(c : Collision) {  
     if (itsBall(c)) {  
       ballAmount--;  
     }  
   }  
   function itsBall(c : Collision) {  
     return ((ballTag == c.transform.tag) ? true : false);  
   }    
 }
I needed only amount of balls on arm. If You need to have list of this objects: add a list variable and update it in onEnter/onExist function.