我创建了一个使用4个不同GameStates的游戏:READY,RUNNING,GAMEOVER和HIGHSCORE(GAMEOVER的变体,除了这个通知玩家已达到高分)。我的问题是我设置InputHandler的方式是,在GameState.READY表单中,用户可以触摸屏幕中的任何位置以进入GameState.RUNNING表单。我已经尝试了多种策略来创建一个playButton,但似乎没有什么工作正在我的方式。我创建了一个PlayButton类:
public class PlayButton {
private Vector2 position;
private Rectangle boundingRectangle;
private int width;
private int height;
private PlayScreen playScreen;
public PlayButton (float x, float y, int width, int height) {
this.width = width;
this.height = height;
position = new Vector2(x, y);
boundingRectangle = new Rectangle();
}
public void update(float delta) {
boundingRectangle.set(position.x,(position.y),width,height);
}
public float getTheX() {
return position.x;
}
public float getY() {
return position.y;
}
public float getWidth() {
return width;
}
public float getHeight() {
return height;
}
public Rectangle getBoundingRectangle(){
return boundingRectangle;
}
}
在我的InputHandler
我试过这个:
public InputHandler(GameWrold myWorld, float scaleFactorX, float scaleFactorY){
this.myWorld = myWorld;
mySam = myWorld.getSam();
playButton = new PlayButton(45,gameHeight-75,50,-35);
buttonPlay = myWorld.getPlayButton();
int midPointY = myWorld.getMidPointY();
this.scaleFactorX = scaleFactorX;
this.scaleFactorY = scaleFactorY;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Vector2 touchPos = new Vector2();
touchPos.set(Gdx.input.getX(), Gdx.input.getY());
Vector2 tuch = new Vector2(screenX,screenY);
buttonPlay.getBoundingRectangle();
touch = new Rectangle(touchPos.x,touchPos.y,5,5);
if (myWorld.isReady()) {
if(playButton.getBoundingRectangle().contains(touchPos)){
myWorld.start();
}
}
mySam.onClick();
if (myWorld.isGameOver() || myWorld.isHighScore()) {
// Reset all variables, go to GameState.READ
myWorld.restart();
}
return true;
}
}
正如您所看到的,我尝试使用Rectangle
变量创建touch
,我尝试检查touch
是否与playButton boundingRectangle冲突,如下所示:
if(Intersector.overlaps(touch,playButton.getBoundingRectangle())){
或
(playButton.getBoundingRectangle().overlaps(playButton.getBoundingRectangle()))
答案 0 :(得分:1)
不要发明一个圆圈,也不要打开门。
使用Scene2d:)
这是一个与libGDX完全兼容的简单UI框架,允许您在大约一行代码中创建按钮,滑块,Windows和其他小部件。
您可以在我上面附带的链接中找到一个很好的描述,但TLDR版本是:
使用适当的Stage
创建ViewportStage stage = new Stage(new FitViewport(WIDTH, HEIGHT));
将舞台设置为输入处理器(这意味着将捕获舞台上的所有事件)
Gdx.input.setInputProcessor(stage);
创建一个具有适当样式的按钮(在皮肤中定义)
Button button = new Button(skin, "style");
通过适当的操作将ClickListener附加到按钮
button.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y)
{
//some action
}
});
设置它的位置并将其添加到舞台
button.setPosition(x, y);
stage.addActor(button);
在act()
draw()
和render()
阶段的方法
//render()
stage.act();
stage.draw();
你已经赚了几个小时;)