简体   繁体   中英

libgdx drawing sprite conditionally

I have these two textures

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

On click, I am checking a condition depending on which I will either draw the ballImage or spikeImage in relation to a rectangle (kept in an array). Like below,

 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);
            }
        }

Here's one of the spawn method (the other is similar),

 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);
    }

And the drawing in render is,

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

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

The problem:

In the touch event when isSpike() is false everything is fine and it draws the correct texture (balls) but when it is true then it is supposed to draw the spikeImage which it does, but for some reason a ballImage is drawn before that and spikeImage is drawn on top(overlap) of that. Why is it happening, what am I doing wrong.

I think you just have to delete camera.unproject(touchpos) .
Also, use events while getting input, like this:
1) Add implements InputProcessor on the begging of the class.
2) Add to your code:

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);

with @Override before the function.
3) Add return true; if you use the function or return false; .
4) Add Gdx.input.setInputProcessor(this);
Example:

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

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM