如何修复此碰撞检测块?

时间:2013-05-07 02:10:05

标签: java libgdx collision-detection

我一直在使用LibGDX框架在Java上打破这个破砖游戏。这是我的第一个java游戏。我对其他语言有一点经验,但我遇到了一些麻烦。我设置了碰撞检测功能,大部分都可以使用。球有时会以不正确的方向反弹,有时会撞到不应该的挡块。我一直在搜索,但很难将它翻译成我的游戏。

我的代码非常糟糕,因为球只以45度角移动。不太现实,这将是我修复后的下一步。

public void checkBrickCollision()
{
    for (int i=0;i<level.brickCount;i++) {

            if (level.bricks[i].GetVisible() == true) {
                if (level.bricks[i].getRect().overlaps(ball.getRect()))
                {



        int xd = (int) Math.abs( (ball.ballRect.x + ball.ballRect.width - level.bricks[i].brickRect.x - level.bricks[i].getRect().width) /2 );
        int yd = (int) Math.abs( (ball.ballRect.y + ball.ballRect.height - level.bricks[i].brickRect.y - level.bricks[i].getRect().height) /2 );

        if (xd > yd)
        {
            // Collision on top or bottom, reverse y velocity
            ball.ballSpeedY = -ball.ballSpeedY;
            Score score = new Score(level.bricks[i].getScore(),(int)level.bricks[i].brickRect.x,(int)level.bricks[i].brickRect.y);
            scoreList.add(score);
            level.bricks[i].Destroy();

            System.out.println("Top/Bottom");
            return;
        }


        if (yd > xd)
        {
            // Collision on left or right, reverse x velocity
            ball.ballSpeedX = -ball.ballSpeedX;
            Score score = new Score(level.bricks[i].getScore(),(int)level.bricks[i].brickRect.x,(int)level.bricks[i].brickRect.y);
            scoreList.add(score);
            level.bricks[i].Destroy();

            System.out.println("Sides");
            return;
        }

        if (xd == yd)
        {
            // Collision on corners, reverse both
            ball.ballSpeedX = -ball.ballSpeedX;
            ball.ballSpeedY = -ball.ballSpeedY;
            Score score = new Score(level.bricks[i].getScore(),(int)level.bricks[i].brickRect.x,(int)level.bricks[i].brickRect.y);
            scoreList.add(score);
            level.bricks[i].Destroy();

            System.out.println("Corners");
            return;
        }           



                }       
}
}
}

1 个答案:

答案 0 :(得分:0)

我建议您将 level.bricks [] 数组放在 ArrayList 列表中,以便您可以从列表中廉价删除()和/或销毁()它们。苍蝇,避免在level.bricks数组中每次迭代检查空值(除非你的设置不介意你的数组中的null)。此外,它还可以避免在每个渲染周期中检查所有砖块的数组大小,每次迭代...

List<Brick> brickList = new ArrayList<Brick>();
for (brick: level.bricks) {
    brickList.add( new Brick(brick) );
}
//-------or-------
//if the brick object is a Sprite
for (brick: level.bricks) {
    brickList.add(brick);
}

我认为将错误的砖块检测为“击中”的问题与尝试补偿球纹理和边界是矩形有关。我建议使用 com.badlogic.gdx.math.Circle 类来定义球的边界。以下是 com.badlogic.gdx.math.Intersector 的脏自定义碰撞包装,它应该与您在上面尝试的内容一起使用。它假设球的视觉像素延伸到纹理的边缘,并且球纹理是方形的:

public class Collider {
    private String bounceType = "";
    private boolean vertical = false;
    private boolean horizontal = false;

    // Segment Vertices of the Rectangle
    private Vector2 leftStart = new Vector2();
    private Vector2 leftEnd = new Vector2();
    private Vector2 topStart = new Vector2();
    private Vector2 topEnd = new Vector2();
    private Vector2 rightStart = new Vector2();
    private Vector2 rightEnd = new Vector2();
    private Vector2 bottomStart = new Vector2();
    private Vector2 bottomEnd = new Vector2();

    private Vector2 center = new Vector2();
    private Circle ballBounds = new Circle();

    // Pointers passed once during construction
    private Ball ball;
    private List<Brick> brickList;
    private List<Score> scoreList;

    /**
     * Constructor requires that ball and brickList pointers are given.
     * <p>
     * Runs the updateBallBounds() method after assigning the parameters
     *
     *@param ball points to the ball to be used for the collision calculations
     *@param brickList points to a list of brick objects to check against
     *@param scoreList points to a list of score objects to track the score
     */
    public Collider(Ball ball, List<Brick> brickList, List<Score> scoreList) {
        this.ball = ball;
        this.brickList = brickList;
        updateBallBounds(this.ball, this.ballBounds);
    }

