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

如何解决GDScript连接树莓派WebSocket异常及输入映射问题?

问题与解决方案:树莓派声音传感器数据接入Godot 4

问题背景

  • 树莓派端Python代码实现声音传感器触发时发送数据,Python脚本间通信正常
  • 尝试用Python的keyboard.press_and_release()模拟按键,Godot 4无法识别这类模拟输入
  • 改用Godot的WebSocketPeer连接树莓派服务器,客户端状态始终显示“连接中”,但服务器端已确认连接成功

解决方案

采用StreamPeerTCP建立TCP连接,通过全局节点在游戏启动时初始化连接,在帧更新过程中轮询连接状态、读取数据,并将收到的指令映射为Godot的输入动作。

代码实现

  1. 全局节点初始化连接(GameData全局脚本):
extends Node

var players = []
var scene
const port = 8880
var ip = "192.168.4.1"
var connection 

func _ready():
    connection = StreamPeerTCP.new()
    connection.connect_to_host(ip, port)
  1. 在游戏节点的_process中处理数据与输入映射:
func _process(delta):
    GameData.connection.poll()
    
    var state = GameData.connection.get_status()
    
    if GameData.connection and state == GameData.connection.STATUS_CONNECTED:
        if GameData.connection.get_available_bytes() > 0:
            var s = GameData.connection.get_utf8_string(GameData.connection.get_available_bytes())
            print(str(s))
            if str(s) == "1":
                Input.action_press("1")
            elif str(s) == " ":
                Input.action_press("space")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:03:18