我正在制作具有云功能的多人游戏。
工作原理: 每次用户加入匹配室时,客户端都会使用该玩家的 id 创建匹配树。服务器读取此匹配树并遍历快照中的每个玩家。它检查哪个玩家拥有 gameId 的“占位符”值并创建第二个玩家。
问题在于,当玩家加入时,每个快照只会被调用前两三次。当另一个玩家稍后加入房间时,secondPlater 返回 null,这意味着它没有遍历每个玩家。
这是带有日志的代码:
exports.matchmaker = functions.database.ref('matchmaking/{playerId}')
.onCreate((snap, context) => {
console.log("joined queue");
var gameId = generateGameId();
database.ref('matchmaking').once('value').then(snapshot => {
var secondPlayer = null;
// Search for a player who is not yet matched in the queue
snapshot.forEach(child => { // error: not reading the players
var playerId = child.key
var gameId = child.val().gameId
console.log(playerId);
console.log(gameId);
// Check for an open player and is not the player who just joined
if (gameId === "placeholder" && playerId !== context.params.playerId) {
secondPlayer = child;
}
});
console.log("Second player");
console.log(secondPlayer);
if (secondPlayer === null) return null;
// DO OTHER STUFF and access secondplayer's values
我真的很感激任何帮助。