[英]Rotate an object for placement in a 2d array
我正在尝试创建一个基本的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
我想出了如何从这里的另一块板上完成这项工作。
我要做的第一件事是将对象存储在二维数组中,例如
1 2 1 1
1 1 1 1
然后我转置数组,剩下这个数组
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);
}
}
}
}
首先要考虑的一件事是旋转对象只需要实现一个旋转功能:在一个方向上旋转90度。 其他旋转仅重复此操作2或3次,从而简化了逻辑。
您需要考虑从原始数组到旋转数组的两种映射:
1很简单:交换尺寸。 旋转的1x4变为4x1。
2取决于您的实现,但是如果您使用2d坐标[x, y] => [y, -x] or [-y, x]
取决于旋转方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.