1. 구현 목표

  • 큐브는 총 4개 있음.
  • 서버에서 1초 간격으로 0~3 까지의 난수 전달.
  • 클라이언트들의 화면에는 난수 번째의 큐브가 동일하게 보여야 함.

2. 구현 코드

[ index.ts ]

// deltaTime의 누적합 변수는 반드시 0으로 초기화
tempTime: number = 0;
// spawn 시간
spawnDelayTime: number = 1;
// Cube의 랜덤 인덱스값(0~3)
cubeRandomNumber: number = 0;

onTick(deltaTime: number) {
	this.tempTime += deltaTime;
        
	if (this.tempTime / 1000 > this.spawnDelayTime) {
		this.cubeRandomNumber = Math.floor(Math.random() * 4);
		// client로 Cube의 랜덤 인덱스값 전송
		this.broadcast("cubeRandomNumber", this.cubeRandomNumber);
		this.tempTime = 0;
	}
}

[ SpawnTressure.ts ]

import { GameObject } from 'UnityEngine'
import { Room } from 'ZEPETO.Multiplay';
import { ZepetoScriptBehaviour } from 'ZEPETO.Script'
import { ZepetoWorldMultiplay } from 'ZEPETO.World';

export default class SpawnTressure extends ZepetoScriptBehaviour {

    private cubes: GameObject[] = [];

    private multiplay: ZepetoWorldMultiplay;

    public cubeMaximum: number;

    Start() {
        this.multiplay = GameObject.Find("WorldMultiPlay").GetComponent<ZepetoWorldMultiplay>();

        // cubes 배열 초기화
        for(let i:number = 0; i < this.cubeMaximum; i++) {
            this.cubes[i] = this.transform.GetChild(i).gameObject;
        }

        // RoomJoined Listener
        this.multiplay.RoomJoined += (room: Room) => {
            room.AddMessageHandler("cubeRandomNumber", (message: number) => {
                
                // cubes 모두 숨김
                for(let j:number = 0; j < this.cubeMaximum; j++) {
                    this.cubes[j].SetActive(false);
                }
                // 랜덤한 번호의 cube만 보이기
                this.cubes[message].SetActive(true);
            });
        }
    }
}

3. 핵심 정리

  1. 예를 들어, 4개의 큐브 중 1개의 큐브만 랜덤하게 등장하게 하려면, ‘(1) 모든 큐브를 숨긴다’ > ‘(2) 랜덤한 큐브 한개만 보인다’ 이렇게 작성하면 된다. :)
  2. Server와 Client는 아래와 같이 통신한다.

image-20220723131613503

4. 결과

아래와 같이 host 와 guest 모두 4개의 큐브 중 한개의 랜덤한 큐브만1초 간격으로 동일하게 보인다.

image-20220723131526324

태그:

카테고리:

업데이트:

댓글남기기