-1

我正在做一个游戏,遇到了一个问题。我做了一个碰撞检测,当多边形接触瓷砖时,它说真的。虽然这对于让玩家不要走(真的?)墙壁是完美的。当我应用重力时,它应该以相同的方法停止,但会出现问题。它一直在下落,直到它撞到地板上,但你也不能再走路了,所以我需要另一个碰撞检测。我不知道从哪里开始?:( 谢谢。

4

2 回答 2

1

将所有图块加载到 ArrayList 中。然后,您可以使用 for-each 循环将碰撞检测应用于您的播放器的所有图块。请注意,以下示例可能并未声明所有必要的工作,但它应该可以帮助您了解这种碰撞检测方法的工作原理并允许您将其实现到您的游戏中。

Tile.java

    import java.awt.Rectangle;
    private int tileWidth = 32;
    private int tileHeight = 32;
    private int x;
    private int y;
    public class Tile() {
        public Tile(int tx, int ty) {
            x = tx * tileWidth;
            y = ty * tileHeight;
        }
        public Rectangle getBounds() {
            return new Rectangle(x, y, tileWidth, tileHeight);
        }
    }

CheckCollision.java

    import java.awt.Rectangle;
    public class CheckCollision {
        public boolean isColliding(Player player, Tile tile) {
            Rectangle pRect = player.getBounds();
            Rectangle tRect = tile.getBounds();
            if(pRect.intersects(tRect)) {
                return true;
            } else {
                return false;
            }
        }
    }

播放器.java

    import java.awt.Rectangle;
    import java.util.ArrayList;
    public class Player {
        public void move(ArrayList<Tile> tiles) {
            y -= directionY; //falling
            for(Tile t: tiles) { // for all of the Tiles in tiles, do the following
                Tile next = t;
                if(CheckCollision.isColliding(this, next) {
                    y += directionY; //stop falling
                }
            }
            x -= dx; // move your x
            for(Tile t: tiles) { // for all of the Tiles in tiles, do the following
                Tile next = t;
                if(CheckCollision.isColliding(this, next) {
                    x += directionY; //move back if collides                  }
            }

        }

        public Rectangle getBounds() {
            return new Rectangle(playerX, playerY, playerWidth, playerHeight);
        }
    }

Graphics.java(绘制瓷砖和播放器的类)

    import java.awt.ActionListener;
    import java.util.ArrayList;
    public class Graphics extends JPanel implements ActionListener {
        public ArrayList<Tile> tiles = new ArrayList();
        Player player = new Player();
        public JPanel() {
            tiles.add(new Tile(0, 0)); //adds a Tile at X:0 Y:0 to ArrayList tiles
        }

        @Override
        public void ActionPerformed(ActionEvent e) {
            player.move(tiles);
        }
    }
于 2012-02-17T08:01:08.613 回答
0

我的 Minecraft 克隆版也有类似的问题。问题是我的代码在每一帧都检测到与地板的碰撞,我通过取消所有 3 个维度的运动来响应。我改变了它,所以我只取消了那个动作的垂直分量,它工作得很好。

于 2014-01-03T05:12:21.097 回答