Let’s use the method called Verlet Integration to create simple physics simulations. We are going to implement complex features like collision detection. Just by combining simple dots and lines, we will make a skeleton for a dancing doll like this.

ベレ法という手法を使って簡単な物理シミュレーションを作ってみましょう。衝突判定など複雑な機能は実装しません。シンプルな点や線を部品として組み合わせて、こんな踊る人形の骨組みを作ってみます。

https://www.instagram.com/p/CEHfUGjnJ9j/?utm_source=ig_web_copy_link&igshid=MzRlODBiNWFlZA==

Existing libraries and tools would work better for proper simulations, but knowing a technique like this can be helpful understanding how these work, or when you want to have freedom in inventing interesting movements.

きちんとしたシミュレーションには既存のライブラリやツールを用いる方が良いですが、こうした方法を知っておくと仕組みを理解したり、自由に面白い動きを作りたい時などに助けになります。

Points

First we define points.

まず点を定義します。

In this implementation, instead of explicitly keeping velocity as a variable of the object, we substitute it with the change from the previous position to the current position. If no force is applied, the object is assumed to continue its uniform motion, and if the position changes, the difference is simply considered the velocity.

この実装では、物体に属する変数として速度を明示的に保持する代わりに、前の位置から現在の位置への変化量で代用します。力が加わらなければ物体は等速運動を続けるものとし、位置が変更された場合はその差分を単純に速度とみなすわけです。

class VerletPoint {
  constructor(p) {
    this.setPosition(p);
  }

  setPosition(p) {
    this.position = p;
    this.prevPosition = this.position.copy();
  }

  update() {
    let temp = this.position.copy();
    this.position.add(this.getVelocity());
    this.prevPosition = temp;
  }

  setVelocity(v) {
    this.prevPosition = this.position.copy().sub(v);
  }

  getVelocity() {
    return this.position.copy().sub(this.prevPosition);
  }

  draw() {
    ellipse(this.position.x, this.position.y, 8, 8);
  }
}

https://codepen.io/kynd/pen/BRMmGO