球与矩形之间的碰撞

时间:2016-04-08 08:05:33

标签: java awt java-2d

我被要求根据球和矩形之间的碰撞来改变球的方向。

这是我的代码:

 public Velocity hit(Point collisionPoint, Velocity currentVelocity) {
    Velocity newVelocity = currentVelocity;

    // starting point - according to the upper left point of the rectangle
    double startX = rectangle.getUpperLeft().getX();
    double startY = rectangle.getUpperLeft().getY();

    double x = collisionPoint.getX();
    double y = collisionPoint.getY();

    // Y direction
    if ((x > startX) &&
            (x < startX + rectangle.getWidth())) {
        newVelocity.setDy((currentVelocity.getDy()) * (-1));
    }
    // X direction
    else if ((y > startY) &&
            (y < startY + rectangle.getWidth())) {
        newVelocity.setDx(currentVelocity.getDx() * (-1));
    }
    // hits the corners
    else {
        newVelocity.setDx(currentVelocity.getDx() * (-1));
        newVelocity.setDy(currentVelocity.getDy() * (-1));
    }

    return newVelocity;
}

说明: “命中”是一个获得碰撞点和球速度的函数。 只有在命中的情况下才会调用此函数。在功能中,我检查了球是否击中了矩形的右壁和左壁,底部或汤姆或其他角落。

public void moveOneStep() {

    Velocity currentVelocity = this.getVelocity();
    double collisionHeight;
    double collisionWidth;

    // starting point - according to surface
    double collisionStartX;
    double collisionStartY;

    double x = this.center.getX();
    double y = this.center.getY();

    Line trajectory = new Line(new Point(x, y), 
    new Point(x + currentVelocity.getDx(), 
    y + currentVelocity.getDy()));


    // get the closest collision point between the line and the rectangle
    CollisionInfo collisionInfo = this.gameEnvironment.getClosestCollision(trajectory);

    if (collisionInfo != null) {
        // there's a collision
        currentVelocity = collisionInfo.collisionObject().
        hit(collisionInfo.collisionPoint(), currentVelocity);
    } else {
        collisionHeight = this.surface.getHeight();
        collisionWidth = this.surface.getWidth();
        collisionStartX = this.surface.getStartingPoint().getX();
        collisionStartY = this.surface.getStartingPoint().getY();
        // X direction
        if ((x + currentVelocity.getDx() > collisionWidth - 
            radius - 1 + collisionStartX)
                || (x + currentVelocity.getDx() < radius + collisionStartX)) {
            currentVelocity.setDx((currentVelocity.getDx()) * (-1));
        }
        // Y direction
        if ((y + currentVelocity.getDy() > collisionHeight - 
           radius - 1 + collisionStartY) ||
                (y + currentVelocity.getDy() < radius + collisionStartY)) {
            currentVelocity.setDy(currentVelocity.getDy() * (-1));
        }

    }

    this.setVelocity(currentVelocity);

    this.center = this.velocity.applyToPoint(this.center);
}

说明:球按一条线移动。如果线条与矩形有碰撞点,我会检查每一步。

我有一个问题,球稍微进入矩形。我该如何改变?

谢谢

0 个答案:

没有答案