non-vr lobby, version fix

This commit is contained in:
joonasp
2022-06-29 14:45:17 +03:00
parent 5774be9822
commit 04baadfad1
1774 changed files with 573069 additions and 1533 deletions

View File

@@ -0,0 +1,123 @@
// ----------------------------------------------------------------------------
// <copyright file="BaseController.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN- Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Base class of character controllers.
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------
namespace ExitGames.Demos.DemoPunVoice
{
using Photon.Pun;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
[RequireComponent(typeof(PhotonView))]
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(Animator))]
public abstract class BaseController : MonoBehaviour
{
public Camera ControllerCamera;
protected Rigidbody rigidBody;
protected Animator animator;
protected Transform camTrans; // A reference to transform of the third person camera
private float h, v;
[SerializeField]
protected float speed = 5f;
[SerializeField]
private float cameraDistance = 0f;
protected virtual void OnEnable()
{
ChangePOV.CameraChanged += this.ChangePOV_CameraChanged;
}
protected virtual void OnDisable()
{
ChangePOV.CameraChanged -= this.ChangePOV_CameraChanged;
}
protected virtual void ChangePOV_CameraChanged(Camera camera)
{
if (camera != this.ControllerCamera)
{
this.enabled = false;
this.HideCamera(this.ControllerCamera);
}
else
{
this.ShowCamera(this.ControllerCamera);
}
}
protected virtual void Start()
{
PhotonView photonView = this.GetComponent<PhotonView>();
if (photonView.IsMine)
{
this.Init();
this.SetCamera();
}
else
{
this.enabled = false;
}
}
protected virtual void Init()
{
this.rigidBody = this.GetComponent<Rigidbody>();
this.animator = this.GetComponent<Animator>();
}
protected virtual void SetCamera()
{
this.camTrans = this.ControllerCamera.transform;
this.camTrans.position += this.cameraDistance * this.transform.forward;
}
protected virtual void UpdateAnimator(float h, float v)
{
// Create a boolean that is true if either of the input axes is non-zero.
bool walking = h != 0 || v != 0;
// Tell the animator whether or not the player is walking.
this.animator.SetBool("IsWalking", walking);
}
protected virtual void FixedUpdate()
{
// Store the input axes.
this.h = CrossPlatformInputManager.GetAxisRaw("Horizontal");
this.v = CrossPlatformInputManager.GetAxisRaw("Vertical");
#if MOBILE_INPUT
if (Mathf.Abs(this.h) < 0.5f) { this.h = 0f; }
else { this.h = Mathf.Sign(this.h); }
if (Mathf.Abs(this.v) < 0.5f) { this.v = 0f; }
else { this.v = Mathf.Sign(this.v); }
#endif
// send input to the animator
this.UpdateAnimator(this.h, this.v);
// Move the player around the scene.
this.Move(this.h, this.v);
}
protected virtual void ShowCamera(Camera camera)
{
if (camera != null) { camera.gameObject.SetActive(true); }
}
protected virtual void HideCamera(Camera camera)
{
if (camera != null) { camera.gameObject.SetActive(false); }
}
protected abstract void Move(float h, float v);
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: d6fd61529d855944dbaf37c1058b8d3b
timeCreated: 1446721403
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,37 @@
// ----------------------------------------------------------------------------
// <copyright file="BetterToggle.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN- Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Unity UI extension class that should be used with Unity's built-in Toggle
// to broadcast value change in a better way.
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------
namespace ExitGames.Demos.DemoPunVoice {
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Toggle))]
[DisallowMultipleComponent]
public class BetterToggle : MonoBehaviour {
private Toggle toggle;
public delegate void OnToggle(Toggle toggle);
public static event OnToggle ToggleValueChanged;
private void Start() {
this.toggle = this.GetComponent<Toggle>();
this.toggle.onValueChanged.AddListener(delegate { this.OnToggleValueChanged(); });
}
public void OnToggleValueChanged() {
if (ToggleValueChanged != null) {
ToggleValueChanged(this.toggle);
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 02aa66d915b164c41880df3b7ced396a
timeCreated: 1447199660
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,162 @@
// ----------------------------------------------------------------------------
// <copyright file="ChangePOV.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN- Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// "Camera manager" class that handles the switch between the three different cameras.
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------
#pragma warning disable 0649 // Field is never assigned to, and will always have its default value
namespace ExitGames.Demos.DemoPunVoice {
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Realtime;
using Photon.Pun;
public class ChangePOV : MonoBehaviour, IMatchmakingCallbacks {
private FirstPersonController firstPersonController;
private ThirdPersonController thirdPersonController;
private OrthographicController orthographicController;
private Vector3 initialCameraPosition;
private Quaternion initialCameraRotation;
private Camera defaultCamera;
[SerializeField]
private GameObject ButtonsHolder;
[SerializeField]
private Button FirstPersonCamActivator;
[SerializeField]
private Button ThirdPersonCamActivator;
[SerializeField]
private Button OrthographicCamActivator;
public delegate void OnCameraChanged(Camera newCamera);
public static event OnCameraChanged CameraChanged;
private void OnEnable() {
CharacterInstantiation.CharacterInstantiated += this.OnCharacterInstantiated;
PhotonNetwork.AddCallbackTarget(this);
}
private void OnDisable() {
CharacterInstantiation.CharacterInstantiated -= this.OnCharacterInstantiated;
PhotonNetwork.RemoveCallbackTarget(this);
}
private void Start() {
this.defaultCamera = Camera.main;
this.initialCameraPosition = new Vector3(this.defaultCamera.transform.position.x,
this.defaultCamera.transform.position.y, this.defaultCamera.transform.position.z);
this.initialCameraRotation = new Quaternion(this.defaultCamera.transform.rotation.x,
this.defaultCamera.transform.rotation.y, this.defaultCamera.transform.rotation.z,
this.defaultCamera.transform.rotation.w);
//Check if we are running either in the Unity editor or in a standalone build.
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBPLAYER
this.FirstPersonCamActivator.onClick.AddListener(this.FirstPersonMode);
#else
this.FirstPersonCamActivator.gameObject.SetActive(false);
#endif
this.ThirdPersonCamActivator.onClick.AddListener(this.ThirdPersonMode);
this.OrthographicCamActivator.onClick.AddListener(this.OrthographicMode);
}
private void OnCharacterInstantiated(GameObject character)
{
this.firstPersonController = character.GetComponent<FirstPersonController>();
this.firstPersonController.enabled = false;
this.thirdPersonController = character.GetComponent<ThirdPersonController>();
this.thirdPersonController.enabled = false;
this.orthographicController = character.GetComponent<OrthographicController>();
this.ButtonsHolder.SetActive(true);
}
private void FirstPersonMode() {
this.ToggleMode(this.firstPersonController);
}
private void ThirdPersonMode() {
this.ToggleMode(this.thirdPersonController);
}
private void OrthographicMode() {
this.ToggleMode(this.orthographicController);
}
private void ToggleMode(BaseController controller) {
if (controller == null) { return; } // this should not happen, throw error
if (controller.ControllerCamera == null) { return; } // probably game is closing
controller.ControllerCamera.gameObject.SetActive(true);
controller.enabled = true;
this.FirstPersonCamActivator.interactable = !(controller == this.firstPersonController);
this.ThirdPersonCamActivator.interactable = !(controller == this.thirdPersonController);
this.OrthographicCamActivator.interactable = !(controller == this.orthographicController);
this.BroadcastChange(controller.ControllerCamera); // BroadcastChange(Camera.main);
}
private void BroadcastChange(Camera camera) {
if (camera == null) { return; } // should not happen, throw error
if (CameraChanged != null) {
CameraChanged(camera);
}
}
#region IMatchmakingCallbacks interface methods
public void OnFriendListUpdate(List<FriendInfo> friendList)
{
}
public void OnCreatedRoom()
{
}
public void OnCreateRoomFailed(short returnCode, string message)
{
}
public void OnJoinedRoom()
{
}
public void OnJoinRoomFailed(short returnCode, string message)
{
}
public void OnJoinRandomFailed(short returnCode, string message)
{
}
public void OnLeftRoom()
{
if (ConnectionHandler.AppQuits)
{
return;
}
this.defaultCamera.gameObject.SetActive(true);
this.FirstPersonCamActivator.interactable = true;
this.ThirdPersonCamActivator.interactable = true;
this.OrthographicCamActivator.interactable = false;
this.defaultCamera.transform.position = this.initialCameraPosition;
this.defaultCamera.transform.rotation = this.initialCameraRotation;
this.ButtonsHolder.SetActive(false);
}
#endregion
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 4dd7c72bb79ad6544aae08d975251222
timeCreated: 1446115192
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,361 @@
// ----------------------------------------------------------------------------
// <copyright file="CharacterInstantiation.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN- Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Class that handles character instantiation when the actor is joined.
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------
namespace ExitGames.Demos.DemoPunVoice
{
using System.Collections.Generic;
using ExitGames.Client.Photon;
using Photon.Realtime;
using UnityEngine;
using Photon.Pun;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class CharacterInstantiation : MonoBehaviourPunCallbacks, IOnEventCallback
{
public enum SpawnSequence { Connection, Random, RoundRobin }
public Transform SpawnPosition;
public float PositionOffset = 2.0f;
public GameObject[] PrefabsToInstantiate;
public List<Transform> SpawnPoints;
public bool AutoSpawn = true;
public bool UseRandomOffset = true;
public SpawnSequence Sequence = SpawnSequence.Connection;
public delegate void OnCharacterInstantiated(GameObject character);
public static event OnCharacterInstantiated CharacterInstantiated;
[SerializeField]
private byte manualInstantiationEventCode = 1;
protected int lastUsedSpawnPointIndex = -1;
#pragma warning disable 649
[SerializeField]
private bool manualInstantiation;
[SerializeField]
private bool differentPrefabs;
[SerializeField] private string localPrefabSuffix;
[SerializeField] private string remotePrefabSuffix;
#pragma warning restore 649
public override void OnJoinedRoom()
{
if (!this.AutoSpawn)
{
return;
}
if (this.PrefabsToInstantiate != null)
{
int actorNumber = PhotonNetwork.LocalPlayer.ActorNumber;
if (actorNumber < 1)
{
actorNumber = 1;
}
int index = (actorNumber - 1) % this.PrefabsToInstantiate.Length;
Vector3 spawnPos;
Quaternion spawnRotation;
this.GetSpawnPoint(out spawnPos, out spawnRotation);
Camera.main.transform.position += spawnPos;
if (this.manualInstantiation)
{
this.ManualInstantiation(index, spawnPos, spawnRotation);
}
else
{
GameObject o = this.PrefabsToInstantiate[index];
o = PhotonNetwork.Instantiate(o.name, spawnPos, spawnRotation);
if (CharacterInstantiated != null)
{
CharacterInstantiated(o);
}
}
}
}
private void ManualInstantiation(int index, Vector3 position, Quaternion rotation)
{
GameObject prefab = this.PrefabsToInstantiate[index];
GameObject player;
if (this.differentPrefabs)
{
player = Instantiate(Resources.Load(string.Format("{0}{1}", prefab.name, this.localPrefabSuffix)) as GameObject, position, rotation);
}
else
{
player = Instantiate(prefab, position, rotation);
}
PhotonView photonView = player.GetComponent<PhotonView>();
if (PhotonNetwork.AllocateViewID(photonView))
{
object[] data =
{
index, player.transform.position, player.transform.rotation, photonView.ViewID
};
RaiseEventOptions raiseEventOptions = new RaiseEventOptions
{
Receivers = ReceiverGroup.Others,
CachingOption = EventCaching.AddToRoomCache
};
PhotonNetwork.RaiseEvent(this.manualInstantiationEventCode, data, raiseEventOptions, SendOptions.SendReliable);
if (CharacterInstantiated != null)
{
CharacterInstantiated(player);
}
}
else
{
Debug.LogError("Failed to allocate a ViewId.");
Destroy(player);
}
}
public void OnEvent(EventData photonEvent)
{
if (photonEvent.Code == this.manualInstantiationEventCode)
{
object[] data = photonEvent.CustomData as object[];
int prefabIndex = (int) data[0];
GameObject prefab = this.PrefabsToInstantiate[prefabIndex];
Vector3 position = (Vector3)data[1];
Quaternion rotation = (Quaternion)data[2];
GameObject player;
if (this.differentPrefabs)
{
player = Instantiate(Resources.Load(string.Format("{0}{1}", prefab.name, this.remotePrefabSuffix)) as GameObject, position, rotation);
}
else
{
player = Instantiate(prefab, position, Quaternion.identity);
}
PhotonView photonView = player.GetComponent<PhotonView>();
photonView.ViewID = (int) data[3];
}
}
#if UNITY_EDITOR
protected void OnValidate()
{
// Move any values from old SpawnPosition field to new SpawnPositions
if (this.SpawnPosition)
{
if (this.SpawnPoints == null)
this.SpawnPoints = new List<Transform>();
this.SpawnPoints.Add(this.SpawnPosition);
this.SpawnPosition = null;
}
}
#endif
/// <summary>
/// Override this method with any custom code for coming up with a spawn location.
/// </summary>
protected virtual void GetSpawnPoint(out Vector3 spawnPos, out Quaternion spawnRot)
{
// Fetch a point using the Sequence method indicated
Transform point = this.GetSpawnPoint();
if (point != null)
{
spawnPos = point.position;
spawnRot = point.rotation;
}
else
{
spawnPos = new Vector3(0, 0, 0);
spawnRot = new Quaternion(0, 0, 0, 1);
}
if (this.UseRandomOffset)
{
Random.InitState((int)(Time.time * 10000));
Vector3 random = Random.insideUnitSphere;
random.y = 0;
random = random.normalized;
spawnPos += this.PositionOffset * random;
}
}
protected virtual Transform GetSpawnPoint()
{
// Fetch a point using the Sequence method indicated
if (this.SpawnPoints == null || this.SpawnPoints.Count == 0)
{
return null;
}
switch (this.Sequence)
{
case SpawnSequence.Connection:
{
int id = PhotonNetwork.LocalPlayer.ActorNumber;
return this.SpawnPoints[(id == -1) ? 0 : id % this.SpawnPoints.Count];
}
case SpawnSequence.RoundRobin:
{
this.lastUsedSpawnPointIndex++;
if (this.lastUsedSpawnPointIndex >= this.SpawnPoints.Count)
{
this.lastUsedSpawnPointIndex = 0;
}
// Use Vector.Zero and Quaternion.Identity if we are dealing with no or a null spawnpoint.
return this.SpawnPoints[this.lastUsedSpawnPointIndex];
}
case SpawnSequence.Random:
{
return this.SpawnPoints[Random.Range(0, this.SpawnPoints.Count)];
}
default:
return null;
}
}
}
#if UNITY_EDITOR
[CustomEditor(typeof(CharacterInstantiation))]
public class CharacterInstantiationEditor : Editor
{
private SerializedProperty spawnPoints, prefabsToInstantiate, useRandomOffset, positionOffset, autoSpawn, manualInstantiation, differentPrefabs, localPrefabSuffix, remotePrefabSuffix, sequence, manualInstantiationEventCode;
private GUIStyle fieldBox;
private const int PAD = 6;
private void OnEnable()
{
this.spawnPoints = this.serializedObject.FindProperty("SpawnPoints");
this.prefabsToInstantiate = this.serializedObject.FindProperty("PrefabsToInstantiate");
this.useRandomOffset = this.serializedObject.FindProperty("UseRandomOffset");
this.positionOffset = this.serializedObject.FindProperty("PositionOffset");
this.autoSpawn = this.serializedObject.FindProperty("AutoSpawn");
this.manualInstantiation = this.serializedObject.FindProperty("manualInstantiation");
this.differentPrefabs = this.serializedObject.FindProperty("differentPrefabs");
this.localPrefabSuffix = this.serializedObject.FindProperty("localPrefabSuffix");
this.remotePrefabSuffix = this.serializedObject.FindProperty("remotePrefabSuffix");
this.manualInstantiationEventCode = this.serializedObject.FindProperty("manualInstantiationEventCode");
this.sequence = this.serializedObject.FindProperty("Sequence");
}
public override void OnInspectorGUI()
{
EditorGUI.BeginChangeCheck();
this.EditableReferenceList(this.prefabsToInstantiate, new GUIContent(this.prefabsToInstantiate.displayName, this.prefabsToInstantiate.tooltip), this.fieldBox);
this.EditableReferenceList(this.spawnPoints, new GUIContent(this.spawnPoints.displayName, this.spawnPoints.tooltip), this.fieldBox);
if (this.fieldBox == null)
{
this.fieldBox = new GUIStyle("HelpBox") { padding = new RectOffset(PAD, PAD, PAD, PAD) };
}
// Spawn Pattern
EditorGUILayout.LabelField("Spawn Pattern Setup");
EditorGUILayout.BeginVertical(this.fieldBox);
EditorGUILayout.PropertyField(this.sequence);
EditorGUILayout.PropertyField(this.useRandomOffset);
if (this.useRandomOffset.boolValue)
{
EditorGUILayout.PropertyField(this.positionOffset);
}
EditorGUILayout.EndVertical();
// Auto/Manual Spawn
EditorGUILayout.LabelField("Network Instantiation Setup");
EditorGUILayout.BeginVertical(this.fieldBox);
EditorGUILayout.PropertyField(this.autoSpawn);
EditorGUILayout.PropertyField(this.manualInstantiation);
if (this.manualInstantiation.boolValue)
{
EditorGUILayout.PropertyField(this.manualInstantiationEventCode);
EditorGUILayout.PropertyField(this.differentPrefabs);
if (this.differentPrefabs.boolValue)
{
EditorGUILayout.PropertyField(this.localPrefabSuffix);
EditorGUILayout.PropertyField(this.remotePrefabSuffix);
}
}
EditorGUILayout.EndVertical();
if (EditorGUI.EndChangeCheck())
{
this.serializedObject.ApplyModifiedProperties();
}
}
/// <summary>
/// Create a basic rendered list of objects from a SerializedProperty list or array, with Add/Destroy buttons.
/// </summary>
public void EditableReferenceList(SerializedProperty list, GUIContent gc, GUIStyle style = null)
{
EditorGUILayout.LabelField(gc);
if (style == null)
style = new GUIStyle("HelpBox") { padding = new RectOffset(6, 6, 6, 6) };
EditorGUILayout.BeginVertical(style);
int count = list.arraySize;
if (count == 0)
{
if (GUI.Button(EditorGUILayout.GetControlRect(GUILayout.MaxWidth(20)), "+", (GUIStyle)"minibutton"))
{
list.InsertArrayElementAtIndex(0);
list.GetArrayElementAtIndex(0).objectReferenceValue = null;
}
}
else
{
// List Elements and Delete buttons
for (int i = 0; i < list.arraySize; ++i)
{
EditorGUILayout.BeginHorizontal();
bool add = (GUI.Button(EditorGUILayout.GetControlRect(GUILayout.MaxWidth(20)), "+", (GUIStyle)"minibutton"));
EditorGUILayout.PropertyField(list.GetArrayElementAtIndex(i), GUIContent.none);
bool remove = (GUI.Button(EditorGUILayout.GetControlRect(GUILayout.MaxWidth(20)), "x", (GUIStyle)"minibutton"));
EditorGUILayout.EndHorizontal();
if (add)
{
list.InsertArrayElementAtIndex(i);
list.GetArrayElementAtIndex(i).objectReferenceValue = null;
EditorGUILayout.EndHorizontal();
break;
}
if (remove)
{
list.DeleteArrayElementAtIndex(i);
EditorGUILayout.EndHorizontal();
break;
}
}
}
EditorGUILayout.EndVertical();
}
}
#endif
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 6eba5753a72c3244c851d7450564c8bd
timeCreated: 1445512365
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,55 @@
// ----------------------------------------------------------------------------
// <copyright file="FirstPersonController.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN- Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Custom fist person character controller.
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------
namespace ExitGames.Demos.DemoPunVoice {
using UnityEngine;
public class FirstPersonController : BaseController {
[SerializeField]
private MouseLookHelper mouseLook = new MouseLookHelper();
private float oldYRotation;
private Quaternion velRotation;
public Vector3 Velocity {
get { return this.rigidBody.velocity; }
}
protected override void SetCamera() {
base.SetCamera();
this.mouseLook.Init(this.transform, this.camTrans);
}
protected override void Move(float h, float v) {
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = this.camTrans.forward * v + this.camTrans.right * h;
desiredMove.x = desiredMove.x * this.speed;
desiredMove.z = desiredMove.z * this.speed;
desiredMove.y = 0;
this.rigidBody.velocity = desiredMove;
}
private void Update() {
this.RotateView();
}
private void RotateView() {
// get the rotation before it's changed
this.oldYRotation = this.transform.eulerAngles.y;
this.mouseLook.LookRotation(this.transform, this.camTrans);
// Rotate the rigidbody velocity to match the new direction that the character is looking
this.velRotation = Quaternion.AngleAxis(this.transform.eulerAngles.y - this.oldYRotation, Vector3.up);
this.rigidBody.velocity = this.velRotation * this.rigidBody.velocity;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 8cf6d7f07293ceb45bb4121e509661d7
timeCreated: 1446184073
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,88 @@
// ----------------------------------------------------------------------------
// <copyright file="Highlighter.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN- Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Class that highlights the Photon Voice features by toggling isometric view
// icons for the two components Recorder and Speaker.
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------
#pragma warning disable 0649 // Field is never assigned to, and will always have its default value
namespace ExitGames.Demos.DemoPunVoice
{
using UnityEngine;
using UnityEngine.UI;
using Photon.Voice.Unity;
using Photon.Voice.PUN;
[RequireComponent(typeof(Canvas))]
public class Highlighter : MonoBehaviour
{
private Canvas canvas;
private PhotonVoiceView photonVoiceView;
[SerializeField]
private Image recorderSprite;
[SerializeField]
private Image speakerSprite;
[SerializeField]
private Text bufferLagText;
private bool showSpeakerLag;
private void OnEnable()
{
ChangePOV.CameraChanged += this.ChangePOV_CameraChanged;
VoiceDemoUI.DebugToggled += this.VoiceDemoUI_DebugToggled;
}
private void OnDisable()
{
ChangePOV.CameraChanged -= this.ChangePOV_CameraChanged;
VoiceDemoUI.DebugToggled -= this.VoiceDemoUI_DebugToggled;
}
private void VoiceDemoUI_DebugToggled(bool debugMode)
{
this.showSpeakerLag = debugMode;
}
private void ChangePOV_CameraChanged(Camera camera)
{
this.canvas.worldCamera = camera;
}
private void Awake()
{
this.canvas = this.GetComponent<Canvas>();
if (this.canvas != null && this.canvas.worldCamera == null) { this.canvas.worldCamera = Camera.main; }
this.photonVoiceView = this.GetComponentInParent<PhotonVoiceView>();
}
// Update is called once per frame
private void Update()
{
this.recorderSprite.enabled = this.photonVoiceView.IsRecording;
this.speakerSprite.enabled = this.photonVoiceView.IsSpeaking;
this.bufferLagText.enabled = this.showSpeakerLag && this.photonVoiceView.IsSpeaking;
if (this.bufferLagText.enabled)
{
this.bufferLagText.text = string.Format("{0}", this.photonVoiceView.SpeakerInUse.Lag);
}
}
private void LateUpdate()
{
if (this.canvas == null || this.canvas.worldCamera == null) { return; } // should not happen, throw error
this.transform.rotation = Quaternion.Euler(0f, this.canvas.worldCamera.transform.eulerAngles.y, 0f); //canvas.worldCamera.transform.rotation;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e4713853bfdc862459ae0bb66b2b3750
timeCreated: 1445530258
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,59 @@
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
[Serializable]
public class MouseLookHelper {
public float XSensitivity = 2f;
public float YSensitivity = 2f;
public bool clampVerticalRotation = true;
public float MinimumX = -90F;
public float MaximumX = 90F;
public bool smooth;
public float smoothTime = 5f;
private Quaternion m_CharacterTargetRot;
private Quaternion m_CameraTargetRot;
public void Init(Transform character, Transform camera) {
this.m_CharacterTargetRot = character.localRotation;
this.m_CameraTargetRot = camera.localRotation;
}
public void LookRotation(Transform character, Transform camera) {
float yRot = CrossPlatformInputManager.GetAxis("Mouse X") * this.XSensitivity;
float xRot = CrossPlatformInputManager.GetAxis("Mouse Y") * this.YSensitivity;
this.m_CharacterTargetRot *= Quaternion.Euler(0f, yRot, 0f);
this.m_CameraTargetRot *= Quaternion.Euler(-xRot, 0f, 0f);
if (this.clampVerticalRotation) {
this.m_CameraTargetRot = this.ClampRotationAroundXAxis(this.m_CameraTargetRot);
}
if (this.smooth) {
character.localRotation = Quaternion.Slerp(character.localRotation, this.m_CharacterTargetRot,
this.smoothTime * Time.deltaTime);
camera.localRotation = Quaternion.Slerp(camera.localRotation, this.m_CameraTargetRot,
this.smoothTime * Time.deltaTime);
}
else {
character.localRotation = this.m_CharacterTargetRot;
camera.localRotation = this.m_CameraTargetRot;
}
}
private Quaternion ClampRotationAroundXAxis(Quaternion q) {
q.x /= q.w;
q.y /= q.w;
q.z /= q.w;
q.w = 1.0f;
float angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan(q.x);
angleX = Mathf.Clamp(angleX, this.MinimumX, this.MaximumX);
q.x = Mathf.Tan(0.5f * Mathf.Deg2Rad * angleX);
return q;
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 7cec8b58f1f52c74ba0226ade0cdcc53
timeCreated: 1446133287
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,47 @@
// ----------------------------------------------------------------------------
// <copyright file="OrthographicController.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN- Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Character controller class for Orthographic camera mode.
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------
namespace ExitGames.Demos.DemoPunVoice {
using UnityEngine;
public class OrthographicController : ThirdPersonController {
public float smoothing = 5f; // The speed with which the camera will be following.
private Vector3 offset;
protected override void Init() {
base.Init();
// should be default camera
this.ControllerCamera = Camera.main;//GameObject.Find("OrthographicCamera").GetComponent<Camera>();
}
protected override void SetCamera() {
base.SetCamera();
// Calculate the initial offset.
this.offset = this.camTrans.position - this.transform.position;
}
protected override void Move(float h, float v) {
base.Move(h, v);
this.CameraFollow();
}
private void CameraFollow() {
// Create a postion the camera is aiming for based on the offset from the target.
Vector3 targetCamPos = this.transform.position + this.offset;
// Smoothly interpolate between the camera's current position and it's target position.
this.camTrans.position = Vector3.Lerp(this.camTrans.position, targetCamPos, this.smoothing * Time.deltaTime);
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 0df83d9cfe88c7641b20a46c5228418c
timeCreated: 1446184100
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,41 @@
// ----------------------------------------------------------------------------
// <copyright file="SoundsForJoinAndLeave.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN- Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Script to play sound when player joins or leaves room.
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------
namespace ExitGames.Demos.DemoPunVoice
{
using Photon.Pun;
using UnityEngine;
using Player = Photon.Realtime.Player;
public class SoundsForJoinAndLeave : MonoBehaviourPunCallbacks
{
public AudioClip JoinClip;
public AudioClip LeaveClip;
private AudioSource source;
public override void OnPlayerEnteredRoom(Player newPlayer)
{
if (this.JoinClip != null)
{
if (this.source == null) this.source = FindObjectOfType<AudioSource>();
this.source.PlayOneShot(this.JoinClip);
}
}
public override void OnPlayerLeftRoom(Player otherPlayer)
{
if (this.LeaveClip != null)
{
if (this.source == null) this.source = FindObjectOfType<AudioSource>();
this.source.PlayOneShot(this.LeaveClip);
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 6a12b1ae2d50d2749bd1c8203cbb423c
timeCreated: 1455025975
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,26 @@
// ----------------------------------------------------------------------------
// <copyright file="ThirdPersonController.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN- Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Third person character controller class.
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------
namespace ExitGames.Demos.DemoPunVoice {
using UnityEngine;
public class ThirdPersonController : BaseController {
[SerializeField]
private float movingTurnSpeed = 360;
protected override void Move(float h, float v) {
this.rigidBody.velocity = v * this.speed * this.transform.forward;
this.transform.rotation *= Quaternion.AngleAxis(this.movingTurnSpeed * h * Time.deltaTime, Vector3.up);
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: ae58c0b74b23bf64e856c46783d1f181
timeCreated: 1446184084
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,424 @@
// ----------------------------------------------------------------------------
// <copyright file="VoiceDemoUI.cs" company="Exit Games GmbH">
// Photon Voice Demo for PUN - Copyright (C) Exit Games GmbH
// </copyright>
// <summary>
// UI manager class for the PUN Voice Demo
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------
using System;
using Photon.Voice.Unity;
using Photon.Voice.PUN;
#pragma warning disable 0649 // Field is never assigned to, and will always have its default value
namespace ExitGames.Demos.DemoPunVoice
{
using Photon.Pun;
using UnityEngine;
using UnityEngine.UI;
using Client.Photon;
#if !UNITY_EDITOR && UNITY_PS4
using Sony.NP;
#elif !UNITY_EDITOR && UNITY_SHARLIN
using System.Runtime.InteropServices;
#endif
public class VoiceDemoUI : MonoBehaviour
{
#if !UNITY_EDITOR && UNITY_SHARLIN
[DllImport("PhotonVoiceLocalUserIDPlugin")]
private static extern int egpvgetLocalUserID(); // returns the user ID of the user at index 0 in the list of local users
#endif
[SerializeField]
private Text punState;
[SerializeField]
private Text voiceState;
private PhotonVoiceNetwork punVoiceNetwork;
private Canvas canvas;
[SerializeField]
private Button punSwitch;
private Text punSwitchText;
[SerializeField]
private Button voiceSwitch;
private Text voiceSwitchText;
[SerializeField]
private Button calibrateButton;
private Text calibrateText;
[SerializeField]
private Text voiceDebugText;
public Recorder recorder;
[SerializeField]
private GameObject inGameSettings;
[SerializeField]
private GameObject globalSettings;
[SerializeField]
private Text devicesInfoText;
private GameObject debugGO;
private bool debugMode;
private float volumeBeforeMute;
private DebugLevel previousDebugLevel;
public bool DebugMode
{
get
{
return this.debugMode;
}
set
{
this.debugMode = value;
this.debugGO.SetActive(this.debugMode);
this.voiceDebugText.text = String.Empty;
if (this.debugMode)
{
this.previousDebugLevel = this.punVoiceNetwork.Client.LoadBalancingPeer.DebugOut;
this.punVoiceNetwork.Client.LoadBalancingPeer.DebugOut = DebugLevel.ALL;
}
else
{
this.punVoiceNetwork.Client.LoadBalancingPeer.DebugOut = this.previousDebugLevel;
}
if (DebugToggled != null)
{
DebugToggled(this.debugMode);
}
}
}
public delegate void OnDebugToggle(bool debugMode);
public static event OnDebugToggle DebugToggled;
[SerializeField]
private int calibrationMilliSeconds = 2000;
private void Awake()
{
this.punVoiceNetwork = PhotonVoiceNetwork.Instance;
}
private void OnEnable()
{
ChangePOV.CameraChanged += this.OnCameraChanged;
BetterToggle.ToggleValueChanged += this.BetterToggle_ToggleValueChanged;
CharacterInstantiation.CharacterInstantiated += this.CharacterInstantiation_CharacterInstantiated;
this.punVoiceNetwork.Client.StateChanged += this.VoiceClientStateChanged;
PhotonNetwork.NetworkingClient.StateChanged += this.PunClientStateChanged;
}
private void OnDisable()
{
ChangePOV.CameraChanged -= this.OnCameraChanged;
BetterToggle.ToggleValueChanged -= this.BetterToggle_ToggleValueChanged;
CharacterInstantiation.CharacterInstantiated -= this.CharacterInstantiation_CharacterInstantiated;
this.punVoiceNetwork.Client.StateChanged -= this.VoiceClientStateChanged;
PhotonNetwork.NetworkingClient.StateChanged -= this.PunClientStateChanged;
}
private void CharacterInstantiation_CharacterInstantiated(GameObject character)
{
if (this.recorder) // probably using a global recorder
{
return;
}
PhotonVoiceView photonVoiceView = character.GetComponent<PhotonVoiceView>();
if (photonVoiceView.IsRecorder)
{
this.recorder = photonVoiceView.RecorderInUse;
}
}
private void InitToggles(Toggle[] toggles)
{
if (toggles == null) { return; }
for (int i = 0; i < toggles.Length; i++)
{
Toggle toggle = toggles[i];
switch (toggle.name)
{
case "Mute":
toggle.isOn = AudioListener.volume <= 0.001f;
break;
case "VoiceDetection":
toggle.isOn = this.recorder != null && this.recorder.VoiceDetection;
break;
case "DebugVoice":
toggle.isOn = this.DebugMode;
break;
case "Transmit":
toggle.isOn = this.recorder != null && this.recorder.TransmitEnabled;
break;
case "DebugEcho":
toggle.isOn = this.recorder != null && this.recorder.DebugEchoMode;
break;
case "AutoConnectAndJoin":
toggle.isOn = this.punVoiceNetwork.AutoConnectAndJoin;
break;
case "AutoLeaveAndDisconnect":
toggle.isOn = this.punVoiceNetwork.AutoLeaveAndDisconnect;
break;
}
}
}
private void BetterToggle_ToggleValueChanged(Toggle toggle)
{
switch (toggle.name)
{
case "Mute":
//AudioListener.pause = toggle.isOn;
if (toggle.isOn)
{
this.volumeBeforeMute = AudioListener.volume;
AudioListener.volume = 0f;
}
else
{
AudioListener.volume = this.volumeBeforeMute;
this.volumeBeforeMute = 0f;
}
break;
case "Transmit":
if (this.recorder)
{
this.recorder.TransmitEnabled = toggle.isOn;
}
break;
case "VoiceDetection":
if (this.recorder)
{
this.recorder.VoiceDetection = toggle.isOn;
}
break;
case "DebugEcho":
if (this.recorder)
{
this.recorder.DebugEchoMode = toggle.isOn;
}
break;
case "DebugVoice":
this.DebugMode = toggle.isOn;
break;
case "AutoConnectAndJoin":
this.punVoiceNetwork.AutoConnectAndJoin = toggle.isOn;
break;
case "AutoLeaveAndDisconnect":
this.punVoiceNetwork.AutoLeaveAndDisconnect = toggle.isOn;
break;
}
}
private void OnCameraChanged(Camera newCamera)
{
this.canvas.worldCamera = newCamera;
}
private void Start()
{
this.canvas = this.GetComponentInChildren<Canvas>();
if (this.punSwitch != null)
{
this.punSwitchText = this.punSwitch.GetComponentInChildren<Text>();
this.punSwitch.onClick.AddListener(this.PunSwitchOnClick);
}
if (this.voiceSwitch != null)
{
this.voiceSwitchText = this.voiceSwitch.GetComponentInChildren<Text>();
this.voiceSwitch.onClick.AddListener(this.VoiceSwitchOnClick);
}
if (this.calibrateButton != null)
{
this.calibrateButton.onClick.AddListener(this.CalibrateButtonOnClick);
this.calibrateText = this.calibrateButton.GetComponentInChildren<Text>();
}
if (this.punState != null)
{
this.debugGO = this.punState.transform.parent.gameObject;
}
this.volumeBeforeMute = AudioListener.volume;
this.previousDebugLevel = this.punVoiceNetwork.Client.LoadBalancingPeer.DebugOut;
if (this.globalSettings != null)
{
this.globalSettings.SetActive(true);
this.InitToggles(this.globalSettings.GetComponentsInChildren<Toggle>());
}
if (this.devicesInfoText != null)
{
if (UnityMicrophone.devices == null || UnityMicrophone.devices.Length == 0)
{
this.devicesInfoText.enabled = true;
this.devicesInfoText.color = Color.red;
this.devicesInfoText.text = "No microphone device detected!";
}
else if (UnityMicrophone.devices.Length == 1)
{
this.devicesInfoText.text = string.Format("Mic.: {0}", UnityMicrophone.devices[0]);
}
else
{
this.devicesInfoText.text = string.Format("Multi.Mic.Devices:\n0. {0} (active)\n", UnityMicrophone.devices[0]);
for (int i = 1; i < UnityMicrophone.devices.Length; i++)
{
this.devicesInfoText.text = string.Concat(this.devicesInfoText.text, string.Format("{0}. {1}\n", i, UnityMicrophone.devices[i]));
}
}
}
#if !UNITY_EDITOR && UNITY_PS4
UserProfiles.LocalUsers localUsers = new UserProfiles.LocalUsers();
UserProfiles.GetLocalUsers(localUsers);
int userID = localUsers.LocalUsersIds[0].UserId.Id;
punVoiceNetwork.PlayStationUserID = userID;
#elif !UNITY_EDITOR && UNITY_SHARLIN
punVoiceNetwork.PlayStationUserID = egpvgetLocalUserID();
#endif
}
private void PunSwitchOnClick()
{
if (PhotonNetwork.NetworkClientState == Photon.Realtime.ClientState.Joined)
{
PhotonNetwork.Disconnect();
}
else if (PhotonNetwork.NetworkClientState == Photon.Realtime.ClientState.Disconnected ||
PhotonNetwork.NetworkClientState == Photon.Realtime.ClientState.PeerCreated)
{
PhotonNetwork.ConnectUsingSettings();
}
}
private void VoiceSwitchOnClick()
{
if (this.punVoiceNetwork.ClientState == Photon.Realtime.ClientState.Joined)
{
this.punVoiceNetwork.Disconnect();
}
else if (this.punVoiceNetwork.ClientState == Photon.Realtime.ClientState.PeerCreated
|| this.punVoiceNetwork.ClientState == Photon.Realtime.ClientState.Disconnected)
{
this.punVoiceNetwork.ConnectAndJoinRoom();
}
}
private void CalibrateButtonOnClick()
{
if (this.recorder && !this.recorder.VoiceDetectorCalibrating)
{
this.recorder.VoiceDetectorCalibrate(this.calibrationMilliSeconds);
}
}
private void Update()
{
// editor only two-ways binding for toggles
#if UNITY_EDITOR
this.InitToggles(this.globalSettings.GetComponentsInChildren<Toggle>());
#endif
if (this.recorder != null && this.recorder.LevelMeter != null)
{
this.voiceDebugText.text = string.Format("Amp: avg. {0:0.000000}, peak {1:0.000000}", this.recorder.LevelMeter.CurrentAvgAmp, this.recorder.LevelMeter.CurrentPeakAmp);
}
}
private void PunClientStateChanged(Photon.Realtime.ClientState fromState, Photon.Realtime.ClientState toState)
{
this.punState.text = string.Format("PUN: {0}", toState);
switch (toState)
{
case Photon.Realtime.ClientState.PeerCreated:
case Photon.Realtime.ClientState.Disconnected:
this.punSwitch.interactable = true;
this.punSwitchText.text = "PUN Connect";
break;
case Photon.Realtime.ClientState.Joined:
this.punSwitch.interactable = true;
this.punSwitchText.text = "PUN Disconnect";
break;
default:
this.punSwitch.interactable = false;
this.punSwitchText.text = "PUN busy";
break;
}
this.UpdateUiBasedOnVoiceState(this.punVoiceNetwork.ClientState);
}
private void VoiceClientStateChanged(Photon.Realtime.ClientState fromState, Photon.Realtime.ClientState toState)
{
this.UpdateUiBasedOnVoiceState(toState);
}
private void UpdateUiBasedOnVoiceState(Photon.Realtime.ClientState voiceClientState)
{
this.voiceState.text = string.Format("PhotonVoice: {0}", voiceClientState);
switch (voiceClientState)
{
case Photon.Realtime.ClientState.Joined:
this.voiceSwitch.interactable = true;
this.inGameSettings.SetActive(true);
this.voiceSwitchText.text = "Voice Disconnect";
this.InitToggles(this.inGameSettings.GetComponentsInChildren<Toggle>());
if (this.recorder != null)
{
this.calibrateButton.interactable = !this.recorder.VoiceDetectorCalibrating;
this.calibrateText.text = this.recorder.VoiceDetectorCalibrating ? "Calibrating" : string.Format("Calibrate ({0}s)", this.calibrationMilliSeconds / 1000);
}
else
{
this.calibrateButton.interactable = false;
this.calibrateText.text = "Unavailable";
}
break;
case Photon.Realtime.ClientState.PeerCreated:
case Photon.Realtime.ClientState.Disconnected:
if (PhotonNetwork.InRoom)
{
this.voiceSwitch.interactable = true;
this.voiceSwitchText.text = "Voice Connect";
this.voiceDebugText.text = String.Empty;
}
else
{
this.voiceSwitch.interactable = false;
this.voiceSwitchText.text = "Voice N/A";
this.voiceDebugText.text = String.Empty;
}
this.calibrateButton.interactable = false;
this.voiceSwitchText.text = "Voice Connect";
this.calibrateText.text = "Unavailable";
this.inGameSettings.SetActive(false);
break;
default:
this.voiceSwitch.interactable = false;
this.voiceSwitchText.text = "Voice busy";
break;
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: ab16f3006dd219540927ecb90f88515e
timeCreated: 1455021665
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: