Search code examples
javaandroidlibgdxandroid-studio-3.0pong

LIBGDX - How to make the paddle not jumping in pong game?


I am making a Pong game and when I click on the screen the paddle jump to my cursor point. I want that I need to drag the cursor to move him and without jumping like normal Pong game. how can I do this?

This is my Paddle class:

public class Paddle {

private Vector3 position;
private int width, height;
private Texture texture;

public Paddle(int x, int y, int width, int height){
    this.width = width;
    this.height = height;
    createTexture(width,height);
    position = new Vector3(x, y, 0);
}

private void createTexture(int width, int height) {
    Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
    pixmap.setColor(Color.BLACK);
    pixmap.fillRectangle(0, 0, width, height);
    texture = new Texture(pixmap);
    pixmap.dispose();
}

public void update(int y){
    position.add(0, y - position.y,0);
    position.y = y;
    position.set(position.x, HeadGuns.HEIGHT - position.y, position.z);
}

public void draw(SpriteBatch sb){
    sb.draw(texture, position.x, position.y, width,height);
}

This is my PlayState class:

public class PlayState extends State {

private Paddle myPaddle;

public PlayState(GameStateManager gsm) {
    super(gsm);
    myPaddle = new Paddle(25, HeadGuns.HEIGHT/2, 25, 150);
}

@Override
public void handleInput() {
    if (Gdx.input.isTouched()){
        //when I touched the screen
        myPaddle.update(Gdx.input.getY());
    }
}

@Override
public void update(float dt) {
    handleInput();
}

@Override
public void render(SpriteBatch sb) {
    sb.begin();
    myPaddle.draw(sb);
    sb.end();
}

@Override
public void dispose() {

}

Solution

  • You are reading touch position:

    Gdx.input.getY()

    and using it directly to set pad position - you can't do that.

    You should use InputLister to get events.

    First you should listen to touchDown and see is user touching your pad or not (compare touch coordinates with pad coordinates)

    Then, for dragging you should use touchDragged() event...to update pad position when dragging happen, but only if touchDown detected that touch:

    https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/InputListener.html#touchDragged-com.badlogic.gdx.scenes.scene2d.InputEvent-float-float-int-