0

衝突検出のために画像を回転させるjs関数を作成しましたが、回転がπ* 1.5(Pi)を超えると関数が正しく機能しません。画像がトリミングされます。

function rotateImage(image , rotation)
{

    // Creates a canvas
    var rotatedImage = document.createElement( "canvas" ) . getContext( "2d" ),

    // Setting a bounding box size
    boundingWidth = Math . abs( image . height * Math . cos( rotation ) + image . width * Math . sin( rotation ) ),
    boundingHeight = Math . abs( image . height * Math . sin( rotation ) + image . width * Math . cos( rotation ) );

    // Changing canvas size
    rotatedImage . canvas.width = boundingWidth;
    rotatedImage . canvas.height = boundingHeight;

    // Translating canvas
    rotatedImage . translate( boundingWidth/2 , boundingHeight/2 );

    // Rotate canvas
    rotatedImage . rotate( rotation );

    // Un-translating canvas
    rotatedImage . translate( -boundingWidth/2 , -boundingHeight/2 );

    // Draws image
    rotatedImage . drawImage( image , 0 , 0 );

    // Returns canvas
    return rotatedImage . canvas;

}

ありがとう :)

4

1 に答える 1

3

[編集: OPは、衝突検出が必要であることを明確にしました]

ああ...回転した長方形の境界ボックスを衝突検出に使用したい。

そのためにキャンバスの回転を使用する必要はありません。三角法を使用するだけです!

// where w = rectangle width (sprite width)
// where h = rectangle height (sprite height)
// where a = angle of rotation in degrees
// calculate the bounding box of the rectangle at the given rotation

function BoundingBoxDimensions(w,h,a){
  var rads=a*Math.PI/180;
  var c = Math.abs(Math.cos(rads));
  var s = Math.abs(Math.sin(rads));
  return({  width: h * s + w * c,  height: h * c + w * s });
}

上記のコードに関して、Math.sin(rotation) または Math.cos(rotation) が負になる場合は、BB 計算で使用する前に絶対値を取得する必要があります。PI * 1.5 で計算が狂ってしまうのはそのためです。

于 2013-04-12T20:20:47.833 に答える