Unity3d

前期实现了背包基本的存储功能,现在开始构建背包物品的移动及调换功能,具体思路如下:

①读取现有物品所在的格子信息。

②对移动目标地点进行判断(即surface的Tag):

如果surface的Tag为空,则使物品的局部坐标归零;

如果surface的Tag不为空,分为几个情况考虑:

1.Tag为背包格子:说明移动地点为空格子,所以讲物品信息赋值到目标下,清除现有信息即可;

2.Tag为背包物品:说明移动地点为有物品格子,将两格子的信息交换即可;

3.Tag为其他物品:说明非常规移动,将物品的位移信息清零。

脚本添加如下:

Class Inventory_item

{

    void ResetPosition( )

    {

        tranform.localPostion = Vector3.zero;

    }

    protected override void OnDragDropRelease(GameObject surface)

    {

        base.OnDragDropRelease(surface);

        if( surface != null )

        {

             if( surface.Tag == "Inventory_grid")          

            {

                if(surface = this.transform.parent.gameObject)

                {

                    ResetPosition();

                }

                else

                {

                    InventoryGrid nowgrid = this.transform.parent.GetCompnent<InventoryGird>();

                    this.tranform.parent = surface.transform;

                    ResetPosition();

                    InventoryGrid newgrid = surface.GetCompnent<InventoryGrid>();

                    newgrid.SetId(nowgrid.id,nowgrid.num);

                    nowgrid.ClearInfo();

                }

            }

            else if( surface.Tag == "InventoryItem" )

            {

                 InventoryGird grid1 = this.transform.parent.GetCompnent<InventoryGrid>();

                 InventoryGrid grid2 = surface.transform.parent.GetCompnent<InventoryGrid>();

                 int id = grid1.id; int num = grid1.num;

                 grid1.SetId(grid2.id,grid2.num);

                 grid2.SetId(id,num);

            }

            else

            {

                ResetPositon();

            }

        }

        else

        {

             ResetPosition();

        }

    }

}

上述功能完成了物品得添加和移动,现在开始实现物品栏的显示和取消。

前期已经定义了Show方法和Hide方法,但是我们只有一个按键,那就是背包按钮,所以需要再添加一个方法,添加脚本如下:

Class Inventory

{

    private bool isShow = false;

    void Show()

    {

        isShow = true;

        tween.playForward();

    }

    void Hide()

    {

        isShow = false;

        tween.playReserved();

    }

    public void TransformState()

    {

        if(isShow){Hide();}

        else{Show();}

    }

}

将该方法注册到按钮即可。

原文地址:https://www.cnblogs.com/yanbenxin/p/5838436.html