本文介绍了数组中的Java对象-冲突检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的代码:

  private void实际上DrawGraphics(Canvas canvas){
canvas。 drawColor(Color.WHITE);

表示(球:球){

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

每个球都记录在一个数组中。我需要进行碰撞(当一个碰撞第二个时),一切都进行得很好,直到有更多的球,例如10。进行这样的检查并没有效率:



球1、2、3、4 ...



球2、1、3、4 ...



有什么办法可以做到这一点?

解决方案
 为(int i = 0; i< balls.size(); i ++){
Ball ball = balls [i];
for(int a = i + 1; a< balls.size(); a ++){
Ball ball2 = balls [a];
//检查与ball和ball2的碰撞。
}
}

像Nacho所说,我相信这会是一种检查所有可能发生的碰撞的更好方法,但是如果您有很多球,那么您可能需要做一些事情以减少在此进行的检查次数。或者,您可能需要改进检查冲突的代码。


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.

这篇关于数组中的Java对象-冲突检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 08:04