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 回答