Android Studio LibGDX问题与代码重复

问题描述:

我的游戏几乎完全工作,但是,我想为我的游戏创建一个无尽的水平,如Flappy Bird,这是添加敌人collisionList.add(new collisionEntity(world, collsionTexture, 6, 1));的代码,这是代码增加了地板groundList.add(new groundEntity(world, groundTexture, overgroundTexture,overground2Texture ,10, 10 ,18));我想这几行代码重复自己像一个循环,不翻来覆去添加它们,如Android Studio LibGDX问题与代码重复

`groundList.add(new groundEntity(world, groundTexture, overgroundTexture,overground2Texture ,10, 10 ,13));` 

    groundList.add(new groundEntity(world, groundTexture, overgroundTexture,overground2Texture ,25, 10 ,20)); 
    groundList.add(new groundEntity(world, groundTexture, overgroundTexture,overground2Texture ,10, 7 ,12)); 
    groundList.add(new groundEntity(world, groundTexture, overgroundTexture,overground2Texture ,10, 10 ,16)); 

我该怎么办呢?我的游戏结果是这样的https://www.youtube.com/watch?v=ql-Mr81fZ0U, Go to 2:23-2:31 minutes to see what I mean

我只是想让它增加障碍,并且一遍又一遍地重复自己,同样也与地面代码一致。

这完全取决于你想要什么,以及你希望事物排列或者随机化。如果你明白update()方法被称为每帧,你可以在其中有语句来检查什么时候你想“产生”一些东西。如果你不再需要它们,从列表中移除项目也很重要,这样垃圾收集器可以收集它们以释放内存。如果你使用一次性物品,你也应该处理这些物品。

一种方法可能是一个定时器,跟踪....是的,时间。当它达到某个特定时间时产生一些东西(添加到你的列表中)。一旦你的相机移过一个物体,你可以从列表中删除它。

float timer = 0; 
float spawnTime = 4; 
private void spawnEntity() 
{ 
    //Increment timer by the duration since the previous frame 
    timer += Gdx.graphics.getRawDeltaTime(); 
    //Compare to spawntime 
    if (timer >= spawnTime) 
    { 
     //Spawn your object 
     groundList.add(new groundEntity(world, groundTexture, overgroundTexture,overground2Texture ,25, 10 ,20));    
     //But you will probably want to spawn something on the right, just outside of your screen view. 

     //This is the right side of your vp in the world. Depending how you draw you can add some more to it. 
     float spawnX = camera.position.x + camera.viewportWidth/2; 
     //Then use this to spawn your object, since you hardcoded stuff I have no idea where to put it. 

     //Now reset timer 
     timer-= spawnTime; 

     //And perhaps randomize the spawnTime? (between 2 and 4 seconds) 
     spawnTime = random.nextFloat() * 2 + 2; 
    } 
} 

只需调用此更新循环即可。目前它将使用硬编码的数字添加。 groundList.add(new groundEntity(world, groundTexture, overgroundTexture,overground2Texture ,25, 10 ,20));因此,如果25,10或20处理定位,它将只覆盖实体。将float spawnX放在groundlist.add(...)的前面,并使用spawnX作为X定位。如果您有移动摄像头,它将从右侧进入。如果您还没有移动摄像头,请将这两行添加到您的更新中以进行测试。

camera.position.x += 1; 
camera.update();