屏幕坐标转世界坐标

前提:

1.修改 渲染模式

Render Mode 为Screen Space - Camera

2. 修改 投影模式

Projection  为 Perspective (透视模式)

persp 透视模式-2D

Los    正交模式-3D

屏幕坐标 转为 世界坐标

方法一:

将鼠标的屏幕坐标 转为 世界坐标(物体随着鼠标移动)

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

public class DragManager : ListenerEvent
{
    public GameObject target;
    public Camera UIcamera;

    void Start()
    {
        target.SetActive(false);
    }
    void Update()
    {
      
        if (Input.GetMouseButton(0)&&!SysDefault.isMove)
        {
            target.SetActive(true);
            // 将鼠标屏幕坐标转换为世界坐标
            Vector3 mousePosition = Input.mousePosition;
            // 设置鼠标位置的 z 坐标与 UI 相机相距的距离
            mousePosition.z = UIcamera.nearClipPlane; // 你可以根据需要调整这个值(100)
            Vector3 worldPosition = UIcamera.ScreenToWorldPoint(mousePosition);
            target.transform.position = worldPosition;
        }
    }
  
}
  • mousePosition.z: 设置鼠标位置的 z 坐标为相机的近裁剪面距离 
  • ScreenToWorldPoint(vector3 position): 将鼠标的屏幕坐标转换为世界坐标。

方法二:

在拖拽物体时,将屏幕坐标转为世界坐标

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems; // 导入命名空间 可使用拖拽 相关的接口

public class DragHandle : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler,IPointerDownHandler,IPointerUpHandler
{
   //拖拽中
   public void OnDrag(PointerEventData eventData)
    {
        Vector3 worldPos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rect, eventData.position, eventData.pressEventCamera, out worldPos))
        {
            transform.position = worldPos;
        }
        //transform.position = Input.mousePosition;
        
    }
}
  • public static bool ScreenPointToWorldPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector3 worldPoint);
  • RectTransformUtility.ScreenPointToWorldPointInRectangle(rect, eventData.position, eventData.pressEventCamera, out worldPos)
  1. eventData为pressEventCamera,可以正常使用
  2. 如果eventData为enterEventCamera,拖动的速度加快会消失在 屏幕上,如果为其他物体的子级将不会出现问题,但父级要充满屏幕

(方法二:未深入了解)

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值