【问题标题】:LibGDX, best way to store multiple different sprite positionsLibGDX,存储多个不同精灵位置的最佳方式
【发布时间】:2020-07-28 18:30:06
【问题描述】:

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

我要做的是将 24 个敌方精灵的位置设置到它们自己独特的区域。这可以通过简单地执行sprite.setPosition(x,y) 轻松完成,但这意味着我必须编写 24 条不同的setPosition 语句。

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

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

【问题讨论】:

    标签: libgdx


    【解决方案1】:

    您可以将每个精灵存储在一个数组中,然后在遍历所有敌人精灵时简单地将所有精灵的位置设置在一个扩大的圆的半径上的某个随机位置上:

    ...
    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);
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多