0
0

Web記事で見かけた「指数平滑法」を使ったアニメーションを p5.js で試してみる

Posted at

以下の記事で見かけた「指数平滑法」を使ったアニメーションを、p5.js で試してみたという話です。

●アニメーションをスムーズに見せるためのテクニック「指数平滑法」とはどんなものなのか? - GIGAZINE
 https://gigazine.net/news/20240427-animation-trick/

上記の記事の内容は、以下のブログが元になっているようです。

●My favourite animation trick: exponential smoothing | lisyarus blog
 https://lisyarus.github.io/blog/posts/exponential-smoothing.html

「指数平滑法」を使ったアニメーションで、ポイントになるのは以下の式のようです。

image.png

これを、p5.js の単純なアニメーションに適用してみます。

p5.js Web Editor で試す

それでは p5.js で試してみます。

環境として、手軽に使える p5.js Web Editor を利用します。

作成したプログラム

プログラムは以下としました。

let ball = {
  x: 0,
  y: 100,
  speed: 3,
  target: 400,
};

function setup() {
  createCanvas(ball.target, 200);
  noStroke();
}

function draw() {
  background(220);

  let dt = 1.0 / frameRate();
  ball.x += (ball.target - ball.x) * (1 - exp(-dt * ball.speed));

  ellipse(ball.x, ball.y, 20, 20);

  if (ball.x >= width - 10) {
    ball.target = 0;
  }
  if (ball.x <= 10) {
    ball.target = width;
  }
}

function mouseClicked() {
  ball.target = width - ball.target;
}

左右方向へのボールの移動に、指数平滑法を適用してみました。

また、冒頭の記事に書かれていた「アニメーションの途中で、移動方向を変化させたときの、アニメーションの切り替わり」という話がありました。それを検証できるように、mouseClicked() を使って、マウスクリックによる移動方向の途中での切り替えを試せるようにしました。

動作確認

上記を動かしてみた結果は、以下のとおりです。

移動途中で、マウスクリックの操作を行って、移動方向を強制的に変えたりもしてみています。

移動方向が途中で変化した際にも、うまくアニメーションがつながることが確認できました。

0
0
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
0
0