这一个月开始了我的Unity3D的学习之旅,好兴奋啊,听说学好了Unity,工资是很高的,冲着这,俺就要悬梁刺股了,好吧,今天写了一个拼图游戏,以下是纯代码,不过程序有bug(原谅下,初学,水平有限),不过要让程序跑起来,还得自己在Unity根目录下加一个资源文件夹,并在资源文件夹下放上相应的图片,名字在程序中。文末有截图。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Demo_02 : MonoBehaviour
{
const int n = 3;
List<Rect_Value> list;
Rect_Value rv;
Point point = new Point();
void Start ()
{
list = new List<Rect_Value>();
int temp = 50;
point.m = (n-1)*temp;
point.n = (n-1)*temp;
for(int i = 0;i<n*n;i++)
{
rv = new Rect_Value();
rv.rect = new Rect((i/n)*temp,(i%n)*temp,temp,temp);
if(i<n*n-1)
{
int item;
flag:while(true)
{
item = Random.Range(1,n*n);
for(int j= 0;j<list.Count;j++)
{
if(item == list[j].x)
{
goto flag;
}
}
switch(item)
{
case 1:
rv.texture2d = (Texture2D)Resources.Load("123_01");
break;
case 2:
rv.texture2d = (Texture2D)Resources.Load("123_02");
break;
case 3:
rv.texture2d = (Texture2D)Resources.Load("123_03");
break;
case 4:
rv.texture2d = (Texture2D)Resources.Load("123_04");
break;
case 5:
rv.texture2d = (Texture2D)Resources.Load("123_05");
break;
case 6:
rv.texture2d = (Texture2D)Resources.Load("123_06");
break;
case 7:
rv.texture2d = (Texture2D)Resources.Load("123_07");
break;
case 8:
rv.texture2d = (Texture2D)Resources.Load("123_08");
break;
}
rv.x = item;
break;
}
list.Add(rv);
}
}
Rect_Value rv2 = new Rect_Value();
rv2.rect = new Rect((n-1)*temp,(n-1)*temp,temp,temp);
rv2.x = n*n;
list.Add(rv2);
}
void OnGUI()
{
int count = 1;
foreach(Rect_Value rv2 in list)
{
if(count < n*n)
{
Rect temp2=new Rect();
if(GUI.Button(rv2.rect,rv2.texture2d)
&&Mathf.Abs(rv2.rect.x-point.m+rv2.rect.y-point.n)==50
&&Mathf.Abs(rv2.rect.x-point.m-rv2.rect.y+point.n)==50)
{
temp2.x = rv2.rect.x;
rv2.rect.x = point.m;
point.m = temp2.x;
temp2.y = rv2.rect.y;
rv2.rect.y = point.n;
point.n = temp2.y;
}
count++;
}
}
}
}
public class Rect_Value
{
public Rect rect;
public int x;
public Texture2D texture2d;
}
public class Point
{
public float m;
public float n;
}
资源文件: