メインコンテンツへスキップ
見出し画像
Photo bynodakaori

ChatGPTに風船を飛ばしてもらった

    こんにちは。ChatGPTに風船をとばしてもらいました。
    今回は過去の記事を参考にして作っています。
    (実践したい方はこちらを読んでください)


    作成

    それではChatGPTに風船を飛ばしてもらいます。


    質問:
    p5.jsでたくさんの風船が飛んでいくコードを書いてください。

    ChatGPTの回答:
    以下は、p5.jsを使用してたくさんの風船がランダムに飛んでいくサンプルコードです。風船はランダムな位置から開始し、ランダムな速度で移動します。風船が画面外に出ると、ランダムな位置から再度開始します。

    let balloons = []; // 風船の配列
    let balloonNum = 50; // 風船の数
    
    function setup() {
      createCanvas(400, 400);
      // 風船を生成
      for (let i = 0; i < balloonNum; i++) {
        balloons.push(new Balloon(random(width), random(height)));
      }
    }
    
    function draw() {
      background(220);
      // 風船を更新・描画
      for (let i = 0; i < balloons.length; i++) {
        balloons[i].update();
        balloons[i].display();
      }
    }
    
    class Balloon {
      constructor(x, y) {
        this.x = x;
        this.y = y;
        this.speedX = random(-2, 2); // x方向の速度
        this.speedY = random(-2, 2); // y方向の速度
        this.size = random(20, 40); // 大きさ
        this.color = color(random(255), random(255), random(255)); // 色
      }
      
      update() {
        // 風船を移動
        this.x += this.speedX;
        this.y += this.speedY;
        // もし画面外に出たら、ランダムな位置から再度開始する
        if (this.x > width || this.x < 0 || this.y > height || this.y < 0) {
          this.x = random(width);
          this.y = random(height);
        }
      }
      
      display() {
        // 風船を描画
        strokeWeight(1);
        stroke(0);
        fill(this.color);
        ellipse(this.x, this.y, this.size, this.size*1.5);
        line(this.x, this.y + this.size*0.75, this.x, this.y + this.size*1.5);
      }
    }

    このコードを実行すると、たくさんの風船がランダムに移動していく様子が確認できます。風船の数や速度、大きさ、色などを調整して、自分なりのバリエーションを加えることができます。



    結果

    風船が飛んでいきました。

    画像
    p5.js Web Editor内で風船が飛んでいく様子


    まとめ

    今回はChatGPTに風船が飛んでいくコードを書いてもらいました。
    最後まで御覧いただき、ありがとうございました。


    過去に書いた記事


     
     
    理系の大学院卒。 プログラミングが少し出来ます。 AIと一緒に楽しく遊ぶ内容を書いています。

    あなたへのおすすめ