Question

basically I am making a game using LibGdx that will involve a ball and ground. The objective is to keep the ball in the air as long as possible by touching it.

So far I have only used box2d and not put any sprites over the shapes. But I cant seem to get the touch working correctly.

Here's what I have so far in regards to this feature:

This is setting up a class that extends the Input processor as I only want to use the touchDown method.

    Gdx.input.setInputProcessor(new InputController(){
        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button){
            if((screenX == ball.getPosition().x) && (screenY == ball.getPosition().y)){
                movement.y = speed;                 
            }
            return true;                
        }

    });

Ball is a body which is set to the world of the ball shape. Speed is a float variable. I then have

    ball.applyForceToCenter(movement, true);

In the render method movement is a vector 2 which is not defined until the touch where it should increase the y position by 500.

Could anyone help as this didn't work :(

Was it helpful?

Solution

Your first issue is that you're testing to see if the point clicked is exactly the position of the ball. This is highly unlikely, and almost certainly not what you want. Instead, you want to test to see if the point clicked hits anywhere in the ball.

Your second issue is that you need to transform your device coordinates to box2d coordinates. The device and box2d use different coordinate systems, so comparing the two doesn't make sense.

To solve the first issue, you can loop through all of the fixtures in the body and use the method fixture.testPoint(x, y) to see if the point hits the fixture. Since your body only has one fixture, you can just use this code for the test:

body.getFixtureList().get(0).testPoint(x, y);

Solving the second issue is a bit trickier. Ideally, your game should be using a camera to handle rendering. If it doesn't, you should get one. With the camera, you can unproject the device coordinates to get camera coordinates like this:

Vector3 mouseCoords = new Vector3(screenX, screenY, 0);
camera.unproject(mouseCoords);
//mouseCoords.x and mouseCoords.y will now be relative to the camera

Then, you have to convert to box2d coordinates:

mouseCoords.scl(WORLD_TO_BOX);

where WORLD_TO_BOX is the scaling from world coordinates to box coordinates, which you should already have setup. You can then use mouseCoords.x and mouseCoords.y in the testPoint method.

EDIT: Code below shows how to loop through all fixtures in a body. This isn't necessary if you only have one fixture, however.

for(Fixture fixture : body.getFixtureList())
{
    //Do something to fixture
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top