0
\$\begingroup\$

I am working on a landscape java game.

I have a sprite array like this;

Sprite stickArray[] = new Sprite[10];

and initializing it like this with visibility as false.

for (int j = 0; j < stickArray.length; j++) {

        if (stickArray[j] != null) {

            stickArray[j].setPosition(stickX, stickY);
            stickArray[j].setVisible(false);
        }
    }

Later I want to position it like one after another vertically on repeating a key.pressBool is false initially.

public void keyRepeatInGame(int keyCode) {
    int gameKey = getGameAction(keyCode);
    Graphics g = getGraphics();
    if (gameKey == FIRE || keyCode == KEY_NUM5) {
        pressBool = true;
    }
}

Later I have written code like this; Initially one Sticksprite is there.above this sprite, I want to place each sticks on clalling keyrepeat()in space key.

for (int i = 0; i < stickArray.length; i++) {
            if (pressBool) {
                if (i == 0) {
                    stickArray[i].setPosition(stickSprite.getX(),
                            stickSprite.getY() - stickSprite.getHeight());
                    stickArray[i].setVisible(true);
                } else {
                    stickArray[i].setPosition(stickArray[i-1].getX(),
                            stickArray[i-1].getY() - stickArray[i].getHeight());
                    stickArray[i].setVisible(true);
                }
            }
        }

This code is working partially.Stick is getting added on the sprite,all at once.

How can I change the code to make the sticks repeatedly getting added on calling keyrepeat() only, and make it visible one by one properly?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

It is adding all of them because you are saying so by doing a loop on all your sticks and setting them as visible. All of them.

What you might want to do is something like this :

int index = 0;

while (gameLoopOngoing)
{
    pressBool = checkForKeyPressed();
    if (pressBool)
    {
         if (index < stickArray.length)
              stickArray[index].setVisible(true); // Too lazy to write positionning too but you get the point
         index++;
    }
    pressBool = false;
}

I am putting pressBool at false in the end to force a key press again but that may not be working depending on the way you get the input.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .