1
\$\begingroup\$

I have a stack of balls of 4 colors some touching some not. When you click on one color ball I want to destroy that ball and any other balls of that color that are close. They may not be touching so collision wont work.

How do I detect gameobjects close but not touching that are the same color? Say half a radius away from the edge of the ball clicked.

Here are the two scripts I'm working with to create and touch the game objects.

public class SpawnBalls : MonoBehaviour {
public Rigidbody ball;
public float waittime = 0.5f;

// Use this for initialization
void Start () {
    spawn ();
}

// Update is called once per frame
void Update () {
    //Instantiate (ball);

}
public void spawn(){
    //yield WaitForSeconds(waittime);

        for (var i = 0; i < 10; i++) {
            Instantiate (ball);
        }
}

}

Selecting the balls

public class Ball : MonoBehaviour {

public Color[] colors;
private Color ballpicked;

// Use this for initialization
void Start () {
    GetComponent<Renderer>().material.color = colors[Random.Range (0, 4)];
}

// Update is called once per frame
void Update () {

}
 void OnMouseDown(){
    if (Input.GetKey("mouse 0")){

        ballpicked = GetComponent<Renderer> ().material.color;

        //if (ballpicked == "Any other balls within a half a ball width") {

        //}

        Destroy (gameObject);
    }
}
\$\endgroup\$
3
\$\begingroup\$

There's a few physics methods you may be interested in:

  • OverlapSphere - Returns an array with all colliders touching or inside the sphere.
  • OverlapBox - Find all colliders touching or inside of the given box.

You can utilize one of the above to select all the objects within a specified area. Then you can iterate through them and just keep the ones you're interested in.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.