Godot 3.5调用parse_input_event后鼠标位置重置为(0,0)的问题
解决思路:手柄摇杆移鼠标+模拟点击后位置重置问题
问题根源
模拟鼠标点击时未正确设置事件的位置参数,或依赖系统维护的鼠标位置(模拟事件后系统可能错误重置该值),导致后续摇杆移动时从(0,0)开始计算。
具体解决方案
1. 手动维护鼠标位置变量
不要依赖get_global_mouse_position()或系统返回的位置,自己定义变量跟踪当前鼠标坐标,彻底避免系统状态干扰。
2. 确保模拟点击事件的位置正确
创建InputEventMouseButton时,必须将position和global_position设为当前维护的鼠标位置,而非默认的(0,0)。
3. 基于维护的位置计算摇杆移动
摇杆输入是增量值,每次移动都基于手动维护的位置累加,再更新视口鼠标位置。
代码示例(GDScript)
# 手动维护当前鼠标位置 var current_mouse_pos: Vector2 = Vector2.ZERO func _ready(): # 初始化鼠标位置为当前视口鼠标位置 current_mouse_pos = get_viewport().get_mouse_position() func _process(delta): # 获取摇杆输入(需先在项目设置中映射手柄输入到对应动作) var stick_input = Input.get_vector("left_stick_left", "left_stick_right", "left_stick_up", "left_stick_down") # 摇杆死区处理,过滤微小输入 if stick_input.length() > 0.1: var move_speed = 200.0 * delta # 基于维护的位置计算新坐标 current_mouse_pos += stick_input * move_speed # 限制鼠标在视口范围内 current_mouse_pos.x = clamp(current_mouse_pos.x, 0, get_viewport().size.x) current_mouse_pos.y = clamp(current_mouse_pos.y, 0, get_viewport().size.y) # 更新视口鼠标位置 get_viewport().warp_mouse(current_mouse_pos) func _input(event): # 处理A键点击 if event.is_action_pressed("a_button"): # 创建鼠标按下事件 var left_click_press = InputEventMouseButton.new() left_click_press.button_index = BUTTON_LEFT left_click_press.pressed = true # 关键:设置事件位置为当前维护的鼠标坐标 left_click_press.position = current_mouse_pos left_click_press.global_position = current_mouse_pos Input.parse_input_event(left_click_press) # 创建鼠标释放事件(避免一直处于按下状态) var left_click_release = InputEventMouseButton.new() left_click_release.button_index = BUTTON_LEFT left_click_release.pressed = false left_click_release.position = current_mouse_pos left_click_release.global_position = current_mouse_pos Input.parse_input_event(left_click_release)
额外注意事项
- 死区处理:避免摇杆微小输入导致鼠标无意义抖动。
- 视口范围限制:防止鼠标移出游戏窗口边界。
- 完整的点击事件:必须同时发送按下和释放事件,否则会出现鼠标一直按住的异常状态。
内容的提问来源于stack exchange,提问作者Andrejs Klavins
相关产品推荐
相关产品推荐

