我正在制作自己的mario版本。我遇到的一个问题是如何做游戏的侧滚动部分。但是我不太了解如何将imageableX和imageableY实现到世界展示中。
任何帮助将非常感激!这是我到目前为止所拥有的:

public class World extends JPanel implements Runnable, KeyListener{

private static final int BEGINNING_X = 0, ENDING_X = 10000;
private static final int TOP_Y = 0, BOTTOM_Y = 5000;
private boolean inGame = false;

private Player player;
//set up a new world with a player
public World(Player player){
    inGame = true;
    this.player = player;
}

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    //the world size
    g.drawRect(0, 0, BEGINNING_X, ENDING_X);
}

//check to see if the new x postition is valid on the game board
public boolean isValidXPosition(double x){
    if(x < BEGINNING_X || x > ENDING_X){
        return false;
    }
    return true;
}

public double imageableStartX(Player player){
    if(player.returnX() - 100 <= BEGINNING_X)
        return BEGINNING_X;
    else
        return player.returnX() - 100;
}

public double imageableTopY(Player player){
    if(player.returnY()-100 <= BOTTOM_Y)
        return BOTTOM_Y;
    else
        return BOTTOM_Y - 100;
}

public double imageableEndX(Player player){
    if(player.returnX() + 200 <= ENDING_X)
        return ENDING_X;
    else
        return player.getX() + 200;
}

public double imageableBottomY(Player player){
    if(player.returnY()+100 >= BOTTOM_Y)
        return BOTTOM_Y;
    else
        return BOTTOM_Y + 100;
}

public void run() {
    while(inGame){
        //TODO run game code
    }
}

public void keyTyped(KeyEvent e) {}

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_RIGHT){
        player.moveRight();
    }
    if(e.getKeyCode() == KeyEvent.VK_LEFT){
        player.moveLeft();
    }
    if(e.getKeyCode() == KeyEvent.VK_SPACE){
        player.setSprint(true);
    }
    if(e.getKeyCode() == KeyEvent.VK_UP){
        player.Jump();
    }


}

public void keyReleased(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_UP){
        player.Descend();
        player.setFalling(true);
    }
    if(e.getKeyCode() == KeyEvent.VK_SPACE){
        player.setSprint(false);
    }
}
}

最佳答案

您可能会发现,更容易在paintComponent()方法中实现X和Y位置定义,而不是将流程抽象为其他方法并每次都传递Player对象。尝试为视口尺寸定义常量(VIEWPORT_WIDTH,VIEWPORT_HEIGHT等)。在paintComponent()方法中,将其与玩家的坐标一起引用以将您的角色放置在屏幕上。还要确保使用相对坐标:

// center the screen on the player, though you can modify it to do otherwise
int viewportX = player.returnX() - VIEWPORT_WIDTH/2;
int viewportY = player.returnY() - VIEWPORT_HEIGHT/2;

g.setColor(Color.WHITE);
g.fillRect(viewportX, viewportY, VIEWPORT_WIDTH, VIEWPORT_HEIGHT);


如果您希望视口始终存在于世界中,即使您的角色移动到屏幕边缘,也可以正常进行所有位置计算,但在实际绘制任何内容之前要进行一些检查,以便进行更改到您的视口位置,以防它碰巧脱离屏幕。

祝好运。

09-13 05:39