【问题标题】:Unity, C# - pointer using mouseUnity,C# - 使用鼠标指针
【发布时间】:2021-09-16 11:14:38
【问题描述】:

我目前正在研究一个指针,它可以直观地显示玩家当前指向的确切位置。这应该有两个功能:

  1. 指出屏幕中间
  2. 允许玩家与他指向的任何东西进行交互(因为指针有碰撞器)

代码:

public class MousePosition3D : MonoBehaviour {
[SerializeField] private Camera mainCamera;

private void Update()
{
    Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out RaycastHit raycastHit))
    {
        transform.position = raycastHit.point;
    }
}}

上面的代码所做的是将指针的 transform.position 设置在最近的有碰撞器的对象上。这很好用,但是当我向我的指针添加一个对撞机(以允许玩家与其他对象交互)时,它开始无限循环到我的 POV 所在的对象,因为每一帧它都与它自己的对撞机发生碰撞,不断改变位置。

参考视频: https://vimeo.com/606446838

有人知道如何解决这个问题吗?或者也许有更好的选择?我的目标是在屏幕中间放置一个指针(移动和相机旋转是分开完成的),让玩家与场景中的其他对象进行交互。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    将光标碰撞器设置为专用的Layer

    然后您可以使用例如忽略PhysicsRacast 中的这个特定层LayerMask

    // Configure this via the Isnpector and select only layers you want to hit 
    [SerializeField] private LayerMask layersToHit;
    
    private void Update()
    {
        Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
    
        if (Physics.Raycast(ray, out var raycastHit, Mathf.Infinity, layersToHit))
        {
            transform.position = raycastHit.point;
        }
    }
    

    或者只将你的层设置为忽略并使用

    // Configure this via the Isnpector and select only layers you want to ignore
    [SerializeField] private LayerMask layersToIgnore;
    
    private void Update()
    {
        Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
    
        // The "~" inverts the bitmask so we hit every layer except the ones selected in the mask
        // see https://docs.microsoft.com/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators#bitwise-complement-operator-
        if (Physics.Raycast(ray, out var raycastHit, Mathf.Infinity, ~layersToIgnore))
        {
            transform.position = raycastHit.point;
        }
    }
    

    【讨论】:

    • ~layersToHit,你的意思是写 !layersToHit 吗?
    • @Laurent no ... 我的意思是写~layersToHit ;)
    • 哦,这是一个位运算符,以前从未见过这个..谢谢你的启发! :)
    猜你喜欢
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2013-09-09
    • 2010-09-19
    • 1970-01-01
    • 2018-12-16
    相关资源
    最近更新 更多