java - 在 libGdx 中用随机 vector 2填充数组

标签 java arrays libgdx

当我在测试两个明显相似的代码时遇到问题时,我试图用随机的 vector 2填充数组“stars”。

Array<Vector2> stars;
int numStars;

第一个代码

public void initStars() {

    int a = 100;
    int b = 120;
    numStars = (int) (a * b * 0.01f);
    stars = new Array<Vector2>(numStars);
    Random rand = new Random();
    Vector2 star = new Vector2();

    for (int i = 0 ;i <numStars ;i++){
        star.set(rand.nextInt(a),rand.nextInt(b));
        stars.add(star);           
    }
}

第二个代码

public void initStars() {

    int a = 100;
    int b = 120;
    numStars = (int) (a * b * 0.01f);
    stars = new Array<Vector2>(numStars);
    Random rand = new Random();

    for (int i = 0 ;i <numStars ;i++){
        Vector2 star = new Vector2();
        star.set(rand.nextInt(a),rand.nextInt(b));
        stars.add(star);           
    }
}

第一个不起作用,只需用循环中生成的最后一个随机 vector 填充数组即可,即。数组中的所有 vector 都相等,第二个 vector 工作得很好,我的问题是,如果两个代码显然是相等的,为什么会发生这种情况。

最佳答案

第一段代码不可能工作。仔细看看:

Vector2 star = new Vector2();

for (int i = 0 ;i <numStars ;i++){
    star.set(rand.nextInt(a),rand.nextInt(b));
    stars.add(star);           
}

您创建 vector 一次,然后不断为其分配新坐标,然后将其添加到集合中。当您调用 set() 时,您正在设置同一 vector 的值(因为您仍然引用同一 vector )。

结果是您将相同的 vector 存储在集合中 numStars 次,这正是您所注意到的。

也许为了更具体,您在第一个场景中创建的内容本质上是这样的:

stars = [starA, starA, starA, ..., starA]

第二个是这样的:

stars = [starA, starB, starC, ..., starZ]

如果您调用starA.set(),在第一种情况下,您不仅会修改要添加的星号,而且还会修改星号。您正在修改之前放入的每颗星星(因为它们是同一颗星星!)。

希望这有帮助。

关于java - 在 libGdx 中用随机 vector 2填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37352060/

相关文章:

java - 使用 Comparable 按 2 个字段比较两个对象 ASC 和 DESC

android - LibGDX - 限制透视相机的缩放

java - 如何在 LibGDX 中通过路径绘制自定义形状?

java - 按最低有效数字排序

java - 如何使用其他表中的列在 Liquibase 中创建索引?

Java通过反射访问私有(private)属性

java - 方法内可变数组长度

python - 如何使用 NumPy 数组实现字典?

javascript - 匹配返回 100 而不是实际值

java - libGDX - 在图像周围制作边框