码迷,mamicode.com
首页 > 其他好文 > 详细

NGUI的背包制作

时间:2014-11-26 16:37:07      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   os   for   on   2014   log   

NGUI制作背包很是方便,听紫龙慢慢道来:


这次比较简单,但是需要理解代码。首先建立bg-——背景,然后是Grid,然后Grid下面是cell,cell是背包的格子,然后里面放物品——wuping。wuping下面放个Label,Label里面写数字,暂时表示物品数量。一切都如图所示;

bubuko.com,布布扣


之后給wuping加一个脚本,脚本命名也为wuping ,下面是详细代码:

话说这段代码要理解一下,wuping继承的是UIDragDropItemz这是NGUI本来就有的,从if开始是自己写的。

说明一下在写代码之前要给cell和wuping都加tag,我给cell加的tag名字是cell,wuping加的tag名字为wuping。从下面代码就可以看到了。

这是把物品放到格子里的代码:

using UnityEngine;
using System.Collections;

public class wuping : UIDragDropItem {

    protected override void OnDragDropRelease(GameObject surface)
    {
        base.OnDragDropRelease(surface);
        print(surface);


        if (surface.tag == "cell")//若拖到的是空格子里
        {
            this.transform.parent = surface.transform;//拖动wuping放到cell时,让格子(现在的是surface也就是cell)成为所选物体的parent。
            this.transform.localPosition = Vector3.zero;//所选物体的local坐标,实现的是放到格子里是放到格子位置的中心。

        }
        //else if (surface.tag == "wuping")
        //{
        //    Transform parent = surface.transform.parent;
        //    surface.transform.parent = this.transform.parent;
        //    surface.transform.localPosition = Vector3.zero;

        //    this.transform.parent = parent;
        //    this.transform.localPosition = Vector3.zero;
       // }
    }
}

下面是若cell里已经有了wuping的情况就把两个物品交换的代码:


using UnityEngine;
using System.Collections;

public class wuping : UIDragDropItem {

    protected override void OnDragDropRelease(GameObject surface)
    {
        base.OnDragDropRelease(surface);
        print(surface);


        if (surface.tag == "cell")//若拖到的是空格子里
        {
            this.transform.parent = surface.transform;//拖动wuping放到cell时,让格子(现在的是surface也就是cell)成为所选物体的parent。
            this.transform.localPosition = Vector3.zero;//所选物体的local坐标,实现的是放到格子里是放到格子位置的中心。

        }
        else if (surface.tag == "wuping")//若拖到的是已经放了物体的格子里,也就是格子里已有wuping了。
        {
            Transform parent = surface.transform.parent;
            surface.transform.parent = this.transform.parent;//保留还没有移动wuping前wuping目前所在的cell
            surface.transform.localPosition = Vector3.zero;//保留还没有移动wuping前wuping目前所在的cell的位置

            this.transform.parent = parent;//新的cell成为移动后的wuping的cell(也就是交换wuping)
            this.transform.localPosition = Vector3.zero;
        }
    }
}

然后把脚本添加给wuping即可运行:

bubuko.com,布布扣


NGUI的背包制作

标签:blog   http   io   ar   os   for   on   2014   log   

原文地址:http://blog.csdn.net/alayeshi/article/details/41516465

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!