Raycast 仅在我以中等速度移动时才有效?

Posted

技术标签:

【中文标题】Raycast 仅在我以中等速度移动时才有效?【英文标题】:Raycast is only working when I move at a moderate speed? 【发布时间】: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);
            
        
    

【问题讨论】:

您没有遇到错误吗?你假设命中对象总是被填充,你应该首先检查是否不为空。 【参考方案1】:

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

【讨论】:

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

来自docs:

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

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

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

【讨论】:

以上是关于Raycast 仅在我以中等速度移动时才有效?的主要内容,如果未能解决你的问题,请参考以下文章