Java碰撞检测故障

时间:2016-02-21 03:23:46

标签: java collision-detection collision detection

我正在尝试编写一个碰撞检测,它将检测玩家正在碰撞的一侧。我尝试了两种方法,但都没有效果。在这个例子中,如果玩家从瓷砖的右侧发生碰撞,那么他可以向右滑动并向左滑动瓷砖,然后在离开瓷砖后卡住

这是我的碰撞检测代码(我让玩家扩展了实体超类)

public void collide(Entity e) {
    /**
     * Previous code:
    if ((e.x + e.width) == this.x && (e.y < height && e.y > y)) {
        if (e.dx > 0) {
            System.out.println("Collided from left");
            e.dx = 0;
        }
    } else if (e.x == (x + width) && (e.y < height && e.y > y)) {
        if (e.dx < 0) {
            System.out.println("Collided from right");
            e.dx = 0;
        }
    }
    if ((e.y + e.height) == this.y && (e.x < width && e.x > this.x)) {
        if (e.dy > 0) {
            System.out.println("Collided from top");
            e.dy = 0;
        }
    } else if (e.y == (this.y + this.height) && (e.x < width && e.x > this.x)) {
        if (e.dy < 0) {
            System.out.println("Collided from bottom");
            e.dy = 0;
        }
    }
    */

    if(e.collisionBox.intersects(collisionBox) || collisionBox.intersects(e.collisionBox)) {
        if(e.right) {
            if(e.dx > 0 && !colRight) {
                System.out.println("Collided from left");
                e.dx = 0;
                colLeft = true;
                colRight = false;
                e.x -= 1;
            }
        } else if(e.left && !colLeft) {
            if(e.dx < 0) {
                System.out.println("Collided from right");
                e.dx = 0;
                colRight = true;
                colLeft = false;
                e.x += 1;
            }
        }
        if(e.up) {
            if(e.dy < 0) {
                System.out.println("Collided from bottom");
                e.dy = 0;
                e.y += 1;
            }
        } else if(e.down) {
            if(e.dy > 0) {
                System.out.println("Collided from top");
                e.dy = 0;
                e.y -= 1;
            }
        }
    }
}

0 个答案:

没有答案