/*-------------------------------------------- ex14_2.java ボールを転がそう(初期位置・射出方向ランダム) ---------------------------------------------*/ /* */ import java.applet.*; import java.awt.*; import java.util.Random; public class ex14_2 extends Applet implements Runnable{ Thread thd = null; Dimension size; Random rnd; int x, y, vel, app_wid, app_hei, dia; double theta; public void init() { // 初期化処理 size = getSize(); // アプレット画面の大きさ取得 app_wid = size.width; app_hei = size.height; dia = 50; // 描画ボールの直径(diameter) vel = 10; // 描画ボールの速度(velocity) rnd = new Random(); x = rnd.nextInt(app_wid-dia); y = rnd.nextInt(app_hei-dia); // 描画ボールの初期位置(x, y) theta = Math.PI / rnd.nextInt(13); // 描画ボールの射出方向(π/6) thd = new Thread(this); thd.start(); } public void update(Graphics g) { // 再描画で背景クリアをしない paint(g); } public void paint(Graphics g) { // 描画処理 g.setColor(Color.blue); g.drawOval(x, y, dia, dia); } public void run() { // 実行処理 while (true) { if (0 < x && x < app_wid-dia && 0 < y && y < app_hei-dia) { // theta = theta; } else if (y <= 0 || y >= app_hei-dia) { theta = 2*Math.PI - theta; } else if (x <= 0 || x >= app_wid-dia) { if (0 <= theta && theta < Math.PI) { theta = Math.PI - theta; } else if (Math.PI <= theta && theta <= 2*Math.PI) { theta = 3*Math.PI - theta; } } else { System.out.println("Error: theta..."); } double dx = vel * Math.cos(theta); double dy = vel * Math.sin(theta); x += dx; y += dy; repaint(); try { thd.sleep(10); } catch (InterruptedException e) { } } } }