1
votes

im currently programming on a Menu Screen for my Game. Im trying to create a Rectangle that checks if the Sprite Button is touched . Im using Abitrary World Coordinates public static int WIDTH = 1080 , HEIGHT = 720;

    public void create() {

    cam = new OrthoCamera();
    cam.resize();

    texture = new Texture("Button.png");

    texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    TextureRegion region = new TextureRegion(texture, 59, 52, 300,250);

    sprite = new Sprite(region);
    sprite.setSize(sprite.getWidth()  , sprite.getHeight()  )
    sprite.setPosition(MyGdxGame.WIDTH / 2, MyGdxGame.HEIGHT / 2);

}

I'm using a special Orthographic Camera, if u want to see the both relevant classes klick here. (Not my Project)

    public void update(OrthoCamera cam) {

    if(Gdx.input.isTouched())
     {

       Vector3 tmp = new Vector3( Gdx.input.getX(), Gdx.input.getY(), 0);
       cam.unproject(tmp);

       Rectangle textureBounds = new Rectangle(0,0, 300, 250); //origin at center ?!



      if(textureBounds.contains(tmp.x,tmp.y))
          {

          //ScreenManager.setScreen(new GameScreen());
            System.out.println("Rectangle")          
          } 
     }

     }   

Trough testing i regognized that somehow the origin of the Rectangle Coordinate System is at the center and the width and height is set far to high. Here you can see a picture of the area where i get printet out "Rectangle" by clicking. Normaly the the origin of the Rectangle shoud be at the bottom left, right?

enter image description here

2
That OrthoCamera class is an abomination. :) It has parameters duplicated from the superclass and mixes and matches those with the superclass's in some needlessly overridden methods. That VirtualViewport class also looks quite convoluted. Your problem probably has to do with the overridden class not carefully implementing the superclass's methods. That VirtualViewport class is also pretty convoluted. You should use the built in Libgdx ExtendViewport class instead, with a plain OrthographicCamera.Tenfour04

2 Answers

0
votes

I would highly recommony you to use for example Scene2d. It makes it easy to create a user interface for your app.

With that you could use the ImageButton and attach a ClickListener to it, to get a callback when to button is clicked.

0
votes

To solve the issue of the not centered coordinate system, you have to set the camera to the right position.

You can do this by using the following code:

camera.setOrtho(false);
camera.position.set(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2);
camera.update();