我正在尝试创建一个基本的 RTS 风格网格。网格工作完美,我可以通过将数字设置为 0 以外的任何值来放置对象。
这是最简单的部分。目前我试图允许放置的每个对象旋转。可以旋转的对象可以是任何大小,例如1x1、2x1、3x4等,所有对象都有一个需要随对象旋转的入口 block 。
例如。
我的网格是空的
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
最佳答案
我想出了如何从这里的另一个板上实现这一点。
我做的第一件事是将对象存储在二维数组中,例如
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);
}
}
}
}
关于java - 旋转对象以放置在二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32618414/