    /**
     * Sets the position and radius of the bounding circle
     * for the given ball with a rectangular shape in order
     * to prepare it for bounds checking.
     *
     * @param ball The ball object to 
     * @param bounds The circle object that will store the bounds information
     */
    private void updateBallBounds(Ball ball, Circle bounds) {    
        bounds.set( (ball.ballRect.x + (ball.ballRect.width/2)),  //Center x pos
                    (ball.ballRect.y + (ball.ballRect.height/2)), //Center y pos
                    (ball.ballRect.width / 2) ); //Radius of ball
    }

    /**
     * Builds the start and end Vectors for each of the segments
     * of the provided rectangle. Also builds the center Vector for
     * the ball.
     * <p>
     * Used to prepare for finding which segments of the rectangle the 
     * ball is intersecting 
     *  
     * @param brickRect The rectangle to process the line segments from
     */
    private setVectors(Rectangle brickRect) {
        leftStart.set(brickRect.x, brickRect.y);
        leftEnd.set(brickRect.x, brickRect.height);
        topStart.set(brickRect.x, brickRect.height);
        topEnd.set(brickRect.width, brickRect.height);
        rightStart.set(Poyline( brickRect.width, brickRect.y);
        rightEnd .set(brickRect.width, brickRect.height);
        bottomStart.set(brickRect.x, brickRect.y);
        bottomEnd.set(brickRect.width, brickRect.y);

        center.set(ballBounds.x, ballBounds.y);
    }

    /**
     * Finds bricks in the list that the ball is currently
     * colliding with.
     * <p>
     * For every rectangle that the ball is currently colliding with,
     * the method calls the setVectors() method to prepare the start-end
     * vertices for the processCollision() method.
     * <p>
     * WARNING: this may not handle multiple collision very well. It
     * should work, but you most likely will not give very good results 
     * on multiple brick hit detected. You should think about including 
     * a break statement after the first collision is detected and let 
     * the Collider find an additional collision during the next render()
     * call.
     */  
    public void detectCollisions() {
        updateBallBounds(ball, ballBounds);
        for (brick: brickList) {
            if( Intersector.overlaps(ballBounds, brick.brickRect) ) {
                setVectors(brick.brickRect);
                processCollision(brick, brick.brickRect);
                //break;
            }
        }
    }

    /**
     * Detects how to handle the collision based on the segments being hit.
     *
     *@param brick the brick found by detectCollision() method. will be
     *             destroyed after collision is processed
     */  
    public void processCollision(Brick brick) {
        if ( Intersector.intersectSegmentCircle( topStart, topEnd,
                                                 center * center,
                                                 ballBounds.radius ) ||
             Intersector.intersectSegmentCircle( bottomStart, bottomEnd,
                                                 center * center,
                                                 ballBounds.radius )) {
            vertical = true;
        }

        if ( Intersector.intersectSegmentCircle( leftStart, leftEnd,
                                                 center * center,
                                                 ballBounds.radius ) ||
             Intersector.intersectSegmentCircle( rightStart, rightEnd,
                                                 center * center,
                                                 ballBounds.radius ) ) {
            horizontal = true;
        }

        // The following could return the value to a calling entity.
        // Then the game logic of what to do here would be decoupled.
        if (vertical && horizontal) {
            bounceType = "CORNER"
        } else if (vertical && !horizontal) {
            bounceType = "VERTICAL"
        } else if () {
            bounceType = "HORIZONTAL"
        } else {
            // The game blows up...
        }

        switch (bounceType) {
            case "VERTICAL":
                ball.ballSpeedY = -ball.ballSpeedY;
                break;
            case "HORIZONTAL":
                ball.ballSpeedX = -ball.ballSpeedX;
                break;
            case "CORNER":
                ball.ballSpeedY = -ball.ballSpeedY;
                ball.ballSpeedX = -ball.ballSpeedX;
                break;
            default: // Try not to blow up the game...
                break;
        }
        Score score = new Score(brick.getScore(), brick.x, brick.y)
        scoreList.add(score);
        brickList.remove(brick);
        brick.destroy();
    }
}

我确定这里有错误,没有经过测试。除了之前的假设之外,它不会阻止在数组中呈现砖块(除非destroy()负责处理,并且希望不会在渲染时查找空值...)。

基本结构可以做得更好......

  • 有一些除外,请尝试抓住东西。
  • 您可以添加更多Typed构造函数和方法来覆盖更多形状。
  • 可以使用方法添加空间分区以映射静态边界 施工。然后您的动态对象可以记录它们的分区 当前占用并且仅查询另一个的碰撞结果 记录在这些分区列表中的对象。
  • 我认为应该解耦和处理此类的实现 在其他地方。
  • 这也可以让你创建一个返回/触发的碰撞类或事件。

希望这会有所帮助。


我还建议您查看Box2D。您的要求看起来很简单,可以轻松学习它的使用方法。 This page可以向您展示如何配置和使用LibGDX。这将允许您快速实现对象的材料属性,旋转球,速度变化,角度反弹......,自动化的各种善良,将拯救你的大脑一些周期。物理引擎为您完成所有数学运算。您只需初始化并逐步执行,即可监听事件(如碰撞)。

祝你好运。