简体   繁体   中英

How do I detect if the user touched my Sprites/screen?

Basically, the sprite is spawned at a random time every (1,2 or 3 sec) and infinitely. I want the sprite to disappear once it's touched on the screen. (android touch event)

public void newEnemy(){
        Sprite newEnemy=Pools.obtain(Sprite.class);
        newEnemy.set(enemy);
        newEnemy.setPosition(200, 700);
        enemies.add(newEnemy);
    }

public void update(){
        deltaTime=Gdx.graphics.getDeltaTime();
        timer+=1*deltaTime;
        timer2+=1*deltaTime;
        timer3+=1*deltaTime;

        if(timer>=random){
            newEnemy();  //spawn a new enemy
            timer-=random;
            random=rTime.nextInt(3)*1f+1;//create random time if timer>= initial random time;
        }

You will need to set up a touch listener. Information on that here

You will then need to check if the touch location is within your sprite bounds. A common way to do this would be to create a rectangle and check if the touch location is inside of the rectangle like this

 Rectangle2D bounds = new Rectangle2D.Float(x, y, width, height);

`if(bounds.contains(`the touch x value`,` the touch y value`){`

         //your code to remove the sprite
    }

Alternately you could write your own method in sprite, this would be a better decision if all you needed was the contains method. That way, you don't have to import another library. (Note that it doesn't make much of a difference but it's good practice)

public boolean contains(int x, int y) {
     return (x > this.x && y > this.y && x < this.x + this.width && y < this.y + this.height);
}

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