1

Let's say that I have code like this:

private void actuallyDrawGraphics(Canvas canvas) {
    canvas.drawColor(Color.WHITE);

    for(Ball ball : balls){

        canvas.drawBitmap(ballBitmap,
                -16 + (ball.x / 100f) * canvas.getWidth(),
                -16 + (ball.y / 100f) * canvas.getHeight(),
                paint
                );
    }
}

Every ball is registered in an array. I need to make a collision (when one collides with the second) and everything goes well, until I have more balls, for example 10. It's not efficient to make a check like:

ball 1 with 2, 3, 4...

ball 2 with 1, 3, 4...

Is there any way that this can be done?

5
  • Probably still inefficient, but if you already checked ball 1 with 2, 3, 4, …, then when you check ball 2 you don't need to check with 1, just with 3, 4, …. Commented Sep 8, 2015 at 14:36
  • How many balls are there? Commented Sep 8, 2015 at 14:43
  • I'm confused as to what kind of answer you're looking for here. Can you add more to your question to clarify this? Commented Sep 8, 2015 at 14:45
  • Let's say that there are 5 balls floating randomly on the screen. If any of them collides with any they both change their vectors from x to -x and y to -y. There is a loop that draws balls and I have to make an if statement that checks if any of them collides. Commented Sep 8, 2015 at 14:48
  • 2
    Unless it's a perfomance problem, just stick with your/Nacho's solution. Otherwise chunkify the world space and do checks for balls in the origin and the 8 surrounding chunks Commented Sep 8, 2015 at 14:48

2 Answers 2

0
for (int i = 0; i < balls.size(); i++) {
    Ball ball = balls[i];
    for (int a = i + 1; a < balls.size(); a++) {
        Ball ball2 = balls[a];
        // check for collision with ball and ball2.
    }
}

Like Nacho was saying, I believe that this would be a better way to check every possible collision, but if you have a very large number of balls, then you may need to do something to reduce the number of checks you are making here. Or, you may need to improve your code that checks for a collision.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, big O notation is still not great on that. Binkan Salarymans suggestion for chunkifying the world space would be one of the next steps if there was a big need for a performance improvement I think. For a fairly small number of checks like having 10 or 20 balls, I doubt that there would be any performance issue though.
0

You need another data structure. For example an object Collision containing a List<Ball> ballsThatCollide; or something similar. Or for each Ball to have List<Ball> inCollisionWith. If you want simple arrays, then you'll need a N dimensional array where the dimensions are the balls and the intersection are collisions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.