相互弹跳球(LibGDX)

时间:2014-08-12 17:36:36

标签: java android libgdx

我正在使用游戏开发框架libgdx开发Android游戏。 我想互相反弹多个球。我的方法是CircleCollision工作正常。但是当我尝试这个代码时,球有时会出现在一个随机的地方。它们不会设置为最小平移距离。

    public void moveBalls(float t) {
        // loop through all balls
        for(int i = 0; i < balls.size(); i++) {
             Ball ballA = balls.get(i);
             float vx = ballA.getVx(); // velocity x
             float vy = ballA.getVy(); // velocity y
             float x  = ballA.getX();  // position x
             float y  = ballA.getY();  // position y

             // check if ball collide with other ball
             for (int j = i + 1; j < balls.size(); j++) {
                   Ball ballB = balls.get(j);
                   float radius = BALL_SIZE / 2;
                   float pointXA = x + radius;
                   float pointYA = y + radius;
                   float pointXB = ballB.getX() + radius;
                   float pointYB = ballB.getY() + radius;
                   if(Collision.isCircleCollsion(pointXA, pointYA, pointXB, pointYB, radius, radius)) {
                       // vector between pointA and pointB
                       Vector2 delta = ballA.getPosition().sub(ballB.getPosition());
                       float distance = delta.len();

                       // calculate minimum translation distance vector
                       Vector2 mtd = delta.scl(((radius + radius) - distance) / distance);

                       // add mtd
                       x += mtd.x * 0.5f;
                       y += mtd.y * 0.5f;
                       ballB.setX(ballB.getX() - mtd.x * 0.5f);
                       ballB.setY(ballB.getY() - mtd.y * 0.5f);
                 }
             }

             vx = vx + Gdx.input.getAccelerometerX() * ACCEL_X_FACTOR;
             x -= t * vx;
             y -= t * vy;

             ballA.setVx(vx);
             ballA.setVy(vy);
             ballA.setX(x);
             ballA.setY(y);
        }
    }

变量f是帧增量时间。

vy设置为60f。

所有球的大小都相同。

以下是两个球半径为2的示例:

enter image description here

ballAPoint = (2;2)
ballBPoint = (5;4)
radius     = 2
distance   = sqrt((5-2)^2 + (4-2)^2) = 3,61

delta = (3;2)

// delta * ((radius + radius) - distance) / distance

mtd = delta * ((2 + 2) - 3,61) / 3,61 = (0,324, 216)

mtd.x / 2 -> x intersection
mtd.y / 2 -> y intersection

这似乎有效,但有时球会出现在屏幕上的随机位置。

出了什么问题?

0 个答案:

没有答案
相关问题