3
votes

I am using libGDX java framework for developing a practice game in Eclipse.

My game is in landscape mode and I am using sprite image for game assets .Actually i am trying to follow the kilobolt ZombieBird tutorial

I have set orthographic camera like this -- >

   cam = new OrthographicCamera();
   cam.setToOrtho(true, 250, 120);

I have done this because my background texture region is of 250 x 120 px in the sprite image.

So basically my sprite image is small in size and it is getting scaled according to the device but all the computing is done relative to 250 x 140 px like for changing the position of the object i have defined Vector2 position = new Vector2(x, y); and if i write position.x = 260; the sprite will go outside the screen even if my device width is 500px .

Problem : Now i have to make the moving sprite vanish when someone clicks on it (just imagine zombies moving around and if i click on them they die) .So i am using the following code for matching user click co-ords with the object co-ords.

 int x1 = Gdx.input.getX();
 int y1 = Gdx.input.getY();
 if(position.x == x1 && position.y == y1){
      // do something that vanish the object clicked
  }

The problem is position.x and position.y returns the co-ords relative to the ortho cam width and height which is 250x120 px and the click co-ords are relative to the device width and height which maybe anything according to the device. Because of this even if i click right on the object the click co-ords and the object position co-ords have a huge difference in their values.So i would never get matching values .

Is there any solution for this or am i doing it wrong ?

2

2 Answers

6
votes

You have to unproject the device coordinates using the camera. The camera has a built in function to do this, so it's fairly simple. Furthermore, to determine if the sprite is clicked, you have to check to see if the point clicked is anywhere inside the sprite, not just equal to the sprite's position. Do something like this:

int x1 = Gdx.input.getX();
int y1 = Gdx.input.getY();
Vector3 input = new Vector3(x1, y1, 0);
cam.unproject(input);
//Now you can use input.x and input.y, as opposed to x1 and y1, to determine if the moving
//sprite has been clicked
if(sprite.getBoundingRectange().contains(input.x, input.y)) {
    //Do whatever you want to do with the sprite when clicked
}
0
votes

As an alternative to answer by kabb, you can just use math to convert screen co-ordinates to cam co-ordinates:

//Example:
float ScreenWidth = Gdx.graphics.getWidth(); 
float ScreenHeight = Gdx.graphics.getHeight();
// on a 1080p screen this would return ScreenWidth = 1080, ScreenHeight = 1920; 
//now you get the screen co-ordinates and convert them to cam co-ordinates:
float x1 = Gdx.input.getX();
float y1 = Gdx.input.getY();
float x1cam = (x1/ScreenWidth)*CamWidth
float y1cam = (y1/ScreenHeight)*CamHeight

// now you can use the if statement in kabbs answer