【问题标题】:libgdx drawing sprite conditionallylibgdx 有条件地绘制精灵
【发布时间】:2015-11-08 13:56:50
【问题描述】:

我有这两个纹理

ballImage = new Texture(Gdx.files.internal("ball.png"));
spikeImage = new Texture(Gdx.files.internal("spike.png"));

点击时,我正在检查一个条件,这取决于我将绘制与矩形相关的 ballImage 或 peakImage(保存在数组中)。如下所示,

 if (Gdx.input.isTouched()) {
            Vector3 touchPos = new Vector3();
            touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
            camera.unproject(touchPos);
            if (isSpike()) {
                spawnSpike(touchPos);
            } else {
                spawnBalls(touchPos);
            }
        }

这里有一个spawn方法(另一个类似),

 private void spawnSpike(Vector3 touchPos) {
        Spike spike = new Spike();
        spike.setRectX((int) touchPos.x);
        spike.setRectY((int) touchPos.y);
        spike.setRectWidth(64);
        spike.setRectHeight(48);
        spikes.add(spike);
    }

渲染中的绘图是,

for (Ball ball : balls) {
            game.batch.draw(ballImage, ball.getRectX(), ball.getRectY());
        }

        for (Spike spike : spikes) {
            game.batch.draw(spikeImage, spike.getRectX(), spike.getRectY());
        }

问题:

在触摸事件中,当 isSpike() 为假时,一切都很好,它绘制了正确的纹理(球),但当它为真时,它应该绘制它所做的尖峰图像,但由于某种原因,绘制了一个球图像在此之前,spikeImage 被绘制在其顶部(重叠)。为什么会这样,我做错了什么。

【问题讨论】:

  • 在我看来,您在未显示的部分代码中一定犯了某种错误。可能是一些有缺陷的逻辑。一个球要么在其他地方产生,要么你的 isSpike() 方法有一个错误,导致它在返回 true 之前返回 false,从而产生一个球。

标签: java opengl libgdx


【解决方案1】:

我认为你只需删除camera.unproject(touchpos)
此外,在获取输入时使用事件,如下所示:
1) 求班级加implements InputProcessor
2) 添加到您的代码中:

public boolean keyDown (int keycode);
public boolean keyUp (int keycode);
public boolean keyTyped (char character);
public boolean touchDown (int screenX, int screenY, int pointer, int button);
public boolean touchUp (int screenX, int screenY, int pointer, int button);
public boolean touchDragged (int screenX, int screenY, int pointer);
public boolean mouseMoved (int screenX, int screenY);
public boolean scrolled (int amount);

在函数前加上@Override
3) 如果您使用该功能,请添加return true;return false;
4) 添加Gdx.input.setInputProcessor(this);
示例:

@Override
public boolean keyDown(int keycode){
    if(keycode == Input.Keys.A){
         player.moveBy(-10, 0);
    }
    return true;
}

祝你好运!

【讨论】: