2016-09-20 1 views
1

나는 패널과 2 개의 버튼이 있어야하는 곳에 자바 앱 (연습용)을 만들고있다.충돌했을 때 볼의 색을 바꾼다

  1. 시작 버튼을 누를 때마다 볼이 표시되고 스레드를 기준으로 이동해야합니다. 사용자는 최대 10 개의 독립적 인 볼을 표시 할 수 있습니다.
  2. 정지 버튼을 누르면 정지 버튼을 누를 때마다 1 개의 볼을 제거해야합니다 (예 : 4 개의 볼이있는 경우 사용자가 모든 볼을 독립적으로 제거하려면 4 번 중지 버튼을 눌러야 함)
  3. 모두 볼의 x 및 y 좌표가 매트릭스에 저장되어야
  4. 1 이상의 공 (들)은 청색

확인 적색에서 색을 변경해야 서로 만 충돌 볼과 충돌 할 때 나는 거의 완벽하게 끝냈다. (1 점에서 4 점까지) 그러나 여기에 내 문제가있다. 공이 다른 공과 충돌 할 때 충돌 공의 색상을 파란색으로 변경하는 대신 내 코드가 모든 공 색을 빨간색에서 파란색으로 변경합니다. 나는 내 실수가 new Balls().setColor(Color.Blue)에 있다는 것을 알고 있지만 충돌하는 공만 바꾸는 방법을 모른다.

다음은 Java 앱과 코드의 스크린 샷입니다. 누구든지이 두통으로 나를 도울 수 있습니까?

PRINTSCREEN : enter image description here

소스 코드 : 당신은 응용 프로그램의 정적 필드로 clr을 정의

