Coordinate Algorithm - Rotate around the center

雨燕双飞 提交于 2019-12-19 11:23:08

问题


By looking at this image I think you will understand my problem pretty well:

(image removed - url no longer valid, returns advertising now)

So basically I want a function that takes an object as parameter and gives this object the correct coordinates based on how many objects I've added before.

Let's say I would add all these objects to an array:

objectArray[]

Each time I add a new object: objectArray.add(object)

The object.x and object.y coordinates will be set based on some algorithm:

object.x = ?
object.y = ?

(I'm working in Java)

Thanks for any help.


回答1:


Here's the closed-form solution that doesn't rely on a loop... I'm not handy with Java, so it's in C#, but it uses basic operations.

static void SpiralCalc(int i) {
    i -= 2;
    // Origin coordinates
    int x = 100, y = 100;
    if (i >= 0) {
        int v = Convert.ToInt32(Math.Truncate(Math.Sqrt(i + .25) - .5));
        int spiralBaseIndex = v * (v + 1);
        int flipFlop = ((v & 1) << 1) - 1;
        int offset = flipFlop * ((v + 1) >> 1);
        x += offset; y += offset;
        int cornerIndex = spiralBaseIndex + (v + 1);
        if (i < cornerIndex) {
            x -= flipFlop * (i - spiralBaseIndex + 1);
        } else {
            x -= flipFlop * (v + 1);
            y -= flipFlop * (i - cornerIndex + 1);
        }
    }
    // x and y are now populated with coordinates
    Console.WriteLine(i + 2 + "\t" + x + "\t" + y);
}


来源:https://stackoverflow.com/questions/9135823/coordinate-algorithm-rotate-around-the-center

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!