学Cocos Creator 3.8.0链接GoWorld自带示例ChatRoom

下载Cocos Dashboard

创建按一个3D项目

场景里添加2个UI对象,按钮,编辑框

左下添加一个TS脚本NewComponent添加到Canvas上作为按钮的组件

TS里写

   onBtnClick(event, customEventData){
        var editBox = this.node.getChildByName("EditBox").getComponent(EditBox);
        console.log('按钮按下'+editBox.textLabel.string);
    }

然后按钮事件挂自己的按钮节点,选择这个脚本的这个方法。

点上面三角形运行后会直接打开Edge浏览器,F12打开浏览器调试分割窗口,点击按钮看到右边出现“按钮按下”文字

场景名字改为login

把官方例子的Js代码改为Ts代码调用注册:

import { _decorator, Component, EditBox, Node } from 'cc';
import { encode,decode } from "./msgpack-ts-master/src"
const { ccclass, property } = _decorator;

const _RECV_PAYLOAD_LENGTH = 1
const _RECV_PAYLOAD = 2

const CLIENTID_LENGTH = 16
const ENTITYID_LENGTH = 16
const SIZE_FIELD_SIZE = 4

const MT_INVALID = 0
// Server Messages
const MT_SET_GAME_ID = 1
const MT_SET_GATE_ID = 2
const MT_NOTIFY_CREATE_ENTITY = 3
const MT_NOTIFY_DESTROY_ENTITY = 4
const MT_DECLARE_SERVICE = 5
const MT_UNDECLARE_SERVICE = 6
const MT_CALL_ENTITY_METHOD = 7
const MT_CREATE_ENTITY_ANYWHERE = 8
const MT_LOAD_ENTITY_ANYWHERE = 9
const MT_NOTIFY_CLIENT_CONNECTED = 10
const MT_NOTIFY_CLIENT_DISCONNECTED = 11
const MT_CALL_ENTITY_METHOD_FROM_CLIENT = 12
const MT_SYNC_POSITION_YAW_FROM_CLIENT = 13
const MT_NOTIFY_ALL_GAMES_CONNECTED = 14
const MT_NOTIFY_GATE_DISCONNECTED = 15
const MT_START_FREEZE_GAME = 16
const MT_START_FREEZE_GAME_ACK = 17
// Message types for migrating
const MT_MIGRATE_REQUEST = 18
const MT_REAL_MIGRATE = 19


const MT_GATE_SERVICE_MSG_TYPE_START = 1000
const MT_REDIRECT_TO_GATEPROXY_MSG_TYPE_START = 1001 // messages that should be redirected to client proxy
const MT_CREATE_ENTITY_ON_CLIENT = 1002
const MT_DESTROY_ENTITY_ON_CLIENT = 1003
const MT_NOTIFY_MAP_ATTR_CHANGE_ON_CLIENT = 1004
const MT_NOTIFY_MAP_ATTR_DEL_ON_CLIENT = 1005
const MT_NOTIFY_LIST_ATTR_CHANGE_ON_CLIENT = 1006
const MT_NOTIFY_LIST_ATTR_POP_ON_CLIENT = 1007
const MT_NOTIFY_LIST_ATTR_APPEND_ON_CLIENT = 1008
const MT_CALL_ENTITY_METHOD_ON_CLIENT = 1009
const MT_UPDATE_POSITION_ON_CLIENT = 1010
const MT_UPDATE_YAW_ON_CLIENT = 1011
const MT_SET_CLIENTPROXY_FILTER_PROP = 1012
const MT_CLEAR_CLIENTPROXY_FILTER_PROPS = 1013


// add more ...

const MT_REDIRECT_TO_GATEPROXY_MSG_TYPE_STOP = 1500

const MT_CALL_FILTERED_CLIENTS = 1501
const MT_SYNC_POSITION_YAW_ON_CLIENTS = 1502

// add more ...

const MT_GATE_SERVICE_MSG_TYPE_STOP = 2000
export class ClientEntity extends Component {
    create(owner, typeName, entityID, attrs) {
        this.owner = owner 
        this.typeName = typeName
        this.ID = entityID
        this.attrs = attrs 
        this.isPlayer = false
    }
    onCreated() {
        if (this.typeName == "Account") {
            console.log("Account created, start logining...")
        }
    }    
    onBecomePlayer() {
        let scene = cc.director.getScene()
        
        console.log("获得玩家对象:", this, scene.name)
        if (this.typeName == "Avatar") {
            // 玩家登录成功!
            this.getGoWorld().onAvatarLoginSuccess( this )
        } else if (this.typeName == "Account") {
            // 账号创建成功,可以开始登陆
            if (scene.name != "login") {
                cc.director.loadScene("login");
            }
        }
    }
    onCall(method, args) {
        console.log(this.toString()+"."+method+"("+args+")")
        this[method](...args)
    }
      // Put Client Methods Here 
      ShowError(msg) {
        // this.getGoWorld().showErrorTip(msg)
        console.log('ShowError'+msg);
    }
}
@ccclass('NewComponent')
export class NewComponent extends Component {
    ID="ID_TEST";
    start() {
        this.recvBuf = new ArrayBuffer()
        this.recvStatus = _RECV_PAYLOAD_LENGTH
        this.recvPayloadLen = 0
        this.entities = {}
        this.sendBuf = new ArrayBuffer(1024*1024);
        this._sendPacket = new DataView(this.sendBuf);
        this._sendPacketWritePos = SIZE_FIELD_SIZE
        this.connect();
    }

    update(deltaTime: number) {
        
    }
    onBtnClick(event, customEventData){
        var editBox = this.node.getChildByName("EditBox").getComponent(EditBox);
        console.log('按钮按下'+editBox.textLabel.string);
        let account = this.getEntityByType("Account")
        this.callServer(account,"Register",editBox.textLabel.string,"asdf");
    }    
    getEntityByType(typeName) {
        for (var eid in this.entities) {
            let e = this.entities[eid]
            if (e.typeName == typeName) {
                return e
            }
        }
        return null 
    }
    callServer(entity:ClientEntity, method ) {
        var args = Array.prototype.slice.call(arguments);
        args = args.slice(2)
        this.callServerMethod( entity, method, args )
    }
    callServerMethod(entity:NewComponent, method:string, args) {
        console.log(">>> "+entity+"."+method+"("+args+")")
        // 	packet.AppendUint16(MT_CALL_ENTITY_METHOD_FROM_CLIENT)
        // 	packet.AppendEntityID(id)
        // 	packet.AppendVarStr(method)
        // 	packet.AppendArgs(args)

        this.appendUint16(MT_CALL_ENTITY_METHOD_FROM_CLIENT)
        this.appendEntityID(entity.ID)
        this.appendVarStr(method)
        this.appendArgs(args)
        this.sendPacket()
    }
    appendUint16(v) {
        this._sendPacket.setUint16(this._sendPacketWritePos, v, true)
        this._sendPacketWritePos += 2
    }
    appendEntityID(eid) {
        console.log(eid);
        let b = this.string2Uint8Array(eid)
        console.log("convert", eid, "to", b, b.length)
        this.appendBytes(b)
    }
    string2Uint8Array(str) {
        console.log(str);
        let bufView = new Uint8Array(str.length);
        for (var i=0, strLen=str.length; i

你可能感兴趣的:(Cocos,Creator)