アットウィキロゴ

飛び回る球

  1. package test;
  2.  
  3. import java.applet.Applet;
  4. import java.awt.Color;
  5. import java.awt.Graphics;
  6. import java.awt.Point;
  7. import java.awt.Rectangle;
  8. import java.awt.event.ActionEvent;
  9. import java.awt.event.ActionListener;
  10.  
  11. public class BasicApplet extends Applet implements ActionListener {
  12.  
  13. Ball ball;
  14. Rectangle rect;
  15.  
  16. //コンストラクタはやっつけ
  17. public BasicApplet(){
  18. this.setSize(120,120);
  19. this.setBackground(Color.black);
  20. ball = new Ball(10);
  21. rect = new Rectangle(10,10,100, 100);
  22. new javax.swing.Timer(50, this).start();
  23. }
  24.  
  25. public void paint(Graphics g){
  26. ball.draw(g);
  27. }
  28.  
  29. //タイマーイベントで、ballの座標を更新する
  30. public void actionPerformed(ActionEvent arg0) {
  31. ball.move(rect);
  32. repaint();
  33. }
  34.  
  35. //飛び回るボールのクラス
  36. public class Ball {
  37. private double velocity, arg; //速度,x軸となす角
  38. private final double RAD = Math.PI / 180;
  39. private float hue;//ボールの色を変えるため
  40. private int x, y, size, sizeOffset;//ボールの位置とサイズ
  41. private Color color;//色変え用
  42.  
  43. public Ball(int size) {
  44. this.size = size;
  45. sizeOffset = size / 2;
  46. x = 10;
  47. y = 10;
  48. velocity = 10.0;
  49. arg = 33.0;
  50. hue = 0.f;
  51. color = new Color(0xffffff);
  52. }
  53.  
  54. /**
  55. * @param rect ボールの移動範囲となる四角いエリア
  56. * */
  57. public void move(Rectangle rect) {
  58. int xdist, ydist;
  59. Point next;
  60. xdist = (int) (velocity * Math.cos(arg * RAD));
  61. ydist = (int) (velocity * Math.sin(arg * RAD));
  62.  
  63. next = new Point(x + xdist, y + ydist);
  64.  
  65. // x range check
  66. if (next.x < rect.x) {
  67. next.x = -next.x;
  68. arg = 180 - arg;
  69. } else if (rect.width < next.x) {
  70. next.x = rect.width - (next.x - rect.width);
  71. arg = 180 - arg;
  72. }
  73.  
  74. // y range check
  75. if (next.y < rect.y) {
  76. next.y = -next.y;
  77. arg = 360 - arg;
  78. } else if (rect.height < next.y) {
  79. next.y = rect.height - (next.y - rect.height);
  80. arg = 360 - arg;
  81. }
  82. x = next.x;
  83. y = next.y;
  84. }
  85.  
  86. //ボールを描画する
  87. public void draw(Graphics g) {
  88. if (1.0 <= (hue += 0.05f)) {
  89. hue = 0;
  90. }
  91. g.setColor(new Color(color.HSBtoRGB(hue, 1.f, 1.f)));//色を付ける
  92. g.fillOval(x - sizeOffset, y - sizeOffset, size, size);
  93. }
  94. }
  95. }
  96.  
最終更新:2011年06月30日 00:02