2つのベクトルから角度を求めるとき

tuitui.hatenablog.comのときのメモ

2つのベクトルから角度を求めるとき
A⃗ · B⃗ = ∥∥A⃗ ∥∥ * ∥∥B⃗ ∥∥ * cos(θ) と
A⃗ · B⃗ = axbx+ayby

から θ = cos−1 ( ( A⃗ · B⃗ ) / ( ∥∥A⃗ ∥∥ * ∥∥B⃗ ∥∥ ) )

なので、ベクトルでよく使う関数をいつも使いまわしているんですが そこに内積と、2つのベクトルの間の角度を返す関数をプラスすることにしました

//ベクトル
class Vector{
    constructor(x,y){
    this.x = x;
    this.y = y;
  }
  //初期値を保存
  saveInitProp(){
    this.startX = this.x;
    this.startY = this.y;
  }
  //ベクトル加算
  addProp(vectorA){
    this.x += vectorA.x;
    this.y += vectorA.y;
  }
  //ベクトル減算
  subProp(vectorA){
    this.x -= vectorA.x;
    this.y -= vectorA.y;
  }
  //ベクトル乗算
  mult(num){
    this.x = this.x * num;
    this.y = this.y * num;
  }
  //ベクトル除算
  div(num){
    this.x = this.x / num;
    this.y = this.y / num;
  }
  //ベクトルの大きさを返す
  mag(){
    return Math.sqrt(this.x * this.x + this.y * this.y);
  }
  //正規化する
  normalize(){
    var size = Math.sqrt(this.x * this.x + this.y * this.y);
    if(size === 0){
      return;
    }
    this.x = this.x * (1 / size);
    this.y = this.y * (1 / size);
  }
  //最大値
  limit(max){
    if(this.x > max){
      this.x = max;
    }
    if(this.x * -1 > max){
      this.x = max * -1;
    }
    if(this.y > max){
      this.y = max;
    }
    if(this.y * -1 > max){
      this.y = max * -1;
    }
  }
  //長さ1のランダムな値を返す
  random2D(){
    this.x = (Math.random()*2)-1;
    this.y = (Math.random()*2)-1;
    return this.normalize();
  }
  //同じ値をもったVectorを返す
  copy(){
    return new Vector(this.x, this.y);
  }
  //ベクトル内積
  static dot(vectorA, vectorB){
    return vectorA.x * vectorB.x + vectorA.y * vectorB.y;
  }
  //ベクトル間の角度を返す
  static angleBetween(vectorA, vectorB){
    var theta = Math.acos((this.dot(vectorA,vectorB))/(vectorA.mag() * vectorB.mag()));
    return theta;
  }
}

まだ増えそう。


tuitui.hatenablog.com

のときによくわかってなかったstatic
インスタンス経由でなくクラス経由でメソッドが呼び出せるようになる。 今までappllyとかcallを使ってたところがこれで書けるようになるんですね(?)う〜ん便利