旋转对象以放置在2d数组中

时间:2015-09-16 20:49:35

标签: java c# arrays rotation 2d-games

我正在尝试创建一个基本的RTS样式网格。网格工作得很好,我可以通过将数字设置为0以外的任何值来放置对象。

这很容易。目前我试图允许放置的每个对象旋转。可以旋转的物体可以是任何尺寸,例如1x1,2x1,3x4等,所有对象都有一个需要随对象一起旋转的入口块。

例如。

我的网格是空的

0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0

我可以放置一个如下所示的对象:

1 2 1
1 1 1

会像

一样
0 0 0 0 0 0 0
0 1 2 1 0 0 0       1 2 1
0 1 1 1 0 0 0       1 1 1
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0

但是在旋转时它应该像

一样
1 2 1 0 1 1 0     1 2 1   1 1  
1 1 1 0 1 2 0     1 1 1   1 2  
0 0 0 0 1 1 0             1 1  
0 1 1 0 0 0 0       1 1        
0 2 1 0 1 1 1       2 1   1 1 1
0 1 1 0 1 2 1       1 1   1 2 1

我试图弄清楚如何在代码中实现这一点,因为对象可以是不同的形状? :(

1 1 2 1    1 1 1    1 1 1 1    1 1 1
1 1 1 1    1 1 1    1 1 1 1    2 1 1
1 1 1 1    1 1 2    1 2 1 1    1 1 1
           1 1 1               1 1 1

2 个答案:

答案 0 :(得分:1)

我想出了如何从这里的另一个板上完成这个。

我做的第一件事就是将对象存储在二维数组中,例如

1 2 1 1
1 1 1 1

然后我transposed数组离开我这个数组

1 1
2 1
1 1
1 1

然后我旋转每一行,留下我最后一个旋转的物体

1 1
1 2
1 1
1 1

对于180多次旋转,我只是再次使用这种技术来达到所需的旋转:)

我在Unity3D C#中的最终数组类

using UnityEngine;
using System.Collections;

namespace Arrays {

    public class Array {

        public static int[,] Rotate(int[,] array)
        {
            return Rotate90 (array);
        }

        public static int[,] Rotate90(int[,] array)
        {
            return RotateArrayRow( Transpose(array) );
        }

        public static int[,] Rotate180(int[,] array)
        {
            return Rotate90(Rotate90(array));;
        }

        public static int[,] Rotate270(int[,] array)
        {
            return Rotate90(Rotate180(array));;
        }

        private static int[,] RotateArrayRow(int[,] array){
            int x = array.GetLength(1);
            int y = array.GetLength(0);
            int[,] temp = new int[y,x];
            for(int i=0; i<y; i++)
            {
                for(int j=0; j<x; j++)
                {
                    temp[i,x-j-1] = array[i,j];
                }
            }
            return temp;
        }

        public static int[,] Transpose(int[,] array){
            int x = array.GetLength(1);
            int y = array.GetLength(0);
            int[,] temp = new int[x,y];

            for(int i=0; i<y;i++){
                for(int j=0; j<x; j++){
                    temp[j,i] = array[i,j];
                }
            }

            return temp;
        }

        public static void Log(int[,] array){
            for(int i=0; i<array.GetLength(0); i++)
            {
                string line = "";
                for(int j=0; j<array.GetLength(1); j++)
                {
                    line += array[i,j] + " ";
                }
                Debug.Log(line);
            }
        }
    }
}

答案 1 :(得分:0)

首先要考虑的一件事是,要旋转对象,您只需要实现一个旋转功能:在一个方向上旋转90度。其他旋转只需重复此操作2到3次,简化了逻辑。

您需要考虑从原始阵列到旋转阵列的两个映射:

  1. 维度如何映射?
  2. 指数如何映射?
  3. 1很简单:交换尺寸。旋转的1x4变为4x1。

    2取决于您的实施,但如果您使用的是2d坐标[x, y] => [y, -x] or [-y, x],具体取决于旋转方向。