LibGDX,存储多个不同精灵位置的最佳方法

时间:2020-04-15 17:13:49

标签: libgdx

因此,我目前正在创建一个小型游戏,在一个场景中包含25个精灵。 1个精灵是玩家,其余的是敌人精灵。

我要做的是将24个敌方精灵的位置设置为自己的独特区域。只需执行sprite.setPosition(x,y)即可轻松完成,但这意味着我将不得不编写24个不同的setPosition语句。

我所有的子画面都存储在ArrayList中,这将24个子画面添加到列表中,然后在render()方法中渲染了24次。目前,所有24个精灵都以0,0渲染。

是否有一种更简单,更有效的方法来设置每个精灵的位置,然后可以将其更新为与deltatime一起使用以移动精灵。

1 个答案:

答案 0 :(得分:0)

您可以将每个子画面存储在一个数组中,然后在遍历所有敌方子画面时,将所有子画面的位置设置为在扩展圆半径上的某个随机位置:

...
private Sprite[] enemies;
...
public void positionSprites() {
    for(int i = 0; i < enemies.length; i++) {
        //Gets the enemy from the array.
        Sprite enemy = enemies[i];
        //Generates a random angle between 0 and 2pi in radians to move the sprite to.
        double randAngle = 2 * Math.PI * Math.random();
        //Calculates the radius of the circle to be the (iteration count + 1) * the diagonal size of the sprites to prevent them from overlapping.
        double radius = (i + 1) * Math.sqrt(Math.pow(enemy.getWidth(), 2) + Math.pow(enemy.getHeight(), 2));
        //Calculates the position the enemy at the random angle along the circle.
        float x = (float) radius * Math.cos(angle), y = (float) radius * Math.sin(angle);
        //Sets the enemy position to the new position.
        enemy.setPosition(x, y);
    }
} 
相关问题