2点間の角度を求める



this is flash contents.
2点間の角度を求める方法のメモ.
まずは…
えっと,ソースから

var x0 = 0;
var y0 = 0;
var x1 = 0;
var y1 = 0;
var count = 0;

this.lineStyle(0, 0x0000);

this.onMouseDown = function() {
  this.x0 = this._xmouse;
  this.y0 = this._ymouse;

  this.count++;
  this.moveTo(this.x0, this.y0);
};

this.onMouseUp = function() {
  this.x1 = this._xmouse;
  this.y1 = this._ymouse;

  // *1
  var width:Number = this.x1 - this.x0
  // *2
  var height:Number = -1 * (this.y1 - this.y0);
  var rad:Number;
  var deg:Number;

  // *3
  rad = Math.atan2(height, width);

  // *4
  if (rad > 0 and height < 0) {
    rad += -Math.PI;
  }
  else if (rad < 0 and height > 0) {
    rad += Math.PI;
  }

  // *5
  deg = (rad * 180) / Math.PI;
  
  this.lineTo(this.x1, this.y1);
  this.createTextField('text' + this.count, this.count, 
                        this.x0, this.y0, 100, 20);
  this['text' + this.count].text = deg + '°';
  this['text' + this.count].selectable = false;
  trace(deg);
};

// *1
まず,2点間の角度を出すにはまず2点間の距離の高さと幅を求める.

dx = x1 - x0;
dy = y1 - y0;


// *2
数学座標とグラフィック座標はy軸の方向が違うので-1をかけておいてあげる.

んで,

tan(θ) = dy / dx;

となる.

このθが分かればいいので,それをもとめるのがatan関数.
// *3
しかし,atanの引数は(height / width)となっていて分母が0の時の考慮をしてあげないといけないのでメンドイ.
そこまでやってくれるのがatan2(height, width)関数.


// *4
atan2の戻り値だけでは角度を一意に判別することはできないので先に求めた,移動距離(ベクトル)を参考にしつつ補正してあげる.

// *5
んで,まー,degree(度)に戻すことも無いと思うんですが,表示上もどしておしまいです.


contributor nao : 2005年05月30日 10:30

trackback

trackback for this entry URL:
http://blog.graffiti-web.org/mt/mt-tb.cgi/210

comment