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
相关产品推荐
相关产品推荐

