提问人:Sasrielohn 提问时间:11/15/2023 最后编辑:Sasrielohn 更新时间:11/19/2023 访问量:37
如何在 Godot 中使用 WebSocket 调用 RPC 4.1 |浏览器多人游戏 (websocket + webRTC) (尝试使用未知的对等 ID 调用 RPC)
How to call RPC using WebSocket in Godot 4.1 | browser multiplayer game (websocket + webRTC) (Attempt to call RPC with unknown peer ID)
问:
我一直在尝试制作一个基于浏览器的游戏(html5 导出),它将有主大厅,玩家可以在其中四处走动和聊天,迷你游戏可以是单人或合作的...... 我已经设法按照教程设置了服务器并开始调整它(https://youtu.be/ulfGNtiItnc?si=fvJbxVO1NcsSaaSk) 发送数据包适用于聊天消息,但是当我尝试生成玩家头像时,仅在服务器上调用rpc。 层次结构在所有 Godot 实例上都是相同的
控制
- 客户
-
- 玩家生成
- 服务器
-
- 玩家生成
我的 Server.gd
#Adds player scene, name=id is used for taking control in player controller script
@rpc("any_peer", "call_local")
func addNewPlayer(id):
var currentPlayer = PlayerScene.instantiate()
currentPlayer.name = str(id)
get_tree().root.add_child(currentPlayer)
currentPlayer.global_position = $PlayerSpawn.global_position
pass
#Adds all existing player scenes for player that joined later
@rpc("any_peer", "call_local")
func addExistingPlayers(idExcluded):
for key in users:
var user = users[key]
if idExcluded == user.id:
continue
addNewPlayer(user.id)
#As for calling the RPC, the packets are polled in _process and parsed into string and called like so:
#Only sending this to the new player
addExistingPlayers.rpc_id(int(data.id), data.id)
addNewPlayer.rpc(data.id)
我的 Client.gd
#I create websocket peer
var peer_socket = WebSocketMultiplayerPeer.new()
#and once client gets assigned ID from the server after connecting this is run
multiplayer.multiplayer_peer = peer_socket
#As for sending the packet to the server
var message = {
"message": Utilities.PacketMessage.AVATAR_SPAWN,
"id": id
}
peer_socket.put_packet(JSON.stringify(message).to_utf8_buffer())
尽管连接成功,但服务器不知道任何客户端,即使它向他们发送了唯一的 ID
编辑: 第1个:重新阅读文档后,“要使远程调用成功,发送和接收节点需要具有相同的NodePath,这意味着它们必须具有相同的名称”......所以这是否意味着我需要有 2 个项目......一个用于服务器的东西,一个用于客户端的东西,在服务器中(因为我想要服务器权限),我将生成播放器,在客户端中,脚本将被命名为相同,但@rpc功能将是空白的? 或者因为它对我来说仍然没有意义,考虑到我当前的项目有两个脚本,但 Server.gd 似乎只在 godot 的 HOST 实例上工作 第二:我尝试制作 2 个项目,一个用于服务器,一个用于客户端。并且 RPC 仍然无法与 WebSocket 对等连接一起使用
答:
原来我只是傻...... 你可以用 WebSockets 进行 rpc 调用,但是,在 godot 4 中,你需要确保节点的路径是相同的,并且这两个项目也具有所有@rpc方法。他们不需要任何东西,只需要声明和“通过” 所以这不起作用的原因是服务器脚本中的@rpc函数试图调用其他服务器脚本中的@rpc,但它们不能,因为其他服务器脚本或客户端的脚本没有创建对等体,所以没有 id... 简单地说,假设您正在尝试进行服务器身份验证,并且您的客户端和身份验证之间有网关服务器
#Your Gateway.gd in client project can look like this
#This will only be called from client using testRPC_Client.rpc()
@rpc("any_peer")
func testRPC_Client():
print("testRPC_Client")
#This will only be called from gateway using testRPC_Gate.rpc()
@rpc("any_peer")
func testRPC_Gate():
#You can put ANYTHING HERE
pass
#And your Gateway.gd in Gateway project will have to then contain these methods
#This will only be called from client using testRPC_Client.rpc()
@rpc("any_peer")
func testRPC_Client():
#You can put ANYTHING HERE
pass
#This will only be called from gateway using testRPC_Gate.rpc()
@rpc("any_peer")
func testRPC_Gate():
print("testRPC_Gate")
还要确保注释使用相同的参数,否则校验和将失败
评论