解答は
- ホスト名: earth.mlab.im.dendai.ac.jp
- ディレクトリ: /home/submit/JavaBeginners/[今日の日付]/[学籍番号]
に提出しなさい。ソースファイル (〜.java) のみを提出。 gFTP 等を使い ftp を用いて提出しなさい。
今回の例題「跳ね返るボールのアニメーション(1)」を改良し、 2つの青と赤のボールが跳ね返るアニメーションを行うプログラムを作成しなさい。 ボール同士のぶつかりなどの相互作用は考慮しなくて良い。 ボールの直径は40ピクセルとする。 mainメソッドのあるクラス名 TwoBallsAnimation1 とする。 (ファイル名 TwoBallsAnimation1.java)
[ サンプル ]
サンプルの実行方法: ファイルをダウンロードして、以下のコマンドを実行。
$ java -jar ファイル名.jar
import java.awt.*;
import javax.swing.*;
class TwoBallsAnimation1 {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Ball Animation");
frame.setSize(640, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
class MyPanel extends JPanel implements Runnable {
// 2つのボールオブジェクトを宣言
1つ目のボールについて....;
2つ目のボールについて....;
public MyPanel() {
setBackground(Color.white);
// 2つのボールオブジェクトの生成
// (初期位置, 初期速度, 移動範囲の情報を与えて初期化)
1つ目のボール = new Ball(100,100,2,1,0,0,590,410);
2つ目のボール = new Ball(200,100,1,2,0,0,590,410);
Thread refresh = new Thread(this);
refresh.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// 2つのボールに対してアニメーション1コマ分の移動を行う
1つ目のボールについて....;
2つ目のボールについて....;
// (A) ←問題2の説明用
// ボールの描画
g.setColor(Color.red);
1つめのボールを描く (ボールの直径は40ピクセルとする)
g.setColor(Color.blue);
2つめのボールを描く (ボールの直径は40ピクセルとする)
}
public void run() {
while(true) {
repaint();
try {
Thread.sleep(10);
}
catch(Exception e) {
}
}
}
}
class Ball {
private int x;
private int y;
private int vx;
private int vy;
private int left;
private int right;
private int top;
private int bottom;
public Ball(int x, int y, int vx, int vy, int l, int t, int r, int b) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
right = r;
left = l;
top = t;
bottom = b;
}
public void forward() {
x = x + vx;
y = y + vy;
if (x < left || x > right) {
vx = -vx;
}
if (y < top || y > bottom) {
vy = -vy;
}
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getVX() {
return vx;
}
public void setVX(int vx) {
this.vx = vx;
}
public int getVY() {
return vy;
}
public void setVY(int vy) {
this.vy = vy;
}
}
上のプログラムを元に、 ボール同士がぶつかると跳ね返るように改良しなさい。 mainメソッドのあるクラス名 TwoBallsAnimation2 とする。 (ファイル名 TwoBallsAnimation2.java)
そのためには、上のプログラムの (A) の位置で、 ボールがぶつかったかどうかの判定を行う。判定の方針は次の通り。
ボール間の距離 = √(
(ボール1のX座標 - ボール2のX座標)2 +
(ボール1のY座標 - ボール2のY座標)2 )
ボール間の距離がボールの直径以下であれば、ぶつかったと判定する。
ぶつかった場合、
ボール1のX方向の速度 × ボール2のX方向の速度 < 0 であれば、 各ボールのX方向の進む向き逆転 (速度×-1) させる。
ボール1のY方向の速度 × ボール2のY方向の速度 < 0 であれば、 各ボールのY方向の進む向きを逆転 (速度×-1) させる。
なお、xの平方根 √(x) は Math.sqrt(x) とすると求まる。
[ サンプル ]