Unity ScreenPointToRay 获取到的坐标不准确

奇奇怪怪的

  • 问题描述
  • 解决方案
  • 验证代码

Unity ScreenPointToRay 获取到的坐标不准确_第1张图片

问题描述

使用:Camera.main.ScreenPointToRay 将鼠标坐标转换成射线,然后通过:Physics.Raycast 获取到射线碰撞到的坐标,使用发现偏差比较大

解决方案

测试发现提高nearClip值可以解决该问题,大概是近裁面太小导致的精度问题~
Unity ScreenPointToRay 获取到的坐标不准确_第2张图片

验证代码

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

public class MousePosShow : MonoBehaviour
{
    public GameObject go;
    public GameObject lastHitGo;
    public Vector2 mousePos;
    public Vector2 goScreenPos;
   
    private void LateUpdate()
    {
#if ENABLE_INPUT_SYSTEM
        this.mousePos = Mouse.current.position.ReadValue();
#else
        var mousePos = Input.mousePosition;
#endif
        var ray= Camera.main.ScreenPointToRay(mousePos);
        if (Physics.Raycast(ray, hitInfo: out RaycastHit hitInfo,maxDistance:5000))
        {
            go.transform.position = hitInfo.point;
            var hitGo = hitInfo.transform.gameObject;
            if (lastHitGo != hitGo)
            {
                Debug.Log($"鼠标位置物体:{hitGo.name}", hitGo);
                lastHitGo = hitGo;
            }
        }
    }
    // Update is called once per frame
    void Update()
    {
        goScreenPos = Camera.main.WorldToScreenPoint(go.transform.position);
    }

}

你可能感兴趣的:(Unity,unity,ScreenPoint,Raycast)