LoginSignup
15
10

More than 5 years have passed since last update.

sin・cosを使って円運動を作成する

Last updated at Posted at 2018-04-13

三角関数なんて忘れてしまったのでメモ。

sin・cosとは

sinもcosも数値(角度)を与えてあげると、数値に応じて-1 〜 +1 までの数値を返してくれる便利なやつ。

sinとcosの違いは
sin 0 が 0で、
cos 0 が 1で始まるところ。

alt

周期は同じなので、これを利用して半径(radius)をかけると振幅する値が作れ、
それぞれxとyに指定すればクルクルまわる円運動が作れる。

初期位置だと回転してるときにマイナスにも行ってしまうので、
中心点(center)をさらに足して場所を調整する。

JSで回転させたい

const el = document.querySelector('div');
const center = 100;
const radius = 50;

setInterval(() => {
  const t = new Date().getTime() / 500;

  const x = center + (Math.cos(t) * radius);
  const y = center + (Math.sin(t) * radius);

  el.setAttribute('style', `top: ${x}px; left: ${y}px;`)
}, 10);

今回与えている数値は時間を元に作成していて、new Date().getTime()で取得できるのはミリ秒、これを500で割っている。
つまり0.5秒で1度変化する。

See the Pen create circular motion using sin & cos by なりたけいすけ (@narikei) on CodePen.

逆回転させたい

sinとcosを反対にすると、逆回転できる

See the Pen create circular motion using sin & cos (reverse) by なりたけいすけ (@narikei) on CodePen.

15
10
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
15
10