1

I'm making a libgdx game as an exercise. Its pretty simple, something like "escape" kind of game. Just screens with background, some items and go left/right arrows.

As libgdx makes everything easy, I was wandering if there is an easy method of handling actions. Now its just a bunch of "if else" statements in onClick() method. Now its fine, but with tens or houndreds of items it will be messy and probably laggy when clicked.

public void onClick(int scrX, int scrY){
    pX = (scrX/viewW)*WORLD_W;
    pY = (scrY/viewH)*WORLD_H;
    if (pX > 10 && pX < 20 && pY > 10 && pY < 20) {
        if (stage.getInfo().getLeft() == true) {
            Gdx.app.log("Click", "Left");
            stage = new StageGame(stage.getInfo().getLeftStage());
        }
    }
    else if(pX > 80 && pX < 90 && pY > 10 && pY < 20) {
        if (stage.getInfo().getRight() == true) {
            Gdx.app.log("Click", "Right");
            stage = new StageGame(stage.getInfo().getRightStage());
        }
    }
}

I was thinking about switch here, but i would still have to use some conditions. Other idea was a matrix, lets say 100x100. With every stage it would be read from file. After click x and y would be easly translated into grid values and proper action would happen. But thats good only for static game, and not shure about memory usage, and handling that matrix.

I'm pretty shure thats all wrong but i cant find something that i cant name :P Help pls!

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
gonnog
  • 15
  • 3
  • Matrix of screen objects is not a bad idea if you are sure that you'll have exactly MxN matrix. Other way, maybe a list, to make it more flixibile. List of lists actually. Also, I didn't use it, but libGDX has some map feature, so check it out - maybe you can use that. – MilanG Apr 01 '15 at 11:31

1 Answers1

0

I think you can use the Libgdx Actors infrastructure (aka Scene2d) to help organize your on-screen elements. The Actors can have a location on the screen, and their own onClick handlers. Libgdx will take care of figuring out which Actor has been clicked and will invoke its handler. See When to use actors in libgdx? What are cons and pros? and https://github.com/libgdx/libgdx/wiki/Scene2d

As an aside, you don't really need to worry about the performance of the click detection unless you have 1000s of objects on screen (and then you have other problems). I would be much more worried about making the code maintainable and debuggable at this point.

Community
  • 1
  • 1
P.T.
  • 24,557
  • 7
  • 64
  • 95