Search code examples
javaandroidlibgdx

Coordinates off when using FitViewport


Im currently programming on a little Game where you have to avoid Asteroids with a Spaceship. To keep the Game look same on every device im using a FitViewport. Unfortunately by using the Viewports my Coordinates are getting a bit off when resizing. First have a look at the Class Diagramm for a better overall look.

enter image description here

(Class Diagramm was created using ObjectAid)

To fix this I need to implement the viewport.unproject() method in the update() method in the Spaceship class. Spaceship Class:

public void update() 
{

    if (Gdx.input.isTouched()) 
    {

        y = MyGdxGame.HEIGHT -  Gdx.input.getY();
        x = Gdx.input.getX();
         sprite.setPosition(x, y); 

    }
}

The Viewport is only avalible in the GameScreenClass, so i cant just write in the update method. The GameScreen looks like this:

 @Override
 public void render(SpriteBatch batch) 
 {
     // TODO Auto-generated method stub

    cam.update();
    batch.setProjectionMatrix(cam.combined);
    batch.begin();
    em.render(batch);
    [...]

 }

I dont want to have the hole Code in the GameScreenClass. I tried creating an update Method with a Viewport parameter but I just got a white screen. Is there another way how I could fix this issue? Here you can have a complete look over my Project. (https://github.com/Zui0per/SpaceAvoiding/tree/master/tmp)

Thanks in Advance!


Solution

  • The solution is probably to unproject touch coordinates in your main class and pass in the unprojected x and y as parameters to your various update() methods. For example in Spaceship:

    public void update(float unprojectedX, float unprojectedY) {
        if (Gdx.input.isTouched()) {
             sprite.setPosition(unprojectedX, unprojectedY); 
        }
    }
    

    It's hard to follow your code, since you have multiple render and unproject methods in each class, but you would need to unproject the touch coordinates and pass them into the EntityManager.update() method, and it could pass those along to its children.