0

I'm trying to make sprites act as buttons, so when a sprite is pressed, it performs an action. This is my code

        if(Gdx.input.justTouched())
    {
       int x = Gdx.input.getX();
       int y = Gdx.input.getY();

        spriteIterator = spriteArray.iterator();
        while(spriteIterator.hasNext()){
            Sprite cur = spriteIterator.next();
            if(cur.getBoundingRectangle().contains(x, y)) {
                System.out.println("Pressed button");
                //Change to collide message, and pause the game here
            }
        }

    }

It doesn't seem to work. Button press does register but in seemingly random places and times. What's the better way to go about this please?

Wayneio
  • 3,466
  • 7
  • 42
  • 73

2 Answers2

0

Are you using a camera in your app? Then you probably have to unproject(Vector3 vec) the touch positions to the coordinate system of your camera and scene. This might cause your problems.

Anyways, I would strongly recommend you to use scene2d, which is provided by libgdx. This way, you can create actors and buttons which work really well. For example, because they support a lot of different user actions.

To offer your users a good user experience, buttons shouldn't really react on a touch-down, rather when the player lifts the finger off the button. Also, it is possible, that a user clicks down on a button, then slides off it and lifts the finger somewhere else, to abort clicking on the button. So I'd definitely recommend of doing this differently.

Also, try using event-based touch handling so you don't have to check this every time...

Hope it helps... :)

florianbaethge
  • 2,520
  • 3
  • 22
  • 29
  • Thanks. I'll take a look. I'm not actually using a camera on this menu screen though. – Wayneio Mar 28 '14 at 07:07
  • @Wayneio you should definitly use camera, or if you are using the newest libgdx version use Viewport. It is easy to use and helps a lot – Robert P Mar 28 '14 at 07:36
0

See this question

Basically, you need to project or convert your screen touch position to the gameworld position

Community
  • 1
  • 1
Barodapride
  • 3,475
  • 4
  • 25
  • 36