Unity3D 鼠标拖动地图实现

1.鼠标按下记录鼠标位置;

2.拖动时设置拖动偏移量;

代码如下:

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

public class BattleMap : MonoBehaviour
{
    // Start is called before the first frame update
    public Collider _mapCollider = null;
    //待拖动的单位
    public GameObject _contentNode = null;
    private Vector3 _beginPos;
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            _beginPos = this.getCurMouseOnScreenPos();
        }

        if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                if (hit.collider == _mapCollider)
                {
                    var curPos = this.getCurMouseOnScreenPos();
                    var offset = curPos - _beginPos;
                    _beginPos = curPos;
                    _contentNode.transform.position = _contentNode.transform.position + offset;
                }
            }
        }
    }

    Vector3 getCurMouseOnScreenPos() {
        Vector3 screenPosition;//将物体从世界坐标转换为屏幕坐标
        Vector3 mousePositionOnScreen;//获取到点击屏幕的屏幕坐标
        Vector3 mousePositionInWorld;//将点击屏幕的屏幕坐标转换为世界坐标

        screenPosition = Camera.main.WorldToScreenPoint(_contentNode.transform.position);

        //获取鼠标在场景中坐标
        mousePositionOnScreen = Input.mousePosition;

        //让鼠标坐标的Z轴坐标 等于 场景中游戏对象的Z轴坐标
        mousePositionOnScreen.z = screenPosition.z;

        //将鼠标的屏幕坐标转化为世界坐标
        mousePositionInWorld = Camera.main.ScreenToWorldPoint(mousePositionOnScreen);
        return new Vector3(mousePositionInWorld.x, mousePositionInWorld.y, mousePositionInWorld.z);
    }
}

你可能感兴趣的:(Unity3D,Unity3d拖动物体)