2011-04-07 106 views
2

我正在製作我自己的馬里奧版本。我遇到的一個問題是如何做側面滾動遊戲的一部分。但我不知道如何將imageableX和imageableY實現到世界展示中。 任何幫助將不勝感激!以下是我迄今爲止:Java側面滾動遊戲

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

你可能會考慮使用2D平鋪引擎來處理繪圖http://stackoverflow.com/questions/903760/java-2d-game-engine-for-tile-based-game – LumpN 2011-04-07 08:10:15

+0

對不起,這聽起來有點愚蠢,但是從來沒有從事瓦片引擎的工作,你能簡單地解釋他們做什麼以及如何製作一個? – mimis40 2011-04-07 20:15:26

回答

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); 

如果你希望你的視在任何時候都保持在世界上,甚至當你的角色移動到屏幕的邊緣,做你的位置計算正常,但是在實際繪製任何東西之前先進行一些檢查,以便在發生脫離屏幕的情況下對視口位置進行更改。

祝你好運。