【问题标题】:Ball to Rectangle collision球到矩形碰撞
【发布时间】:2020-12-01 23:36:04
【问题描述】:

您好,我正在用 java 制作一个需要从球碰撞到矩形的游戏。

pos.x = 球的 x 值

pos.y = 球的 y 值

vel.x = x 球的速度

vel.y = 球的 y 速度

sh = 球的高度

sw = 球的宽度

W = 矩形的宽度

H = 矩形的高度

到目前为止我有:

  boolean insideRect = pos.x >= X && pos.x <= X+W && pos.y >= Y && pos.y <= Y+H;
  
  if(insideRect){
  
    if(pos.y + sh/2 >= H){
       vel.y = (-1*vel.y)*gravity;
       vel.x *= .6;
       if(pos.y < Y+H/2){
         pos.y = Y;
       } else{
         pos.y = Y+H;
       }
    }
    if(pos.x + sw/2 > W){
       vel.x = -1*vel.x;
    }       
  }

但是,这只是说它是击中矩形的左侧还是右侧,以及击中的是顶部还是底部。

因此,如果您在 if 语句下打印,输出将是:(left, up), (right, down), (left, down), (right, up)

所以问题在于,要让它工作,我只能有一个,左、右、上或下。

如果我有两个,那么它会认为它同时撞到天花板和右侧墙壁,并且有两个视觉输出。

我该如何解决这个问题?

【问题讨论】:

标签: java algorithm math physics


【解决方案1】:
/**
     * checks to see if the obstacles and balls collide.
     * Utilizes bounding boxes for obstacles and coordinates for ball:
     * + = Obstacle
     *            ballTop
     *             : :
     *          :      :
     *ballLeft :        : ballRight
     *          :      :
     *            : :
     *         ballBottom
     *
     *          ____
     *          |+++|
     *          |+++|
     *          |+++|
     *          ----
     * @param ball
     * @param rect
     * @return boolean
     */

    public boolean intersects(Ball ball, Obstacle rect){
        double r = ball.getRadius();

        double rectTop = rect.y;
        double rectLeft = rect.x;
        double rectRight = rect.x + rect.width;
        double rectBottom = rect.y + rect.height;

        double ballTop = ball.y - r;
        double ballLeft = ball.x - r;
        double ballRight = ball.x + r;
        double ballBottom = ball.y + r;


        //NO COLLISIONS PRESENT
        if(ballRight < rectLeft){
            return false;
        }
        if(ballTop > rectBottom){
            return false;
        }
        if(ballBottom < rectTop){
            return false;
        }
        if(ballLeft > rectRight){
            return false;
        }

        //HAS TO BE A COLLISION
        return true;
    }

//In Logic File
private void collideBallObstacles(Ball ball,Obstacle rect){
        if(rect.intersects(ball, rect)){
            ball.velX *= -1;
            ball.velY *= -1;
            if (ball == player){
                flashGreen();
                obstaclesevaded--;
            }
            obstacles.remove(rect);
        }
    }

您还必须渲染它,并更改变量或创建适合此代码的变量。

只是好奇——这个游戏的名字会是什么?

【讨论】:

    猜你喜欢
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2014-03-18
    • 1970-01-01
    相关资源
    最近更新 更多