it编程 > 游戏开发 > unity

【Unity实现背包拖拽功能 】

112人参与 2024-08-06 unity

unity实现背包拖拽功能 可以实现背包拖拽交换位置、合成 等一系列功能的实现

using system;
using system.collections;
using system.collections.generic;
using unityengine;
using unityengine.eventsystems;

public class dragctrl : monobehaviour, ibegindraghandler, ienddraghandler, idraghandler, icanvasraycastfilter
{
    public gradeitem item;
    private transform nowparent;
    private bool israycastlocationvalid = true;//默认射线不能穿透物体
    public transform iconlist;//存放拖拽物体的公共节点
    public bool israycastlocationvalid(vector2 sp, camera eventcamera)
    {
        return israycastlocationvalid;
    }
    /// <summary>
    /// 开始拖动
    /// </summary>
    /// <param name="eventdata"></param>
    public void onbegindrag(pointereventdata eventdata)
    {
        oclickbtn();
        this.transform.setaslastsibling();//将被拖拽的物体设置为最后渲染
        nowparent = this.transform.parent;//保存最初始的位置
        israycastlocationvalid = false;//设置射线穿透
        transform.setparent(iconlist);//将拖拽的物体放在公共父节点下
        //下面可以放拖拽时的功能
    }

    /// <summary>
    /// 拖动中
    /// </summary>
    /// <param name="eventdata"></param>
    public void ondrag(pointereventdata eventdata)
    {
        vector2 v2 = vector2.zero;
        recttransformutility.screenpointtolocalpointinrectangle(iconlist.getcomponent<recttransform>(), input.mouseposition,staffuimgr.instance.mcamera, out v2);将拖拽时的屏幕坐标转换为公共节点下的局部坐标,不转换将看不见拖拽物体
        transform.localposition = v2;
    }

    /// <summary>
    /// 拖动结束
    /// </summary>
    /// <param name="eventdata"></param>
    /// <exception cref="system.notimplementedexception"></exception>
    public void onenddrag(pointereventdata eventdata)
    {
        //transform.find("select").gameobject.setactive(false);
        gameobject go = eventdata.pointercurrentraycast.gameobject;
        if(go != null)
        {
            if (go.transform.parent.name == "iconitem")
            {
                //放拖动结束需要实现的功能
            }
            else
            {
            	//拖动失败  拖动物体复原
                transform.setparent(nowparent);
                transform.position = nowparent.position;
            }
        }
        else
        {
        	//拖动失败  拖动物体复原
            transform.setparent(nowparent);
            transform.position = nowparent.position;
        }
        israycastlocationvalid = true;//射线不可以穿透物体
    }


   
(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

Unity 制作简单的轮播图

08-06

Unity基础 粒子系统

08-06

Unity3D教程

08-06

Unity内置后处理Post Processing

08-06

Unity 在Game输出Console内容

08-06

Unity怎么通过WIFI连接真机调试

08-06

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论