2017-10-05 121 views
-2

我試圖編寫一個應該創建圓柱體的類。但是當我嘗試繪製我的ArrayList時,有180個對象具有相同的值。當我嘗試添加四邊形到我的ArrayList時,我不明白那裏有什麼問題。將元素添加到ArrayList中

public class Planet { 
    public static ArrayList<Quad> createRing(int x, int y, int z, int radius) { 
     ArrayList<Quad> quads = new ArrayList<Quad>(); 
     for (int i = 0; i < 360; i++) { 
      float x1 = (float) (Math.sin(Math.toRadians(i)) * radius); 
      float y1 = (float) (Math.cos(Math.toRadians(i)) * radius); 
      i++; 
      float x2 = (float) (Math.sin(Math.toRadians(i)) * radius); 
      float y2 = (float) (Math.cos(Math.toRadians(i)) * radius); 

      quads.add(new Quad(new Vector3f(x1, y1, 4), new Vector3f(x2, y2, 4), new Vector3f(x2, y2, 0), 
        new Vector3f(x1, y1, 0))); 
     } 
     return quads; 
    } 
} 

----QUAD.java 

import org.lwjgl.opengl.GL11; 
import org.lwjgl.util.vector.Vector3f; 

public class Quad { 
//have to be non-static 
static Vector3f Cord1; 
static Vector3f Cord2; 
static Vector3f Cord3; 
static Vector3f Cord4; 
//have to be non-static 
public Quad(Vector3f cord1,Vector3f cord2,Vector3f cord3,Vector3f cord4) { 
Cord1 = cord1; 
Cord2 = cord2; 
Cord3 = cord3; 
Cord4 = cord4; 
} 
public void draw() { 
//GL11.glBegin(GL11.GL_QUADS); 
GL11.glColor3f(1, 0, 0); 
GL11.glVertex3f(Cord1.x, Cord1.y, Cord1.z); 
GL11.glVertex3f(Cord2.x, Cord2.y, Cord2.z); 
GL11.glVertex3f(Cord3.x, Cord3.y, Cord3.z); 
GL11.glVertex3f(Cord4.x, Cord4.y, Cord4.z); 
} 
public void out() { 

System.out.println(Cord1.x+" "+ Cord1.y+" "+ Cord1.z); 
System.out.println(Cord2.x+" "+ Cord2.y+" "+ Cord2.z); 
System.out.println(Cord3.x+" "+ Cord3.y+" "+ Cord3.z); 
System.out.println(Cord4.x+" "+ Cord4.y+" "+ Cord4.z); 
} 
} 
+0

你試過'System.out.println(eins); System.out.println(zwei);'等,並檢查它們是否相同?你確定每次都分配不同的值嗎? –

+1

我通過更改for循環中的值來測試該值,並且每次繪製時我都會獲得另一部分圓柱體。但我不能一下子抽出整個缸。 –

+0

「Quad」是你定義的類嗎?它的成員是否是「靜態」?請添加該類的代碼。 (如果它們是靜態的,則使它們不是靜態的)。 –

回答

0
public class Quad { 
static Vector3f Cord1; 
static Vector3f Cord2; 
static Vector3f Cord3; 
static Vector3f Cord4; 
public Quad(Vector3f cord1,Vector3f cord2,Vector3f cord3,Vector3f cord4) { 
Cord1 = cord1; 
Cord2 = cord2; 
Cord3 = cord3; 
Cord4 = cord4; 
} 

所做的CordN變量static,所以每場剛剛值爲1,該類的所有實例之間共享。因此,每次創建類的新實例時,以前的值都會被覆蓋。

刪除static修飾符。


另外請注意,這是很好的做法,使成員變量final除非你絕對需要他們不要。這似乎並不是這種情況,因此請將它們設爲final - 並且這會自動引發您的問題,因爲您無法在構造函數中重新指派static final字段。

相關問題