Unity使用UGUI实现某个UI控件进入某个区域后按格移动

最近项目需求,需要实现类似于暗黑破坏神背包那样的按格存放功能,在此之前先实现物体按格进入背包,然后触发相应的事件,减少后续的归位操作。

图片控制代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ImgControl : MonoBehaviour
{
    public BackGroundControl m_backGround;              //懒得弄了直接拖吧

    private bool m_isChoosed;

    private Vector3 m_mouseOldPos;
    private Vector3 m_transNextPos;
    private Vector3 m_transToMouseOffset;

    void Start()
    {
        m_isChoosed = false;

    }

    void Update()
    {
        if (m_isChoosed)
        {
            //先计算物体要移动的下个点
            m_transNextPos = this.transform.position + Input.mousePosition - m_mouseOldPos;
            m_transNextPos = m_backGround.ConfirmImgPos(m_transNextPos);

            //计算鼠标此时应在的位置
            m_mouseOldPos = m_transNextPos + m_transToMouseOffset;

            this.transform.position = m_transNextPos;
        }

        //抬起鼠标则不能移动
        if (Input.GetMouseButtonUp(0))
        {
            m_isChoosed = false;
        }
    }

    /// 
    /// 选定图片,懒得绑定了,面板拖动
    /// 
    public void ChooseImg()
    {
        m_mouseOldPos = Input.mousePosition;
        m_transToMouseOffset = Input.mousePosition - this.transform.position;
        m_isChoosed = true;
        m_backGround.ConfirmRect();
    }
}

背景面板控制代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BackGroundControl : MonoBehaviour
{
    public RectTransform m_imgRect;         //图片的Rect

    private Rect m_backGroundRect;          //放置区域的Rect
    private int m_boxWidth = 10;            //格格宽
    private int m_boxHeight = 10;

    /// 
    /// 确定图片位置
    /// 
    /// 
    /// 
    public Vector3 ConfirmImgPos(Vector3 pos)
    {
        if (m_backGroundRect.Contains(pos))
        {
            //计算鼠标位置和边界的差值
            float x = pos.x - m_backGroundRect.x;
            float y = pos.y - m_backGroundRect.y;

            //求出移动的倍数
            int xRatio = Mathf.CeilToInt(x / m_boxWidth);
            int yRatio = Mathf.CeilToInt(y / m_boxHeight);

            pos.x = m_backGroundRect.x + xRatio * m_boxWidth;
            pos.y = m_backGroundRect.y + yRatio * m_boxHeight;
        }
        return pos;
    }

    /// 
    /// 确定区域矩形
    /// 
    public void ConfirmRect()
    {
        Rect transRect = this.GetComponent().rect;
        Rect imgRect = m_imgRect.rect;

        m_backGroundRect.Set(this.transform.position.x + transRect.x + imgRect.x,
           this.transform.position.y + transRect.y + imgRect.y,
           transRect.width + imgRect.width, transRect.height + imgRect.height);
    }
}

源程序:源程序

你可能感兴趣的:(Unity,Unity3D,C#)