PlayerCamera.ts
script to it. Each PlayerCamera object executes its PlayerCamera.ts
script on start.start()
method of PlayerCamera.ts
, the script emits the OnRegisterPlayerCamera event to register itself with the PlayerCameraManager: start() {
// Self register this PlayerCamera to the PlayerManager using a broadcast event.
// We are using a broadcast event because it is easier to add / remove cameras as you adjust the number of max players for your world.
// For more performance at world startup you may want to make this a non-broadcast network event and use the propsDefinition
// to specify a reference to the PlayerManager, then just use a sendNetworkEvent directly.
this.sendNetworkBroadcastEvent(CameraManagerEvents.OnRegisterPlayerCamera, {ObjectId: "PlayerCamera", Object: this.entity});
};
PlayerCameraManager.ts
, a listener in the preStart()
method pushes the registering camera into the list of available PlayerCameras: preStart(): void {
this.connectNetworkBroadcastEvent(CameraManagerEvents.OnRegisterPlayerCamera, ({ObjectId, Object}) => {
if (ObjectId === "PlayerCamera") {
this.playerCameras.push(Object);
};
});
};
private retryCameraAssignDelay: number = 0.1;
private maxAssignAttempts: number = 5;
getCameraForPlayer(player: hz.Player)
in the PlayerCameraManager class, which returns a camera from the array at the player’s index. Whether joining the world via mobile, web or in VR, each player is automatically assigned a player index, which increases from [0]
to the maximum avatar capacity.Note: There must be at least the same number of PlayerCamera entities in the world as the maximum avatar capacity of the world, so that a camera can be found and assigned for every web and mobile player that joins. Potentially, all visitors to the world could be mobile players.
export const CameraManagerEvents = {
OnRegisterPlayerCamera: new hz.NetworkEvent<{
ObjectId: string;
Object: hz.Entity;
}>('OnRegisterPlayerCamera'),
OnSetPlayerCamera: new hz.NetworkEvent<{
player: hz.Player;
camera: hz.Entity;
}>('OnSetPlayerCamera'),
};
Event name | Use |
---|---|
OnRegisterPlayerCamera | When the player has been assigned a PlayerCamera, the player/PlayerCamera combination is pushed in the PlayerCameras array of entities. |
OnSetPlayerCamera | When a player enters the world, PlayerCameraManager.ts attempts to assign a PlayerCamera object to the player. |
Tip: This assignment mechanism can be generalized to handle assignment of other entity types to players entering and exiting the world.