前回のコードをクラスを使って書き換えてみます。
以下のように書き換えてみました。クラスの中に変数と動き(メソッド)を入れたので、前よりもすっきりとしました。
Ball[] balls = new Ball[10];
Racket me = new Racket();
Enemy enemy = new Enemy();
class Ball{
float x, y, xSpeed, ySpeed, r, hr, xDir, yDir;
Ball(){
x = width/2;
y = height/2;
xSpeed = random(-5, 5);
ySpeed = random(-5, 5);
r = random(4, 8);
xDir = 1;
yDir = 1;
hr = r/2;
}
void move(){
fill(255);
ellipse(x, y, r, r);
if ((y+hr>height) || (y-hr<0))
yDir *= -1;
if ((x+hr >= 440) && (x+hr <= 450) && (y > me.y-25) && (y < me.y+25))
xDir *= -1;
if (((x-hr) <= 50) && ((x-hr) >= 40) && (y > enemy.y) && (y < enemy.y+100))
xDir *= -1;
if (x > width) {
enemy.score ++;
x = width/2;
y = height/2;
xSpeed = random(1, 4);
ySpeed = random(1, 4);
}
else if(x < 0) {
me.score ++;
x = width/2;
y = height/2;
xSpeed = random(1, 4);
ySpeed = random(1, 4);
}
x += xSpeed * xDir;
y += ySpeed * yDir;
xSpeed += 0.01;
ySpeed += 0.01;
}
}
class Racket{
float x, y, easing, targetY;
int score;
Racket(){
x = 440;
y = height/2;
easing = 0.1;
score = 0;
}
void move(){
targetY = mouseY;
y += (targetY - y) * easing;
rect(x, y-25, 10, 50);
}
}
class Enemy{
float x, y, dir;
int score;
Enemy(){
x = 40;
y = height/2;
dir = 1;
score = 0;
}
void move(){
rect(40, y, 10, 100);
y += dir;
if((y < 0) || ((y+250) > width)) dir *= -1;
}
}
void setup() {
size (480,320);
for (int i = 0; i < balls.length; i++){
balls[i] = new Ball();
}
me = new Racket();
enemy = new Enemy();
}
void draw() {
background(0);
for(int i = 0; i < 10; i++) balls[i].move();
strokeWeight (1);
stroke(255);
for ( int i = 0; i < height; i += 10 ){
line(width/2, i, width/2, i+5);
}
me.move();
enemy.move();
// score display
textAlign(CENTER, CENTER);
textSize(30);
text(enemy.score, 120, 20);
text(me.score, 360, 20);
// end message
textSize(80);
if (me.score >= 100){
text("You WIN!", width/2, height/2-30);
textSize(40);
text("Click to restart", width/2, height/2+30);
}
else if (enemy.score >= 100){
text("You LOSE!", width/2, 130);
textSize(40);
text("Click to restart", width/2, 200);
}
// reset
if(mousePressed){
for (int i = 0; i < 10; i++){
balls[i].x = width/2;
balls[i].y = height/2;
}
me.score = 0;
enemy.score = 0;
}
}
ラケットの動きは、move() というメソッドにまとめました。draw() 内でのラケットの記述は、me.move(); と enemy.move(); のみです。まだ少しプレイヤーのラケットのボールの衝突判定が雑なときがありますね。忘れなければいつか修正します。細かな部分を少し修正しましたが、内容は前回のものとほとんど同じです。
敵強いな・・・。勝てない。
