libgdx向4个方向移动玩家

时间:2018-05-14 21:31:17

标签: android libgdx

当玩家触摸并拖动时,我想移动主角。问题是我无法向各个方向移动chacarter(向上,向下,向左,向右)。只有上下,或左右。但从来没有四个代码相同。

这是主要代码:InputProcessor。我认为问题出在touchDragged函数中。使用此代码,播放器仅向左移动:

public class UserTouchs implements InputProcessor {
int previousY = 0;
int previousX = 0;

private Charcter character;
private GameScreen screen;
private Vector2 stageCoord;

private Stage stage;

public UserTouchs(GameScreen screen) {

    this.screen = screen;
    character= screen.getCharacter();
    stage = screen.getStage();
}

public boolean keyDown (int keycode) {
    return false;
}

public boolean keyUp (int keycode) {
    return false;
}

public boolean keyTyped (char character) {
    return false;
}

public boolean touchDown (int x, int y, int pointer, int button) {
    previousY = y;

    stageCoord = stage.screenToStageCoordinates(new Vector2(x, y));
    Actor actorHit = stage.hit(stageCoord.x, stageCoord.y, true);
    if (actorHit != null)
        if(actorHit.getName()=="character"){

        }
    return true;
}

public boolean touchUp (int x, int y, int pointer, int button) {
    character.straight();
    return true;
}

public boolean touchDragged (int x, int y, int pointer) {
    if (previousY > y) {
        character.down();
    } else {
        character.up();
    }
    previousY = y;

    //This isn't working well
    if (previousX > x) {
        character.left();
    } else {
        character.right();
    }
    previousX = x;
    return true;
}

public boolean mouseMoved (int x, int y) {
    return false;
}

public boolean scrolled (int amount) {
    return false;
}

}

如果我删除了x(左和右),则播放器会正确上下移动。

    public boolean touchDragged (int x, int y, int pointer) {
    if (previousY > y) {
        character.down();
    } else {
        character.up();
    }
    previousY = y;
    return true;
}

有什么问题?

1 个答案:

答案 0 :(得分:0)

解决。问题是If else:

    public boolean touchDragged (int x, int y, int pointer) {
    // Si la Y es menor que la anterior Y, va hacia abajo
    if (previousY > y) {
        goku.down();
        //Si la Y es mayor que la que tenemos guardada, va hacia arriba
    } else if (previousY < y){
        goku.up();
        //Si la X es menos que la que tenemos guardada, vamos hacia la izquierda
    } else if (previousX > x){
        goku.left();
        //En caso contrario, el jugador va hacia la derecha
    } else {
        goku.right();
    }
    // Almacenamos ambas posiciones
    previousY = y;
    previousX = x;
    return true;
}