TUTORIAL
Tutorial Bermain Ganda
15min
📘 Contoh Multiplay https://github.com/naverz/zepeto-multiplay-example

Ringkasan | Dari membuat server Multiplay hingga klien, siapkan lingkungan yang diperlukan untuk mengembangkan Dunia Multiplay. |
---|---|
Kesulitan | Menengah |
Waktu yang Diperlukan | 1 Jam |

- Dari membuat server Multiplay hingga klien, siapkan lingkungan yang diperlukan untuk mengembangkan Dunia Multiplay.


- Pelajari tentang Skema yang diperlukan untuk komunikasi antara server dan klien, dan definisikan Jenis Skema dan Status Ruangan.

- Harap dicatat bahwa skrip server yang digunakan dalam video, yang mencakup konten terkait hashCode, tidak lagi didukung.
- Oleh karena itu, kecualikan kode berikut saat menulis.
TypeScript
1if (client.hashCode) {
2 player.zepetoHash = client.hashCode;
3}


- Tulis logika Dunia yang diperlukan untuk menyinkronkan dari lokasi pemain ke keluaran pemain.


- Jalankan server dan hubungkan ke Multiplay.


schemas.json
1{
2"State" : {"players" : {"map" : "Pemain"}},
3"Player" : {"sessionId" : "string","zepetoUserId" : "string","transform" : "Transformasi","state" : "number","subState" : "number"},
4"Transform" : {"position" : "Vektor3","rotation" : "Vektor3"},
5"Vector3" : {"x" : "number","y" : "number","z" : "number"}
6}


index.ts
1import {Sandbox, SandboxOptions, SandboxPlayer} from "ZEPETO.Multiplay";
2import {DataStorage} from "ZEPETO.Multiplay.DataStorage";
3import {Player, Transform, Vector3} from "ZEPETO.Multiplay.Schema";
4
5export default class extends Sandbox {
6
7
8 storageMap:Map<string,DataStorage> = new Map<string, DataStorage>();
9
10 constructor() {
11 super();
12 }
13
14 onCreate(options: SandboxOptions) {
15 // Dipanggil saat objek Ruang dibuat.
16 // Tangani status atau inisialisasi data objek Ruang.
17
18 this.onMessage("onChangedTransform", (client, message) => {
19 const player = this.state.players.get(client.sessionId);
20
21 const transform = new Transform();
22 transform.position = new Vector3();
23 transform.position.x = message.position.x;
24 transform.position.y = message.position.y;
25 transform.position.z = message.position.z;
26
27 transform.rotation = new Vector3();
28 transform.rotation.x = message.rotation.x;
29 transform.rotation.y = message.rotation.y;
30 transform.rotation.z = message.rotation.z;
31
32 if (player) {
33 player.transform = transform;
34 }
35 });
36
37 this.onMessage("onChangedState", (client, message) => {
38 const player = this.state.players.get(client.sessionId);
39 if (player) {
40 player.state = message.state;
41 player.subState = message.subState; // Pengontrol Karakter V2
42 }
43 });
44 }
45
46
47
48 async onJoin(client: SandboxPlayer) {
49
50 // Buat objek pemain yang didefinisikan dalam schemas.json dan atur nilai awal.
51 console.log(`[OnJoin] sessionId : ${client.sessionId}, userId : ${client.userId}`)
52
53 const player = new Player();
54 player.sessionId = client.sessionId;
55
56 if (client.userId) {
57 player.zepetoUserId = client.userId;
58 }
59
60 // [DataStorage] Memuat DataStorage Pemain yang masuk
61 const storage: DataStorage = client.loadDataStorage();
62
63 this.storageMap.set(client.sessionId,storage);
64
65 let visit_cnt = await storage.get("VisitCount") as number;
66 if (visit_cnt == null) visit_cnt = 0;
67
68 console.log(`[OnJoin] jumlah kunjungan ${client.sessionId} : ${visit_cnt}`)
69
70 // [DataStorage] Perbarui jumlah kunjungan Pemain dan kemudian Simpan Storage
71 await storage.set("VisitCount", ++visit_cnt);
72
73 // Kelola objek Pemain menggunakan sessionId, nilai kunci unik dari objek klien.
74 // Klien dapat memeriksa informasi tentang objek pemain yang ditambahkan dengan menambahkan acara add_OnAdd ke objek pemain.
75 this.state.players.set(client.sessionId, player);
76 }
77
78 onTick(deltaTime: number): void {
79 // Dipanggil berulang kali pada setiap waktu yang ditetapkan di server, dan acara interval tertentu dapat dikelola menggunakan deltaTime.
80 }
81
82 async onLeave(client: SandboxPlayer, consented?: boolean) {
83
84 // Dengan mengatur allowReconnection, dimungkinkan untuk mempertahankan koneksi untuk sirkuit, tetapi segera membersihkan dalam panduan dasar.
85 // Klien dapat memeriksa informasi tentang objek pemain yang dihapus dengan menambahkan acara add_OnRemove ke objek pemain.
86 this.state.players.delete(client.sessionId);
87 }
88}


