2014-07-11 2 views
2

내가 틀렸다면 나를 바로 잡습니다. 나는 Java에 익숙하지 않고 lwjgl을 사용하여 간단한 물리 엔진을 만들려고 노력 중이다. 현재 코드가 좀 지저분하지만, 올바르게 시작되고 올바르게 작동하며 물리학이 완벽하게 작동합니다. 사용자가 마우스를 클릭하여 physics_object를 추가 할 수있는 방법을 생각하려고합니다. 현재는 가능하지만 한계가 있기 때문에 모든 객체 이름을 코딩해야합니다. phys_square 클래스자바에 많은 객체 추가하기

phys_square rec1 = new phys_square(100, 100, 10.0f, -1.0f, 10, 0.0f, 0.5f, 0.0f); 

및 코드 :

package quad; 
import org.lwjgl.LWJGLException; 
import org.lwjgl.input.Keyboard; 
import org.lwjgl.input.Mouse; 
import org.lwjgl.opengl.Display; 
import org.lwjgl.opengl.DisplayMode; 
import org.lwjgl.opengl.GL11; 

public class phys_square { 

float velocityY; 
float velocityX; 
int x; 
int y; 
int particleSize; 
float red; 
float green; 
float blue; 
public phys_square(int xpos, int ypos, float velocity_x, float velocity_y, int size, float red, float green, float blue) { this.x = xpos; this.y = ypos; this.velocityY = velocity_y; this.velocityX = velocity_x; this.particleSize = size; this.red = red; this.green = green; this.blue = blue;} 
public void updatePos() { 
    if (this.y == 0 | this.y < 0) { 
     this.velocityY *= -0.825f; 
    } 
    if (this.y > 0 | this.y >= this.velocityY) { 
     this.y -= this.velocityY; 
     this.velocityY += 0.2f; 
    } 

    if (this.x <= 0 | this.x + quad_main.particleSize >= 800) { 
     this.velocityX *= -0.5f; 
    } 
    if (this.x > 0 | this.x >= this.velocityX) { 
     this.x -= this.velocityX; 
     if (Math.abs(this.velocityX) <= 0){ 
      this.velocityX -= 0.2f; 
     } 
    } 
    if (this.x < 0) { 
     this.x = 0; 
    } 
    if (this.x > 800 + quad_main.particleSize) { 
     this.x = 800 + quad_main.particleSize; 
    } 
    if (this.y < 0){ 
     this.y = 0; 
    } 
} 
public void render() { 
    window.particle(this.x, this.y, this.red, this.green, this.blue, this.particleSize); 
} 
public static void main(String[] args[]){ 

} 
} 

수동으로 모든 이름을 지정하지 않고 여러 개체를 만들 수있는 방법이 있나요

물리학 객체를 추가? 나는 PHP와 다른 언어들에서 문자열의 값을 다른 언어의 이름으로 사용할 수 있다고 들었다.

답변

2

참고 :이 대답은 런타임에 이름을 만들지 않고 이름을 전혀 필요로하지 않는다고 가정합니다. 이를 위해 해시 맵을 사용하십시오.

ArrayList과 같은 목록에 개체를 저장할 수 있습니다. 이것은 객체의 배열처럼 작동하지만 크기를 조정할 수 있으며 자유롭게 추가하고 색인을 사용하여 액세스하며 반복 할 수 있습니다.


당신의 수입에 이것을 넣어 :

import java.util.ArrayList; 

다음 코드는 생성하여 ArrayList :

squaresList.add(new phys_square(/* paramenters here */)); 
:이처럼 ArrayList에 객체를 추가 할 수 있습니다

ArrayList<phys_square> squaresList = new ArrayList<phys_square>(); 

개체를 처리하려면 목록을 반복 할 수 있습니다. 다음 코드는 목록의 모든 요소에 대해 메서드를 실행합니다.

for (phys_square sq : squaresList) { 
    processPhysicsStuff(sq); 
    processGraphicsStuff(sq); 
} 

당신은 Arraylisthere에 대한 문서를 볼 수 있습니다. 읽기, 그것은 매우 유용한 수업입니다.