简体   繁体   English

尝试使用数学旋转多边形

[英]Trying to rotate a polygon using math

I have a school assignment where I'm supposed to (among other things) rotate a polygon. 我有一个学校作业,应该(除其他事项外)旋转多边形。 I can not use any premade rotate functions, so I have an array of points. 我不能使用任何预制的旋转功能,所以我有很多点。 The array is set up like this: 数组设置如下:

intArray[2][amount_of_points] where intArray[0] equals the points x coordinate, and intArray[1] holds the y coordinates. intArray[2][amount_of_points] ,其中intArray[0]等于点x坐标,而intArray[1]保存y坐标。

    //x=pivot point x coordinate, y = pivot point y coordinate.
public int[][] rotate(int[][]matrix,int x, int y, double degrees){

    double s=Math.sin(degrees);
    double c=Math.cos(degrees);


    for (int i=0;i<matrix.length;i++){

        //translate to origin
        int px=matrix[0][i]-x;
        int py=matrix[1][i]-y;

        //rotate
        double xnew = (px*c)-(py*s);
        double ynew = (px*s)+(py*c);

        //translate back
        px=(int)((xnew+x)+0.5);
        py=(int)((ynew+y)+0.5);

        matrix[0][i]=px;
        matrix[1][i]=py;
    }

This is my code so far, and it is definitely not working out for me. 到目前为止,这是我的代码,对于我来说绝对不可行。 I tried to trim the code as much as I could. 我试图尽可能地减少代码。 Any help would mean a lot! 任何帮助都将非常重要!

edit: I'm not getting any errors when I run the code, no exceptions etc. The only problem is that the polygon isn't rotating the way I intend it to. 编辑:运行代码时没有出现任何错误,也没有异常等。唯一的问题是多边形没有按照我的预期旋转。

I've made a test polygon: 我做了一个测试多边形:

polyArray = new int [2][3];
    polyArray[0][0]=400;
    polyArray[1][0]=200;
    polyArray[0][1]=300;
    polyArray[1][1]=500;
    polyArray[0][2]=500;
    polyArray[1][2]=500;

Which I draw in a JPanel, then I run this array through the rotation method like this: polyArray=mm.rotate(polyArray, polyArray[0][0], polyArray[1][0], Math.PI); 我在一个JPanel中绘制,然后通过如下旋转方法运行该数组:polyArray = mm.rotate(polyArray,polyArray [0] [0],polyArray [1] [0],Math.PI);

Using the top point as pivotpoint. 使用最高点作为枢轴点。 The whole polygon is then deformed. 然后整个多边形变形。

Although still not very clear on question, I feel your problem is with the loop. 尽管问题仍然不是很清楚,但我认为您的问题出在循环中。 matrix.length is 2 . matrix.length is 2 So, the code never uses these : 因此,代码从不使用这些:

polyArray[0][2]=500;
polyArray[1][2]=500;

If you change the condition as below, it should work : 如果您按以下方式更改条件,则它应该可以工作:

for (int i=0;i<matrix[0].length;i++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM