LoginSignup
44
27

More than 5 years have passed since last update.

p5.jsでヒレが元気に動く魚を作ってみた!

Posted at

先日、魚のマウスストーカーが実装される拡張機能を作りました!
kakucyou.gif

gif動画では確認しにくいのですが、実はこの魚たちはp5.jsで作られていて、ヒレや尾びれも元気に動いています笑

ここでは、p5.jsにおける魚の作り方を紹介します。参考になれば幸いです。

成果物

fishMoving.gif

魚の基本形

まずプログラムを紹介し、その後に解説を進めていきます!

p5.js
class Fish {
  constructor(x, y) {
    this.position = createVector(x, y)
    this.theta = 0
    this.color = { filet: color(153, 206, 255), body: color(30, 144, 255) }
  }

  update() {
    this.theta += PI / 100
  }

  display() {
    push()
    noStroke()
    translate(this.position.x, this.position.y)

    //左右のヒレ
    for (let i = -1; i <= 1; i += 2) {
      push()
      fill(this.color.filet)
      translate(0, 10)
      rotate((PI / 12) * sin(this.theta * 2) * i)

      beginShape()
      vertex(0, 0)
      vertex(12 * i, 4)
      vertex(10 * i, 10)
      vertex(0, 4)
      endShape()
      pop()
    }
    ////////////

    //尻尾
    push()
    fill(this.color.filet)
    translate(0, 25)
    rotate((PI / 12) * sin(this.theta * 2))
    beginShape()
    vertex(0, 0)
    bezierVertex(0, 0, 5, 5, 3, 15)
    bezierVertex(3, 15, 0, 8, 0, 8)
    bezierVertex(0, 8, 0, 8, -3, 15)
    bezierVertex(-3, 15, -5, 5, 0, 0)
    endShape()
    pop()

    //胴体
    beginShape()
    fill(this.color.body)
    vertex(0, 30)
    bezierVertex(0, 30, -10, 10, 0, 0)
    bezierVertex(0, 0, 10, 10, 0, 30)
    endShape()

    pop()
  }
}

let fish

function setup() {
  createCanvas(300, 200)
  fish = new Fish(width / 2, height / 2)
}

function draw() {
  background(0)
  fish.update()
  fish.display()
}

超簡単にまとめると、displayが魚の描写、 updateがヒレに関与するthetaを更新する関数になります!

ヒレが動く原理

ヒレは、基本形をrotateで回転させて胴体にくっつけています。

ここでthetaをsinにぶち込むことで、ヒレが円運動します!もしヒレの速さや振れ幅を変えたいときは、rotate内の数字をいじってみて下さい!

最後に

ここではp5.jsで魚を表現するプログラミングを紹介しました。ここから派生して、色々な魚を作ることができますので、ぜひ色々お試しください!

おまけ:フィッシュマウスストーカーの拡張機能

fishMouseStalker

44
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44
27