import java.awt.Color;    
import java.awt.Dimension;  
import java.awt.FlowLayout; 
import java.awt.Graphics;  
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.JButton;  
import javax.swing.JFrame;  
import javax.swing.JLabel; 
import javax.swing.JPanel;` 


public class BouncingBalls extends JPanel implements ActionListener { 

protected List<Ball> balls = new ArrayList<Ball>(10); 
private final Container container; 
private final DrawCanvas canvas; 
private int canvasWidth; 
private int canvasHeight; 
public JButton start, stop; 
int [][] coords= new int[11][2]; 
int ammountOfBalls = 0; 
static Color clr= Color.RED; 


public static int random(int maxRange) { 
    return (int) Math.round((Math.random() * maxRange)); 
} 

public BouncingBalls(int width, int height) { 
    setLayout(new FlowLayout()); 
    start= new JButton("start"); 
    start.addActionListener(this); 
    stop= new JButton("stop"); 
    stop.addActionListener(this); 
    add(start); 
    add(stop); 
    add(new JLabel("")); 
    container = new Container(); 
    canvasWidth = width; 
    canvasHeight = height; 
    canvas = new DrawCanvas(); 
    this.setLayout(new FlowLayout()); 
    this.add(canvas); 
    start(); 

} 

public void start() { 

    Thread t = new Thread() { 
     @Override 
     public void run() { 

      while (true) { 

       update(); 
       getPositions(); 
       collisionDetection(); 
       repaint(); 
       try { 
        Thread.sleep(30); 
       } catch (InterruptedException e) { 
       } 
      } 
     } 

     private void collisionDetection() { 
      // The algorithm that detects collision 
      for(int i=0;i<ammountOfBalls;i++){ 
      for(int j=i+1; j<ammountOfBalls; j++){ 
        if(collisionMethod(i,j)){ // my collision method 
         //HOW DO I CHANGE ONLY THE COLLIDING BALLS COLOR HERE???? 
        new Ball().setColor(Color.BLUE); // this line here changes the color of all the balls on the panel 
         System.out.println("Its a hit"); 
        } 
       } 

      } 

     } 

     private void getPositions() { 
      int row=0; 
      for (Ball ball : balls) { 
      int x =ball.getXPosition(); 
      int y =ball.getYPosition(); 
      coords[row][0]=x; 
      coords[row][1]=y; 
      row++; 
      } 

     } 

     private boolean collisionMethod(int i, int j) { 
      float xd = coords[i][0]-coords[j][0]; 
      float yd=coords[i][1]-coords[j][1]; 
      float radius= new Ball().ballRadius; 
      float sqrRadius= radius * radius; 
      float distSqr= (xd * xd) + (yd * yd); 

      if(distSqr <= sqrRadius) 
       return true; 

      return false; 
     } 
     }; 
    t.start(); 
} 

public void update() { 
    for (Ball ball : balls) { 
     ball.move(container); 
    } 
} 

@Override 
public void actionPerformed(ActionEvent e) { 
    if(e.getSource() == start){ 
     if(ammountOfBalls < 10){ 
      // to limit the ammount of balls to 10 
      balls.add(new Ball()); 
      ammountOfBalls++; 
     } 
    } 

    else if(e.getSource() == stop){ 
     if(ammountOfBalls > 0){ 
     ammountOfBalls --; 
     balls.remove(ammountOfBalls); 

    } 

    } 
} 

class DrawCanvas extends JPanel { 

    @Override 
    public void paintComponent(Graphics g) { 

     super.paintComponent(g); 
     container.draw(g); 
     for (Ball ball : balls) { 
      ball.draw(g); 
     } 
    } 
    @Override 
    public Dimension getPreferredSize() { 
     return (new Dimension(700, 400)); 
    } 
} 

public static void main(String[] args) { 
      JFrame f = new JFrame("Bouncing Balls"); 
      f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); 
      f.setPreferredSize(new Dimension(800,500)); 
      f.setContentPane(new BouncingBalls(800,800)); 
      f.pack(); 
      f.setVisible(true); 
    } 


public static class Ball { 

    public int random(int maxRange) { 
     return (int) Math.round(Math.random() * maxRange); 
    } 

int x = random(700); // method to get random coords for the x-value 
int y = random(400); // method to get random coords for the y-value ...... these are used to get random positions for the balls instead of only static 
int xMovement = 10; 
int yMovement = 10; 
int ballRadius = 20; 
int i = 0; 


public Color getColor(){ 
    return clr; 
} 
public Color setColor(Color color){ 
clr=color; 
return clr; 
} 
    public void draw(Graphics g) { 
     g.setColor(getColor()); 
     g.fillOval(x,y,ballRadius,ballRadius); 

    } 
    public int getXPosition(){ 
     return x; 
    } 
    public int getYPosition(){ 
     return y; 
    } 

    public void move(Container container) { 
     x += xMovement; 
     y += yMovement; 

     if (x - ballRadius < 0) { 
      xMovement = -xMovement; 
      x = ballRadius; 
     } 
     else if (x + ballRadius > 700) { 
      xMovement = -xMovement; 
      x = 700 - ballRadius; 
     } 

     if (y - ballRadius < 0) { 
      yMovement = -yMovement; 
      y = ballRadius; 
     } 
     else if (y + ballRadius > 400) { 
      yMovement = -yMovement; 
      y = 400 - ballRadius; 
     } 
    } 
} 



public static class Container { 
    private static final int hightPanel = 800; 
    private static final int widthPanel= 800; 

    public void draw(Graphics g) { 
     g.setColor(Color.WHITE); 
     g.fillRect(0, 0, widthPanel, hightPanel); 
    } 
} 
} 

`

+1

실제로 충돌하는 볼을 식별해야합니다. 시각적 표현과 분리 된 객체의 좌표를 처리하는 이상한 방법처럼 보입니다. – ChiefTwoPencils

+0

작동 예제를 보려면 [복잡한 모양으로 충돌 감지] (http://stackoverflow.com/a/14575043/418556)도 참조하십시오. –

답변

5

. Ball 클래스가 setColor()을 호출 할 때 clr의 값을 파란색으로 변경하면 getColor()을 호출하는 Ballclr이 파란색이라는 것을 알게됩니다.

해결 방법 : clr을 응용 프로그램 전체의 정적 필드로 사용하지 마십시오. Ball 클래스에서 정적이 아닌 필드로 정의하십시오. 따라서 각 Ball에는 자체 색상이 있습니다.

+1

좋은 눈. 나는 그들이 추가 쟁점을 가지고 있다고 생각한다. 그들은 충돌시 새로운 볼을 만들고 실제로 충돌하는 볼을 가지고 있지 않습니다. 그들의 좌표 만. – ChiefTwoPencils

+0

도움 주셔서 대단히 감사합니다. 이제 완벽하게 작동하고 있습니다. –

관련 문제