当我在libgdx中触摸特定纹理时绘制纹理



我正在用libgdx制作游戏。如果我触摸屏幕,就会出现一个纹理,但我真正想做的是,当我触摸一个特定的纹理时,另一个纹理必须出现。这是我现在的代码:

public class MyGame extends InputAdapter implements ApplicationListener {
    SpriteBatch batch;
    Texture ball;
    Texture bat;
    @Override
    public void create() {
        ball = new Texture("ball.png");
        bat = new Texture("bat.png");
        batch = new SpriteBatch();
    }
    @Override
    public void render() {
        batch.begin();
        if (Gdx.input.isTouched()) {
            batch.draw(ball, Gdx.input.getX(), Gdx.graphics.getHeight()
                    - Gdx.input.getY());
            batch.draw(bat, 50, 50);
            batch.end();
        }
    }
    }   

这不是整个代码,只是用来显示这些纹理的代码。

我真的很感谢你的帮助。谢谢

下面的代码给出了一个如何扩展当前方法来测试触摸是否在纹理区域内的例子,但我不建议在真正的游戏中使用它。作为一种理解发生了什么的练习,这是很好的,但随着游戏变得越来越复杂,以这种方式手动编码触摸区域将很快变得麻烦。我强烈建议您熟悉libGdx中的scene2d包。这个包有方法来处理所有常见的2D行为,如触摸事件,移动和碰撞。与许多libGdx库一样,如果您是初学者,那么文档可能很难理解,而且周围也没有很多教程。我建议你去看一下dermetfan的Java Game Development (LibGDX)系列youtube视频。在我刚开始工作的时候,它帮助我理解了很多领域。好运。

SpriteBatch batch;
Texture firstTexture;
Texture secondTexture;
float firstTextureX;
float firstTextureY;
float secondTextureX;
float secondTextureY;
float touchX;
float touchY;
@Override
public void create() {
    firstTexture= new Texture("texture1.png");
    firstTextureX = 50;
    firstTextureY = 50;
    secondTexture = new Texture("texture2.png");
    secondTextureX = 250;
    secondTextureY = 250;
    batch = new SpriteBatch();
}
@Override
public void render() {
    batch.begin; // begin the batch
    // draw our first texture
    batch.draw(firstTexture, firstTextureX, firstTextureY);
    // is the screen touched?
    if (Gdx.input.isTouched()) {
        // is the touch within the area of our first texture?
        if (touchX > firstTextureX && touchX < (firstTextureX + firstTexture.getWidth())
                && touchY > firstTextureY && touchY < (firstTextureY + firstTexture.getHeight()) {
            // the touch is within our first texture so we draw our second texture
            batch.draw(secondTexture, secondTextureX, secondTextureY);
    }
    batch.end; // end the batch
}

最新更新