2013-05-21 2 views
0

자바에서 작은 풍선 게임을 만들고 코드를 작성하려고합니다. 따라서 새로운 '풍선'객체를 만들 때 화면에서 겹치지 않게 만듭니다.절대 겹치지 않는 그래픽 객체 만들기 Java

내가 지금까지 가지고있는 코드는 다음과 같습니다

public void newGame(){ 
    UI.clearGraphics(); 
    this.currentScore = 0; 
    this.totalPopped = 0; 
    for (int i = 0; i < this.balloons.length-1; i++) { 
     this.balloons[i] = new Balloon(50 + Math.random()*400, 50 + Math.random()*400); 
     for (int j = i + 1; j < this.balloons.length; j++) { 
      if (this.balloons[i] !=null && this.balloons[j] != null && this.balloons[i].isTouching(balloons[j])) { 
       this.balloons[j] = new Balloon(50 + Math.random()*400, 50+ Math.random()*400); 
      } 
     } 
     this.balloons[i].draw(); 
    } 
    UI.printMessage("New game: click on a balloon. High score = "+this.highScore); 
} 

은 무 isTouching 방법 사용 :

public void draw(){ 
    UI.setColor(color); 
    UI.fillOval(centerX-radius, centerY-radius, radius*2, radius*2); 
    if (!this.popped){ 
     UI.setColor(Color.black); 
     UI.drawOval(centerX-radius, centerY-radius, radius*2, radius*2); 
    } 
} 

    /** Returns true if this Balloon is touching the other balloon, and false otherwise 
* Returns false if either balloon is popped. */ 
public boolean isTouching(Balloon other){ 
    if (this.popped || other.popped) return false; 
    double dx = other.centerX - this.centerX; 
    double dy = other.centerY - this.centerY; 
    double dist = other.radius + this.radius; 
    return (Math.hypot(dx,dy) < dist); 
} 

어떻게 풍선을 만들 때 그래서 나는, 그들 중 누구도 이것을 쓸 수 없습니다 서로 만지고 있니?

+1

당신은 간단히 ballon의 경계 Rectangle을 계산하고 intersects 메서드를 사용하여 겹치기를 결정할 수 있습니다. – MadProgrammer

답변

1

바로 지금 두 개의 루프가 있습니다. 첫 번째 루프에서 풍선이 만들어집니다. 두 번째 루프에서는 모든 풍선이 모든 다른 루프에 대해 테스트됩니다. 첫 번째 루프에서이 테스트를 수행하십시오. 새 풍선을 작성한 후 이미 존재하는 모든 풍선에 대해 테스트하십시오.

+0

생각했지만 작동하지 않을 것이라고 생각했습니다. 어떻게하면 루프의 첫 번째 반복 코드를 작성할 수 있습니까? 하나의 풍선 만 만들었습니까? –

+0

하나의 품번 기호 만 작성된 경우 다른 품번 기호를 테스트 할 수 없습니다. 그래서 간단한'if' 절이이 경우를 처리해야합니다. –

+0

null을 확인하기 위해 if 문을 사용해야한다고 생각합니다. 맞습니까? –