-1

我目前正在硬编码 10 个不同的实例,如下面的代码,但我想创建更多。我想知道是否可以为每个块生成一个随机 X 值,而不是为新关卡设置相同的布局(这将是它进入关卡的距离)。一个 100,000 像素宽的关卡就足够了,但如果有人知道一个系统可以让关卡继续下去,我也想知道。这基本上就是我现在定义块的方式(删除了不相关的代码):

block = new Block(R.drawable.block, 400, platformheight);
block2 = new Block(R.drawable.block, 600, platformheight);
block3 = new Block(R.drawable.block, 750, platformheight);

400是 X 位置,我想在关卡中随机放置,platformheight变量定义了我不想更改的 Y 位置。

4

1 回答 1

1

考虑到每个块都需要比前一个块更远,

List<Block> blocks = new LinkedList<Block>();
Random rnd = new Random(System.currentTimeMillis());

int x = 400;

while (youNeedMoreBlocks)
{
    int offset = rnd.nextInt(400) + 100; //500 is the maximum offset, this is a constant
    x += offset;                         //ofset will be between 100 and 400

    blocks.add(new Block(R.drawable.block, x, platformheight));

    //if you have enough blocks, set youNeedMoreBlocks to false
}

但这在我看来过于简单。要么我不明白你的问题,要么实际上就是这么简单。

编辑:

对于这样的任务:

block.setY(three_quarters - 10); 
block2.setY(three_quarters - 10); 
block3.setY(three_quarters - 10);

您需要修改循环:

List<Block> blocks = new LinkedList<Block>();
Random rnd = new Random(System.currentTimeMillis());

int x = 400;

while (youNeedMoreBlocks)
{
    int offset = rnd.nextInt(400) + 100; //500 is the maximum offset, this is a constant
    x += offset;                         //ofset will be between 100 and 400

    Block tmp = new Block(R.drawable.block, x, platformheight);
    tmp.setY(three_quarters - 10);                 
            //do with tmp everything you need to apply to each block

    blocks.add(tmp);

    //if you have enough blocks, set youNeedMoreBlocks to false
}

另一个明智的想法是在玩家靠近地图边缘时按需生成块,这样你的加载时间就会更快。

于 2012-04-09T22:12:09.187 回答