Java Objects in Array - collision detection

前提是你 提交于 2019-12-24 11:35:51

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/32460510/java-objects-in-array-collision-detection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!