资源大湿 发表于 2012-11-20 12:31

Unity3D拼图游戏部分代码




以前看过一段代码,说的是用鼠标在屏幕上拖动图片,但这段代码的扩展性不是很好,拖动任何位置,图片都会移动,且只能拖动一张图片。代码如下:

var Tu : Texture2D;
private var first = Vector2.zero;
private var second = Vector2.zero;
private var tempx : float = 0;
private var tempy : float = 0;
function OnGUI () {
GUI.DrawTexture (Rect (tempx, tempy, 50, 50),Tu);
   if(Event.current.type == EventType.MouseDown){
first = Event.current.mousePosition ;
}
   if(Event.current.type == EventType.MouseDrag){
second = Event.current.mousePosition ;
tempx += (second.x-first.x);
tempy += (second.y-first.y);
first = second;
}
}
function Update () {
}

  下面贴一段我修改后的代码,这段代码可以实现鼠标必须点击在图片上才能拖动图片,且可以拖动多张图片。拖动某一张图片时,其他图片不会收影响。利用这个思想,你可以实现其他的很多功能,不仅仅是拖动图片,例如可以实现判断图片是否拖入某一正确区域等等(拼图游戏可以用上述方法实现)。

var Tu : Texture2D;
var Tu1 : Texture2D;
private var first = Vector2.zero;
private var second = Vector2.zero;
private var tempx : float = 0;
private var temp1x : float = 500;
private var tempy : float = 0;
private var temp1y : float = 0;
var IsTu : int = 0;
var IsTu1 : int = 0;
function Update () {
}
function OnGUI () {
GUI.DrawTexture (Rect (tempx, tempy, 50, 50),Tu);
GUI.DrawTexture (Rect (temp1x, temp1y, 50, 50),Tu1);
if(Event.current.type == EventType.MouseDown){
first = Event.current.mousePosition ;
}
if(first.x > tempx && first.x < (tempx+50) && first.y > tempy && first.y < (tempy+50) ){
IsTu = 1;
}
if(first.x > temp1x && first.x < (temp1x+50) && first.y > temp1y && first.y < (temp1y+50) ){
IsTu1 = 1;
}
if(Event.current.type == EventType.MouseDrag && IsTu == 1){
second = Event.current.mousePosition ;
tempx += (second.x-first.x);
tempy += (second.y-first.y);
first = second;
IsTu = 0;
}
if(Event.current.type == EventType.MouseDrag && IsTu1 == 1){
second = Event.current.mousePosition ;
temp1x += (second.x-first.x);
temp1y += (second.y-first.y);
first = second;
IsTu1 = 0;
}
}

琳琳 发表于 2012-11-21 10:19

{:soso_e147:}

monery8 发表于 2012-11-21 16:46

{:5_387:}{:5_387:}支持 不错

胡椒孙 发表于 2012-11-28 12:03

至此已至此已{:soso__637689327989451638_2:}

胡椒孙 发表于 2012-11-29 10:30

我尝试了了一下,您没有给提供配合使用的贴图啊,我不知道该怎么弄出这个效果,烦躁

yilongli1989 发表于 2012-11-30 15:43

为什么弄个部分的,来个全的吧,谢谢

skyangel 发表于 2012-12-1 09:26

不错 收集到

hejianchun1314 发表于 2012-12-4 14:26

胡椒孙 发表于 2012-11-29 10:30 static/image/common/back.gif
我尝试了了一下,您没有给提供配合使用的贴图啊,我不知道该怎么弄出这个效果,烦躁

随便截个图50X50的贴图来就可以啊 加在那2个上面,我都弄出来了

ゅ星星点灯° 发表于 2012-12-7 15:40

支持一下 谢谢分享

kelvinhuang 发表于 2013-4-27 09:13


不错 不错 不错{:soso__3922851084632044791_6:}
页: [1] 2
查看完整版本: Unity3D拼图游戏部分代码