放入List后,vector2的元素值被覆盖

时间:2016-10-26 12:52:28

标签: java

我知道这个问题看起来很愚蠢,我不知道我的代码有什么问题,我一直在想弄清楚它有什么问题但没有成功

当我将Vector2s放在List中时,Vector2s的元素值都被覆盖,但它可以在Arrays中正常工作。

   private Array<Float> generateBorderVertices() {

    Vector2[] _hillKeyPoints = generateTheHills();
    Array<Float> borderVertices = new Array<>();

    List<Vector2> vertices = new ArrayList<>();

    int kHillSegmentWidth = 10;

    for (int i = 1; i < kMaxHillKeyPoints; i++) {

        Vector2 p0 = _hillKeyPoints[i - 1];
        Vector2 p1 = _hillKeyPoints[i];
        int hSegments = (int) Math.floor((p1.x - p0.x) / kHillSegmentWidth);

        float dx = (p1.x - p0.x) / hSegments;
        float da = MathUtils.PI / hSegments;
        float ymid = (p0.y + p1.y) / 2;
        float ampl = (p0.y - p1.y) / 2;

        Vector2 pt0;
        Vector2 pt1 = new Vector2();
        pt0 = p0;
        borderVertices.add(pt0.x);
        borderVertices.add(pt0.y);
        vertices.add(pt0);
        for (int j = 0; j < hSegments + 1; ++j) {


            pt1.x = p0.x + j * dx;
            pt1.y = ymid + ampl * MathUtils.cos(da * j);

            //Using a List. here i put the Vector2s into a List
            vertices.add(pt1);
            //End

            //Using Array
            borderVertices.add(pt0.x);
            borderVertices.add(pt0.y);
            borderVertices.add(pt1.x);
            borderVertices.add(pt1.y);


            pt0 = pt1;
        }
    }
    //While accessing them, they are all floored ?!
    vertices.forEach(System.out::println);

    return borderVertices;
}

1 个答案:

答案 0 :(得分:0)

来自comments on this question

  

您正在循环中使用同一个Vector2实例,即您永远不会在循环中创建新实例。我想最后的pt1 = new Vector2()之类的东西应该可以工作(或者将行Vector2 pt1 = new Vector2();放在循环体的顶部)。 - 托马斯