简体   繁体   中英

How to see if a texture is touched in libgdx?

pretty much i want my texture to move to a random position on the screen when its touched and when its missed i want to system.out("missed"). I cant figure out how to see if its touched. right now i can only get if the screen is touch and it records about 10 touches for every one touch because it renders so fast.

public void render(float delta) {
    Gdx.gl.glClearColor(0,1,0,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);   
    
    camera.update();

    game.batch.setProjectionMatrix(camera.combined);
    game.batch.begin();

    if(Gdx.input.isTouched()) {
        int randomX2 = (int)MathUtils.random(100,500);
        int randomY2 = (int)MathUtils.random(100,500);
        game.batch.draw(boxImage, randomX2, randomY2);
    }
    
    game.batch.end();
}

If randomX2 and randomY2 are your coordinates for the texture, you can check with this code:

Rectangle bounds = new Rectangle(randomX2, randomY2, boxImage.getWidth(), boxImage.getHeight());
Vector3 tmp = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(tmp);

if (bounds.contains(tmp.x, tmp.y)) {
    System.out.println("Is touched");
}

I could solve this without using Vector3.

var upArrowCircle = Circle(randomX, randomY, radius)
if(upArrowCircle.contains(Gdx.input.getX().toFloat(), Gdx.input.getY().toFloat()))
{
    Gdx.app.log("upArrow", "contains")
}

For me it works perfectly.

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