Java侧滚动游戏

时间:2011-04-07 03:59:32

标签: java scroll

我正在制作我自己的马里奥版本。我遇到的一个问题是如何进行游戏的侧滚动部分。但我不太清楚如何将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);
    }
}
}

1 个答案:

答案 0 :(得分:1)

您可能会发现在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);

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

祝你好运。