<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ball Launch and Particle Explosion</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
</head>
<body>
<script>
let balls = [];
let particles = [];
let gravity = 0.2;
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
}
function draw() {
background(0);
// グリーンの地面を描画
drawGround();
// カメラ設定
let cameraZ = (height / 2.0) / tan(PI * 30.0 / 180.0);
camera(0, 0, cameraZ, 0, 0, 0, 0, 1, 0);
// 全てのボールの動きと描画
for (let i = balls.length - 1; i >= 0; i--) {
let ball = balls[i];
ball.update();
ball.display();
// ボールが地面に衝突したらパーティクル生成
if (ball.y > height / 2) {
createParticles(ball.x, ball.y, ball.z);
balls.splice(i, 1); // 地面に衝突したボールを配列から削除
}
}
// パーティクルの動き
for (let i = particles.length - 1; i >= 0; i--) {
particles[i].update();
particles[i].display();
if (particles[i].isFinished()) {
particles.splice(i, 1); // 消えたパーティクルを配列から削除
}
}
}
function drawGround() {
push();
translate(0, height / 2, 0);
rotateX(PI / 2);
fill(0, 255, 0);
noStroke();
plane(width * 2, height * 2);
pop();
}
class Ball {
constructor(x, y, z, vx, vy, vz) {
this.x = x;
this.y = y;
this.z = z;
this.vx = vx;
this.vy = vy;
this.vz = vz;
}
update() {
this.x += this.vx;
this.y += this.vy;
this.z += this.vz;
this.vy += gravity;
}
display() {
push();
translate(this.x, this.y, this.z);
noStroke();
fill(255, 0, 0);
sphere(20);
pop();
}
}
class Particle {
constructor(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
this.vx = random(-3, 3);
this.vy = random(-3, 3);
this.vz = random(-3, 3);
this.alpha = 255;
}
update() {
this.x += this.vx;
this.y += this.vy;
this.z += this.vz;
this.alpha -= 5;
}
display() {
push();
translate(this.x, this.y, this.z);
noStroke();
fill(255, 255, 0, this.alpha);
sphere(5);
pop();
}
isFinished() {
return this.alpha <= 0;
}
}
function createParticles(x, y, z) {
for (let i = 0; i < 100; i++) {
particles.push(new Particle(x, y, z));
}
}
// スペースキーでボールを発射
function keyPressed() {
if (key === ' ') {
// 発射する角度と速度にランダム要素を追加
let randomVx = random(2, 5); // X軸方向に少しランダム性を追加
let randomVy = random(-2, 2); // Y軸方向に少しランダム性を追加
let randomVz = random(-6, -3); // Z軸方向にも少しランダム性を追加
// 新しいボールを生成
let ball = new Ball(0, -height / 2, 0, randomVx, randomVy, randomVz);
balls.push(ball); // ボールを配列に追加
}
}
</script>
</body>
</html>