Cocos creator 3.x uses the official frame synchronization service to develop a real-time battle WeChat mini-game tutorial (2)

Following the previous article, cocos creator 3.x uses the official frame synchronization service to develop a real-time battle WeChat mini game tutorial (1) We have successfully applied for a 2V2 matchId, and we will use it in the game developed by cocos creator 3.x it. (When developing, it is recommended to create a 1V1 matchId for easy debugging)

Contents of this chapter:

The player clicks the match button to call his own backend server, obtain the matchId generated in step 1, and use this matchId to call the mini game service

Take a single scene as an example, put a button with the text set to "Start Matching", after clicking the button, call your own backend server to get the matchId and call the game service to wait for other players, and display a window to tell the player that the match is in progress.

public gameserver:GameServer| null = null;
start() {
    
    
	//实例化游戏服务并登录
	this.gameserver = new GameServer()
	this.gameserver.login()
}

For this GameServer class, I use the GameServer.js in the official example , which encapsulates most of the methods such as login, matching, and checking the WeChat version number, etc., just convert it into ts and import it.

After entering the scene, first instantiate a game service object and log in. It should be noted that the login takes about 1-2 seconds to log in successfully. If the user clicks the matching button to call the matching service before the login is successful, an error will be reported , developers can add their own logic, such as enabling the matching button after a successful login.

Add an event that matches the button

 onbtnMatchClick() {
    
    
 	 let _this = this
     let request = {
    
     userId: "test", vsType: "2V2"}
     //post方法调用自己后端服务器获取matchId,自己封装哈不会的可以百度XMLHttpRequest
        post("GetMatchIdByVsType", request, function (result) {
    
    
        //result就是服务器返回的matchId
            if (result != "") {
    
    
                _this.gameserver.server.startMatch({
    
    
                    matchId: result,
                    success: () => {
    
    
                        console.log('加入匹配成功')
                        //_this.lblMessage.string = '匹配中...'
                    },
                    fail: res => {
    
    
                        console.error('加入匹配失败', res)
                        //_this.lblMessage.string = '匹配异常,请重启游戏'
                    }
                })
            }
            else {
    
    
                //_this.lblMessage.string = '获取匹配Id异常'
                return;
            }
        })   
 }

After using the post method to get the matchId, you can call GameServerManager.startMatch to start matching.

At the beginning of new GameServer(), the this.bindEvents() method will bind many events, including monitoring the matching event onMatch, that is to say, when all 4 players match with the same matchId in 2V2 mode, they will Enter the event bound to onMatch.
Let's take a look at what is done in the onMatch method in the official example

onMatch(res){
    
    
        let nickname = res.groupInfoList[0].memberInfoList[0].nickName;
        databus.currAccessInfo = this.accessInfo = res.roomServiceAccessInfo || "";
        this.joinRoom(databus.currAccessInfo)
            .then((res) => {
    
    
                let data = res.data || {
    
    };
                databus.selfClientId = data.clientId;

                this.updateReadyStatus(true);

                if (databus.userInfo.nickName !== nickname) {
    
    
                    setTimeout(
                        this.server.broadcastInRoom.bind(this, {
    
    
                            msg: "START",
                        }),
                        3000
                    );
                }

                wx.showToast({
    
    
                    title: "匹配成功!3秒后开始游戏",
                    icon: "none",
                    duration: 2000,
                });
            })
            .catch((e) => {
    
    
                console.log(e);
            });
    }

In the official example, databus is a class used to save matching information, which we can use in projects. There are two places where databus is used in this method: currAccessInfo and selfClientId. currAccessInfo is a parameter for adding a room. To put it bluntly, it is a token of string type . selfClientId represents your own identity in the room , for example, 1 is yourself, 2 is the opposite player, if it is a 2V2 matching mode, there will be 3 and 4, we can use this ClientId to set the player's birth point, for example, there are ABCD four on the map points correspond to 1234 respectively, then the four players will be assigned to different birth points in sequence after starting the game. The player's selfClientId is determined according to the order of entering the room, not necessarily 1 .

In cocos creator, we can add eventTarget.emit to the onMatch method to emit events, such as adding eventTarget.emit('matched', 'Matched successfully, about to start') and then in the start() of the scene eventTarget.on(' matched', function(){//A prompt pops up to tell the player that the match is successful, and the game will start immediately}). If you don’t know it, please refer to cocos creator launching and monitoring events

When all players in the room enter the onMatch method, the onGameStart event will be triggered after 3 seconds. It should be noted that if all four players are successfully matched, but one player closes the mini-game within 3 seconds of the countdown, then All players will not trigger the onGameStart event (if the matching rule start percentage is set to 100, I am not sure if it will be triggered if the setting is 75, interested players can try it by themselves). If you encounter this situation, there is no solution in the official example, other players will be stuck in onMatch and will not re-match. My own method is to start the timer in onMatch. If onGameStart is not called within 8 seconds, call leaveRoom , and a pop-up prompt will say that someone has slipped away and let the player re-match.

If all four players are well-behaved and no one cheats, then they will enter the onGameStart() method smoothly. In the official example, some debugging information is recorded in this method. When we actually use it, we only need to use the launch event eventTarget of cocos creator. emit('battle') just notify the scene that the game can start, register eventTarget.on('battle', function(){//The game has officially started, jump to the battle scene}) in the start of the scene

If there is no accident at this time, the client has been receiving frames sent by the game service continuously, every 33ms, and the matching function is basically completed.

The next chapter will show how to handle game frames and what to watch out for. (Ah, I'm so sleepy, I'll write again in a few days...)

Simple online example:
WeChat mini-game "Elite Tanker" 1V1 matchmaking

Guess you like

Origin blog.csdn.net/hangsky1990/article/details/131343156
Recommended