asker asker - 3 months ago 11
Java Question

Unable to use the same key press to connect/disconnect two squares

I want to make it so that when the square in my current class is adjacent (on the right) of the redSquare, I can press SPACE to connect the two squares and this square will follow the red one around whilst constantly being next to it.
Then pressing SPACE again would "disconnect" the two squares, meaning this square wont follow the redSquare around any more.
However, since SPACE is also used to connect the squares together, I think the code just keeps repeating, thus the squares never connect.

How do I use SPACE to connect and disconnect?

Boolean isConnected = false;
public void update() {
if (position.x - redSquare.position.x == 40 && position.y == redSquare.position.y) {
if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) {
isConnected = true;
}
}

if (isConnected) {
position.x = redSquare.position.x + 40;
position.y = redSquare.position.y;
if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
isConnected = false;
}
}
}


Also, as a side note, is there any resources you recommend to learn about these type of "logic" problems?

Answer

I would try this:

public void update() {
    if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) {
        if (isConnected) {
            isConnected = false;
        }
        else if (isConnectable(redSquare.position)) {
            isConnected = true;
        }
    }

    if (isConnected) {
        position.x = redSquare.position.x + 40;
        position.y = redSquare.position.y;
    }
}

private boolean isConnectable(Vector2 pos) {
    if (position.x - pos.x == 40 && position.y == pos.y)
        return true;
    return false;
}

No Need to check every cycle if the Position is 'connectable', just do it when SPACE is pressed. The Problem in your code is that you connect and disconnect in one cycle because the final connected-position is also the 'connectable' position