简体   繁体   中英

Java Objects in Array - collision detection

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM