You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Godot引擎:RayCast2D射线未投射至正确位置

解决Godot中RayCast2D投射位置错误的问题

核心原因:坐标系不匹配

你直接传入的fire_position是屏幕坐标系的位置,但RayCast2D.set_cast_to()要求的是相对于该节点的局部坐标系偏移量,两者坐标系不匹配导致射线位置错误。

正确处理步骤

  • 先将鼠标点击位置转换为世界坐标系坐标
    用Godot提供的API直接获取鼠标的世界位置:

    var mouse_world_pos = get_global_mouse_position()
    
  • 再将世界坐标转换为RayCast2D节点的局部偏移量
    RayCast2D的cast_to是从自身节点位置出发的局部偏移,需要通过节点的坐标转换方法计算:

    var local_fire_offset = $RayCast2D.to_local(mouse_world_pos)
    $RayCast2D.set_cast_to(local_fire_offset)
    
  • 可选:强制更新射线检测
    如果设置后射线没有立即生效,手动触发更新:

    $RayCast2D.force_raycast_update()
    

完整示例代码

func _input(event):
    if event is InputEventMouseButton and event.pressed and event.button_index == BUTTON_LEFT:
        # 获取鼠标世界坐标
        var mouse_world = get_global_mouse_position()
        # 转换为RayCast2D的局部偏移
        var local_offset = $RayCast2D.to_local(mouse_world)
        # 设置射线目标
        $RayCast2D.set_cast_to(local_offset)
        # 立即更新射线状态
        $RayCast2D.force_raycast_update()

内容的提问来源于stack exchange,提问作者AbsolutePickle42

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 05:15:31