说明:
最近闲的蛋疼,没事干的时候就写一写小游戏,O(∩_∩)O哈哈哈~
这是一个最基础版基于Unity5.2.1版本写的一个拼图游戏,所用的到知识全来自与Unity中,没有什么特别之处,可以发布移动及PC多平台
界面如下所示:
未运行状态:
运行中状态:
游戏完成状态:
代码共享如下所示:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class MyPingTu : MonoBehaviour
{
ItemImg[] itemImg;
Sprite[] UIShowImage;
int length = 0;
int sqrt = 0;
void Start()
{
var RSLoadAllImages = Resources.LoadAll("Texture1");
length = transform.childCount;
sqrt = (int)Mathf.Sqrt(length);
//childLength-1——其中某一张为空白,即后下角为空白
UIShowImage = new Sprite[length];
for (int i = 0; i < length; i++)
{
UIShowImage[i] = (Sprite)RSLoadAllImages[i + 1];
}
//初始化图片的id,col,row
InitItemImg(length);
InitShow();
}
/// <summary>
/// 初始化图片id,col,row
/// </summary>
void InitItemImg(int count)
{
itemImg = new ItemImg[length];
for (int i = 0; i < count; i++)
{
itemImg[i] = new ItemImg();
itemImg[i]._id = i;
itemImg[i]._col = i / sqrt;
itemImg[i]._row = i % sqrt;
}
}
void InitShow()
{
//初始化显示图片
for (int i = 0; i < UIShowImage.Length; ++i)
{
var t = transform.GetChild(i);
t.GetComponent<Image>().sprite = UIShowImage[i];
//指定Sprite
itemImg[i]._sprite = t.GetComponent<Image>().sprite;
//指定Obj
itemImg[i]._Obj = t.gameObject;
var item = itemImg[i];
itemImg[i]._Obj.GetComponent<Button>().onClick.AddListener(delegate () {
this.OnClickEvent(item);
});
}
itemImg[length - 1]._Obj.GetComponent<Image>().sprite = null;
itemImg[length - 1]._sprite = null;
}
void OnClickEvent(ItemImg item)
{
if (canMovie(item))
{
var t = NoneImage();
t._sprite = item._sprite;
t._Obj.GetComponent<Image>().sprite = item._Obj.GetComponent<Image>().sprite;
item._sprite = null;
item._Obj.GetComponent<Image>().sprite = null;
}
if (Success())
{
Debug.Log("胜利");
}
}
/// <summary>
/// 判断是否可以移动
/// </summary>
bool canMovie(ItemImg item)
{
if (item._sprite == null)
return false;
var t = NoneImage();
if ((t._col == item._col - 1 && t._row == item._row) || (t._col == item._col + 1 && t._row == item._row) || (t._col == item._col && t._row == item._row + 1) || (t._col == item._col && t._row == item._row - 1))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 获取空白图片
/// </summary>
ItemImg NoneImage()
{
for (int i = 0; i < length; i++)
{
if (itemImg[i]._sprite == null)
{
return itemImg[i];
}
}
return null;
}
/// <summary>
/// 判断胜利
/// </summary>
bool Success()
{
for (int i = 0; i < length - 1; i++)
{
if (itemImg[i]._Obj.GetComponent<Image>().sprite != null)
{
if (itemImg[i]._Obj.GetComponent<Image>().sprite.name != "Image_01_" + i.ToString())
return false;
}
}
return true;
}
}
public class ItemImg
{
public int _col;
public int _row;
public int _id;
public GameObject _Obj;
public Sprite _sprite;
}
可执行程序下载地址:
链接:http://pan.baidu.com/s/1eRNKx94 密码:7tgo
Unity中布局: