3
\$\begingroup\$

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 Zombie Bird 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 coords with the object coords:

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 coords relative to the ortho cam width and height which is 250 x 120 px and the click coords 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 coords and the object position coords 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?

\$\endgroup\$
5
\$\begingroup\$

Before using the coordinates of your touch event, you need to scale them to your camera dimentions. You can try this code :

OrthographicCamera cam;
Sprite sprite;    // your sprite
Vector3 touchPos; // creates a vector3 object for our touch event

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

public void render(float delta) { // you need to put it into the main loop
        if (Gdx.input.isTouched()) {
         touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0); //when the screen is touched, the coordinates are inserted into the vector
         cam.unproject(touchPos); // calibrates the input to your camera's dimentions
                 if (touchPos.x > sprite.getX() && touchPos.x < sprite.getX() + sprite.getWidth()) { 
                          if (touchPos.y > sprite.getY() && touchPos.getY() < sprite.getY() + sprite.getHeight()) {
                                //clicked on sprite
                               // do something that vanish the object clicked 
              }
             }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.