-1

I have one ArrayList with this :

ArrayList<Body> snakeBody = new ArrayList<Body>();
Body bodyOne = new Body();
bodyOne.setY(10);
bodyTwo.setX(10);

Body bodyTwo = new Body();
bodyTwo.setY(9);
bodyTwo.setX(10);

snakeBody.add(bodyOne);
snakeBody.add(bodyTwo);

Ok,not problem. When I move the snake ... she is moving to down ( increment Y ) ( Imagine a grid ). Remember , my snake have 2 bodies.

I know that the next moving, bodyOne-coorY would be 11 , and bodyTwo-Y would be 10 .

Here its my problem : How Can I interchange the values ? I don't know. Look this.

SnakeBody    Position    Y     X   
                0        10    10
                1         9    10

Now , the next moving. Y++

New value for Y its 11 

I want this result , but I can't get it.

Position    Y     X   
   0        11    10
   1        10    10

I'm doing this, but not work

        for ( int i = 0  ; i < snakeBody.size() - 1  ;  i++ ){

        y = snakeBody.get(i).getPositionY();
        x = snakeBody.get(i).getPositionX();

        snakeBody.get( i + 1 ).setPositionY(y);
        snakeBody.get( i + 1 ).setPositionX(x);

    }

The last value its same that the before last.

Thanks to all.

4

1 回答 1

0

我不确定我是否完全理解了你的问题,但是就这样吧。

如果您只是想增加每个身体的 Y 坐标,请尝试类似

for(int i = 0; i < snakeBody.size() - 1; i++)  {
    Body currentBody = snakeBody.get(i);
    currentBody.setPositionY(currentBody.getPositionY()+1);
    snakeBody.set(i, currentBody);
}

如果您尝试在snakeBody ArrayList 中交换bodyOne 和bodyTwo 的位置,那么其他问题可能会帮助他们提出类似的建议

Collections.swap(snakeBody, 0, 1);
于 2013-11-06T00:49:54.833 回答