Libgdx Array<> how to get last item?

2019-09-14 17:39发布

问题:

I want to change Y position of "bucket", when camera Y position is higher than "last created bucket" Y position: There is my code in "create()" method

buckets = new Array<Bucket>();
for(int i=1;i<BUCKET_COUNT;i++){
    buckets.add(new Bucket(world,(rand.nextInt((int)W)-45)/PPM,BUCKET_MARGIN*i/PPM));
}

And I am doing like this in "render()" method:

for(Bucket bucket : buckets){
    if(cam.position.y > buckets.peek().getBody().getPosition().y){
        bucket.repos(rand.nextInt((int)W)/PPM,buckets.size+BUCKET_MARGIN/PPM);
    }
}

repos():

public void repos(float x, float y){
    setPosition(x, y);//Bucket class is extends Sprite
}

But it doesn't work and I don't know how to solve this problem

I want to know how to get last item from those array?

回答1:

You should try this,

if(cam.position.y > buckets.peek().getPosition().y){
     for(Bucket bucket : buckets){
        bucket.repos(rand.nextInt((int)W)/PPM,buckets.size+BUCKET_MARGIN/PPM);
    }
}

In this y position of buckets are not properly specified because according to your code all bucket set to particular y position.

EDIT

if(cam.position.y > buckets.peek().getPosition().y){
    for(Bucket bucket : buckets){
            bucket.repos(rand.nextInt((int)W)/PPM,cam.position.y+bucket.getPositon().y);
    }
}

EDIT 2

Take a look of this tutorial, I think it may be helpful for you.