【发布时间】:2014-02-08 09:42:29
【问题描述】:
几个网站给出了相同的答案,但它不适合我。我会很感激任何关于我哪里出错的指导。
情况:我想旋转一个多边形。我有每个点的坐标。我通过这个函数运行每个点,应该给我旋转的多边形。然而,新的比原来的更短更宽 - 它改变了形状。这是我的代码的更完整版本;
function rotatePoint($coord,$rot){
/*
in - x, y coordinate, how much to rotate in degrees
do - rotate each point
out - end coordinate point
rotate a point (x, y) by t radians counterclockwise
about the origin (0, 0), the transformed coordinates (x', y')
can be computed by:
x' = cos(t)*x - sin(t)*y
y' = sin(t)*x + cos(t)*y
*/
$rotRad=deg2rad($rot);
$rotCoord=array();
$rotCoord['x']=(cos($rotRad)*$coord['x'])-(sin($rotRad)*$coord['y']);
$rotCoord['y']=(sin($rotRad)*$coord['x'])+(cos($rotRad)*$coord['y']);
return $rotCoord;
};
$polygonPoints=array(
array('y'=>40.039363507917,'x'=>-76.112888306379),
array('y'=>40.039369668435,'x'=>-76.112935245037),
array('y'=>40.039246457955,'x'=>-76.112959384918),
array('y'=>40.039240297425,'x'=>-76.11291244626),
array('y'=>40.039363507917,'x'=>-76.112888306379)
);
$rotateAmt=90;//how much to rotate
$pointX = array();
$pointY = array();
foreach ($polygonPoints as $key => $row)
{
$pointX[$key] = $row['x'];
$pointY[$key] = $row['y'];
}
$maxX=$minX=$polygonPoints[0]['x'];
$maxY=$minY=$polygonPoints[0]['y'];
for($i=0;$i<count($polygonPoints);$i++){
if($polygonPoints[$i]['x']>=$maxX){$maxX=$polygonPoints[$i]['x'];};
if($polygonPoints[$i]['x']<$minX){$minX=$polygonPoints[$i]['x'];};
if($polygonPoints[$i]['y']>=$maxY){$maxY=$polygonPoints[$i]['y'];};
if($polygonPoints[$i]['y']<$minY){$minY=$polygonPoints[$i]['y'];};
}
$center=array('x'=>($maxX+$minX)/2,'y'=>($maxY+$minY)/2);
$adjustment=array('x'=>0-$center['x'],'y'=>0-$center['y']);
echo 'Adjustment<pre>';
var_dump($adjustment);
echo'</pre>';
$adjustedPolygon=array();
for($i=0;$i<count($polygonPoints);$i++){
$adjustedPolygon[$i]['x']=$polygonPoints[$i]['x']+$adjustment['x'];
$adjustedPolygon[$i]['y']=$polygonPoints[$i]['y']+$adjustment['y'];
}
$rotatedPolygon=array();
for($i=0;$i<count($adjustedPolygon);$i++){
// echo 'before rotatePoint '.$i.'='.$adjustedPolygon[$i]['x'].', '.$adjustedPolygon[$i]['y'].'<br />';
$rotatedPolygon[$i]=rotatePoint($adjustedPolygon[$i],$rotateAmt);
// echo 'after rotatePoint '.$i.'='.$rotatedPolygon[$i]['x'].', '.$rotatedPolygon[$i]['y'].'<br />';
$rotatedPolygon[$i]['x']=$rotatedPolygon[$i]['x']-$adjustment['x'];
$rotatedPolygon[$i]['y']=$rotatedPolygon[$i]['y']-$adjustment['y'];
}
感谢您的帮助。让我知道我是否应该把它放在 math.stackexchange.com 上
【问题讨论】:
-
你能做一个 JSFiddle 吗?
-
你从哪里得到的代码?
-
这段代码没问题。问题一定出在其他地方。
-
我编辑添加了完整的代码。我知道输入数组是正确的。我想把它移到0,通过算法运行每个点,并输出旋转后的数组。