ClientStarter.ts
1import {ZepetoScriptBehaviour} from 'ZEPETO.Script'
2import {ZepetoWorldMultiplay} from 'ZEPETO.World'
3import {Room, RoomData} from 'ZEPETO.Multiplay'
4import {Player, State, Vector3} from 'ZEPETO.Multiplay.Schema'
5import {CharacterState, SpawnInfo, ZepetoPlayers, ZepetoPlayer, CharacterJumpState} from 'ZEPETO.Character.Controller'
6import * as UnityEngine from "UnityEngine";
7
8
9export default class ClientStarterV2 extends ZepetoScriptBehaviour {
10
11 public multiplay: ZepetoWorldMultiplay;
12
13 private room: Room;
14 private currentPlayers: Map<string, Player> = new Map<string, Player>();
15
16 private zepetoPlayer: ZepetoPlayer;
17
18 private Start() {
19
20 this.multiplay.RoomCreated += (room: Room) => {
21 this.room = room;
22 };
23
24 this.multiplay.RoomJoined += (room: Room) => {
25 room.OnStateChange += this.OnStateChange;
26 };
27
28 this.StartCoroutine(this.SendMessageLoop(0.04));
29 }
30
31 // Kirim transformasi karakter lokal ke server pada Interval Waktu yang dijadwalkan.
32 private* SendMessageLoop(tick: number) {
33 while (true) {
34 yield new UnityEngine.WaitForSeconds(tick);
35
36 if (this.room != null && this.room.IsConnected) {
37 const hasPlayer = ZepetoPlayers.instance.HasPlayer(this.room.SessionId);
38 if (hasPlayer) {
39 const character = ZepetoPlayers.instance.GetPlayer(this.room.SessionId).character;
40 this.SendTransform(character.transform);
41 this.SendState(character.CurrentState);
42 }
43 }
44 }
45 }
46
47 private OnStateChange(state: State, isFirst: boolean) {
48
49 // Ketika event OnStateChange pertama diterima, snapshot status penuh dicatat.
50 if (isFirst) {
51
52 // [CharacterController] (Lokal) Dipanggil ketika instance Pemain sepenuhnya dimuat di Scene
53 ZepetoPlayers.instance.OnAddedLocalPlayer.AddListener(() => {
54 const myPlayer = ZepetoPlayers.instance.LocalPlayer.zepetoPlayer;
55 this.zepetoPlayer = myPlayer;
56 });
57
58 // [CharacterController] (Lokal) Dipanggil ketika instance Pemain sepenuhnya dimuat di Scene
59 ZepetoPlayers.instance.OnAddedPlayer.AddListener((sessionId: string) => {
60 const isLocal = this.room.SessionId === sessionId;
61 if (!isLocal) {
62 const player: Player = this.currentPlayers.get(sessionId);
63
64 // [RoomState] Dipanggil setiap kali status instance pemain diperbarui.
65 player.OnChange += (changeValues) => this.OnUpdatePlayer(sessionId, player);
66 }
67 });
68 }
69
70 let join = new Map<string, Player>();
71 let leave = new Map<string, Player>(this.currentPlayers);
72
73 state.players.ForEach((sessionId: string, player: Player) => {
74 if (!this.currentPlayers.has(sessionId)) {
75 join.set(sessionId, player);
76 }
77 leave.delete(sessionId);
78 });
79
80 // [RoomState] Buat instance pemain untuk pemain yang masuk ke Ruangan
81 join.forEach((player: Player, sessionId: string) => this.OnJoinPlayer(sessionId, player));
82
83 // [RoomState] Hapus instance pemain untuk pemain yang keluar dari ruangan
84 leave.forEach((player: Player, sessionId: string) => this.OnLeavePlayer(sessionId, player));
85 }
86
87 private OnJoinPlayer(sessionId: string, player: Player) {
88 console.log(`[OnJoinPlayer] pemain - sessionId : ${sessionId}`);
89 this.currentPlayers.set(sessionId, player);
90
91 const spawnInfo = new SpawnInfo();
92 const position = this.ParseVector3(player.transform.position);
93 const rotation = this.ParseVector3(player.transform.rotation);
94 spawnInfo.position = position;
95 spawnInfo.rotation = UnityEngine.Quaternion.Euler(rotation);
96
97 const isLocal = this.room.SessionId === player.sessionId;
98 ZepetoPlayers.instance.CreatePlayerWithUserId(sessionId, player.zepetoUserId, spawnInfo, isLocal);
99 }
100
101 private OnLeavePlayer(sessionId: string, player: Player) {
102 console.log(`[OnRemove] pemain - sessionId : ${sessionId}`);
103 this.currentPlayers.delete(sessionId);
104
105 ZepetoPlayers.instance.RemovePlayer(sessionId);
106 }
107
108 private OnUpdatePlayer(sessionId: string, player: Player) {
109
110 const position = this.ParseVector3(player.transform.position);
111
112 const zepetoPlayer = ZepetoPlayers.instance.GetPlayer(sessionId);
113
114 var moveDir = UnityEngine.Vector3.op_Subtraction(position, zepetoPlayer.character.transform.position);
115 moveDir = new UnityEngine.Vector3(moveDir.x, 0, moveDir.z);
116
117 if (moveDir.magnitude < 0.05) {
118 if (player.state === CharacterState.MoveTurn)
119 return;
120 zepetoPlayer.character.StopMoving();
121 } else {
122 zepetoPlayer.character.MoveContinuously(moveDir);
123 }
124
125 if (player.state === CharacterState.Jump) {
126 if (zepetoPlayer.character.CurrentState !== CharacterState.Jump) {
127 zepetoPlayer.character.Jump();
128 }
129
130 if (player.subState === CharacterJumpState.JumpDouble) {
131 zepetoPlayer.character.DoubleJump();
132 }
133 }
134 }
135
136 private SendTransform(transform: UnityEngine.Transform) {
137 const data = new RoomData();
138
139 const pos = new RoomData();
140 pos.Add("x", transform.localPosition.x);
141 pos.Add("y", transform.localPosition.y);
142 pos.Add("z", transform.localPosition.z);
143 data.Add("position", pos.GetObject());
144
145 const rot = new RoomData();
146 rot.Add("x", transform.localEulerAngles.x);
147 rot.Add("y", transform.localEulerAngles.y);
148 rot.Add("z", transform.localEulerAngles.z);
149 data.Add("rotation", rot.GetObject());
150 this.room.Send("onChangedTransform", data.GetObject());
151 }
152
153 private SendState(state: CharacterState) {
154 const data = new RoomData();
155 data.Add("state", state);
156 if(state === CharacterState.Jump) {
157 data.Add("subState", this.zepetoPlayer.character.MotionV2.CurrentJumpState);
158 }
159 this.room.Send("onChangedState", data.GetObject());
160 }
161
162 private ParseVector3(vector3: Vector3): UnityEngine.Vector3 {
163 return new UnityEngine.Vector3
164 (
165 vector3.x,
166 vector3.y,
167 vector3.z
168 );
169 }
170}


Diperbarui 11 Oct 2024
Apakah halaman ini membantu Anda?