Libgdx Array<> how to get last item?

孤街浪徒 提交于 2019-12-25 16:56:40

问题


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.



来源:https://stackoverflow.com/questions/43877394/libgdx-array-how-to-get-last-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!