坐标算法 - 绕中心坐标、算法、中心

2023-09-11 02:17:14 作者:陌上煙雨遥

通过看这个图片我想你会明白我的问题pretty的还有:

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

(图像中删除 - 网址不再有效,返回现在的广告)的

所以基本上我想要一个函数,根据我多少对象前添加需要一个对象作为参数,并给出了此对象的正确坐标。

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[]

我每次添加一个新的对象:     objectArray.add(对象)

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

object.x object.y 坐标将根据某种算法进行设置:

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

object.x = ?
object.y = ?

(我用Java开发的)

(I'm working in Java)

感谢您的帮助。

推荐答案

下面是一个不依赖于一个循环的封闭形式的解决方案...我不顺手的Java,因此它在C#中,但它使用基本操作。

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);
}