【问题标题】:Raycast is only working when I move at a moderate speed?Raycast 仅在我以中等速度移动时才有效?
【发布时间】:2021-10-12 02:33:36
【问题描述】:

我曾经使用 raycast 来破坏游戏中的东西,除非我移动得很快,否则它不起作用我将这个脚本统一附加到我的主摄像机上,谁能告诉我我做错了什么,因为我希望它发生无论你是否静止不动。


void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector2 mousePos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
            RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.zero, 100f);
            
            if (hit.collider.tag == "Ground")
            {
                Debug.Log("You clicked a block and tried to break it!");
                Destroy(hit.collider.gameObject);
            }
        }
    }

【问题讨论】:

  • 您没有遇到错误吗?你假设命中对象总是被填充,你应该首先检查是否不为空。

标签: c# unity3d raycasting


【解决方案1】:

Physics2D.Raycast 应该在 FixedUpdate 中使用,因为在那里计算物理。物理与帧无关。

【讨论】:

  • 我试过这样做,但它给了我同样的问题,没有区别。
【解决方案2】:

来自docs

RaycastHit2D Raycast(Vector3 origin, Vector3 direction, float distance)

您已为光线投射指定了一个方向。

一般情况下,您应该使用ScreenPointToRay 并将光线原点和方向传递给Raycast

【讨论】:

    猜你喜欢
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    • 2019-12-19
    相关资源
    最近更新 更多