2014-01-29 40 views
5

我想用libGDX創建一個簡單的棋盤遊戲。只要你對我想要做的事情有一個粗略的想法,想象寶石迷陣(雖然我的當然不是那麼複雜)。libGDX:爲棋盤遊戲創建網格

遊戲涉及一個單元格爲正方形的棋盤。取決於級別,這個網格有不同數量的單元格,比如6x6或8x8。我還想包括一些很好的動畫來切換兩個相鄰單元格的位置(如在Bejeweled中)。當然,屏幕上還需要有一些按鈕。

我的問題是:什麼是最好的方法來做到這一點?我應該使用舞臺,然後表格的網格?那麼我還可以輕鬆製作動畫(使用通用吐溫引擎)?還是單獨繪製精靈更好?還是有另一種完全不同的方式來處理這個問題?

謝謝您的解答,

乾杯,

託尼

回答

5
Sprite square = new Sprite(new Texture("texture")); 

渲染

float squareWidth = camera.viewportWidth/squaresOnWidth; 
float squareHeight = camera.viewportHeight/squaresOnHeight; 
square.setWidth(squareWidth); 
square.setHeight(squareHeight); 
batch.begin(); ` 
for(int y = 0; y < squaresOnHeight; y++){ 
    for(int x = 0; x < squaresOnWidth; x++){ 
     square.setX(x * squareWidth); 
     square.setY(y * squareHeight); 
     square.draw(batch); 
    } 
} 
batch.end(); 

這應該輸出紋理的網格,未經測試。

如果你想創建流暢的動畫你一定要看看UniveralTweenEngine,這裏有什麼可以做一個演示:http://www.aurelienribon.com/universal-tween-engine/gwt/demo.html

如果你想在按鈕網格來代替。

OrthoGraphicCamera camera = new OrthoGraphicCamera(); 
camera.setToOrtho(false, yourViewportWidth, yourViewportHeight); 
camera.translate(xPos, yPos); 
Stage stage = new Stage(your wanted stage width, your wanted stage height, false, batch); 
stage.setCamera(camera); 
for(int y = 0; y < buttonsOnHeight; y++){ 
    for(int x = 0; x < buttonsOnWidth; x++){ 
     stage.addActor(new TextButton("" + x + y * buttonsOnWidth, textButtonStyle); 
    } 
} 

渲染

float buttonWidth = camera.viewportWidth/buttonsOnWidth; 
float buttonHeight = camera.viewportHeight/buttonsOnHeight; 
for(int y = 0; y < buttonsOnHeight; y++){ 
    for(int x = 0; x < buttonsOnWidth; x++){ 
     TextButton button = stage.getActors().get(x + y * buttonsOnWidth); 
     button.setX(x * buttonWidth); 
     button.setY(y * buttonHeight); 
     button.setWidth(buttonWidth); 
     button.setHeight(buttonHeight); 
    } 
} 

然後繪製階段,請注意您應停止當前正在運行,因爲舞臺有它自己的batch.begin()和batch.end()的任何批次。您可以在stage.draw();之後再次啓動批處理。

stage.act(delta); 
stage.draw(); 
+0

好吧,所以你不要使用舞臺。但是,如何在沒有舞臺的情況下添加按鈕?或者有可能只有一個階段只覆蓋部分屏幕? – tomet

+0

答案已被編輯,這是你的意思嗎? – thetheodor

+0

謝謝你的努力。我想要一個Sprites和一些按鈕下面的網格。所以我需要以某種方式渲染。 – tomet

0

爲了有一個網格,你可以而且應該使用相機:

OrthographicCamera cam = new OrthographicCamera(8,8); 

你告訴相機具有8×8 y的視口。 攝像機(0,0)點位於屏幕中間。

有它在你需要它的位置設置爲

cam.translate(camWidth/2, camHeight/2); 

現在你可以在底線在sqare.setX(0)添加sqares爲sqares或sqare.setY(3)將其從左側添加上4RD排左側底部向右。對於動畫,您還可以使用Actions,它允許您向演員添加不同的動作並讓他隨着時間的推移執行動作。例如:

actor.addAction(Actions.parallel(Actions.moveTo(float x, float y, float duration), Actions.rotateTo(float rotation, float duration))); 

隨着你告訴你的演員,從他的位置移動到(x,y)duration秒,雖然他移動到這個位置,他從他目前的旋轉duration秒旋轉到rotation此代碼示例。 希望這會有所幫助

+0

沒有一個方法調用setPosition,它被命名爲translate並且執行相同的操作。另外,當你手動設置攝像機爲0,0時,你可以調用setToOrtho(); – thetheodor

+0

攝像機位置是0/0我不記得確切的方法名稱,Eclipse幫助我很多:P感謝您的評論我將編輯我的答案! – Springrbua

+0

Eclipse確實如此。真的有很大的幫助,不得不在測試代碼之前張貼!:D – thetheodor