2014-01-29 212 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