first commit

This commit is contained in:
2022-07-08 09:14:55 +08:00
commit 4d6bd72555
1123 changed files with 456307 additions and 0 deletions

View File

@@ -0,0 +1,130 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CameraWork.cs" company="Exit Games GmbH">
// Part of: Photon Unity Networking Demos
// </copyright>
// <summary>
// Used in PUN Basics Tutorial to deal with the Camera work to follow the player
// </summary>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------
using UnityEngine;
namespace Photon.Pun.Demo.PunBasics
{
/// <summary>
/// Camera work. Follow a target
/// </summary>
public class CameraWork : MonoBehaviour
{
#region Private Fields
[Tooltip("The distance in the local x-z plane to the target")]
[SerializeField]
private float distance = 7.0f;
[Tooltip("The height we want the camera to be above the target")]
[SerializeField]
private float height = 3.0f;
[Tooltip("Allow the camera to be offseted vertically from the target, for example giving more view of the sceneray and less ground.")]
[SerializeField]
private Vector3 centerOffset = Vector3.zero;
[Tooltip("Set this as false if a component of a prefab being instanciated by Photon Network, and manually call OnStartFollowing() when and if needed.")]
[SerializeField]
private bool followOnStart = false;
[Tooltip("The Smoothing for the camera to follow the target")]
[SerializeField]
private float smoothSpeed = 0.125f;
// cached transform of the target
Transform cameraTransform;
// maintain a flag internally to reconnect if target is lost or camera is switched
bool isFollowing;
// Cache for camera offset
Vector3 cameraOffset = Vector3.zero;
#endregion
#region MonoBehaviour Callbacks
/// <summary>
/// MonoBehaviour method called on GameObject by Unity during initialization phase
/// </summary>
void Start()
{
// Start following the target if wanted.
if (followOnStart)
{
OnStartFollowing();
}
}
void LateUpdate()
{
// The transform target may not destroy on level load,
// so we need to cover corner cases where the Main Camera is different everytime we load a new scene, and reconnect when that happens
if (cameraTransform == null && isFollowing)
{
OnStartFollowing();
}
// only follow is explicitly declared
if (isFollowing) {
Follow ();
}
}
#endregion
#region Public Methods
/// <summary>
/// Raises the start following event.
/// Use this when you don't know at the time of editing what to follow, typically instances managed by the photon network.
/// </summary>
public void OnStartFollowing()
{
cameraTransform = Camera.main.transform;
isFollowing = true;
// we don't smooth anything, we go straight to the right camera shot
Cut();
}
#endregion
#region Private Methods
/// <summary>
/// Follow the target smoothly
/// </summary>
void Follow()
{
cameraOffset.z = -distance;
cameraOffset.y = height;
cameraTransform.position = Vector3.Lerp(cameraTransform.position, this.transform.position +this.transform.TransformVector(cameraOffset), smoothSpeed*Time.deltaTime);
cameraTransform.LookAt(this.transform.position + centerOffset);
}
void Cut()
{
cameraOffset.z = -distance;
cameraOffset.y = height;
cameraTransform.position = this.transform.position + this.transform.TransformVector(cameraOffset);
cameraTransform.LookAt(this.transform.position + centerOffset);
}
#endregion
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fd08475b23aa548b7b9d28397d430b32
labels:
- ExitGames
- PUN
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,174 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Launcher.cs" company="Exit Games GmbH">
// Part of: Photon Unity Networking Demos
// </copyright>
// <summary>
// Used in "PUN Basic tutorial" to handle typical game management requirements
// </summary>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------
using UnityEngine;
using UnityEngine.SceneManagement;
using Photon.Realtime;
namespace Photon.Pun.Demo.PunBasics
{
#pragma warning disable 649
/// <summary>
/// Game manager.
/// Connects and watch Photon Status, Instantiate Player
/// Deals with quiting the room and the game
/// Deals with level loading (outside the in room synchronization)
/// </summary>
public class GameManager : MonoBehaviourPunCallbacks
{
#region Public Fields
static public GameManager Instance;
#endregion
#region Private Fields
private GameObject instance;
[Tooltip("The prefab to use for representing the player")]
[SerializeField]
private GameObject playerPrefab;
#endregion
#region MonoBehaviour CallBacks
/// <summary>
/// MonoBehaviour method called on GameObject by Unity during initialization phase.
/// </summary>
void Start()
{
Instance = this;
// in case we started this demo with the wrong scene being active, simply load the menu scene
if (!PhotonNetwork.IsConnected)
{
SceneManager.LoadScene("PunBasics-Launcher");
return;
}
if (playerPrefab == null) { // #Tip Never assume public properties of Components are filled up properly, always check and inform the developer of it.
Debug.LogError("<Color=Red><b>Missing</b></Color> playerPrefab Reference. Please set it up in GameObject 'Game Manager'", this);
} else {
if (PlayerManager.LocalPlayerInstance==null)
{
Debug.LogFormat("We are Instantiating LocalPlayer from {0}", SceneManagerHelper.ActiveSceneName);
// we're in a room. spawn a character for the local player. it gets synced by using PhotonNetwork.Instantiate
PhotonNetwork.Instantiate(this.playerPrefab.name, new Vector3(0f,5f,0f), Quaternion.identity, 0);
}else{
Debug.LogFormat("Ignoring scene load for {0}", SceneManagerHelper.ActiveSceneName);
}
}
}
/// <summary>
/// MonoBehaviour method called on GameObject by Unity on every frame.
/// </summary>
void Update()
{
// "back" button of phone equals "Escape". quit app if that's pressed
if (Input.GetKeyDown(KeyCode.Escape))
{
QuitApplication();
}
}
#endregion
#region Photon Callbacks
/// <summary>
/// Called when a Photon Player got connected. We need to then load a bigger scene.
/// </summary>
/// <param name="other">Other.</param>
public override void OnPlayerEnteredRoom( Player other )
{
Debug.Log( "OnPlayerEnteredRoom() " + other.NickName); // not seen if you're the player connecting
if ( PhotonNetwork.IsMasterClient )
{
Debug.LogFormat( "OnPlayerEnteredRoom IsMasterClient {0}", PhotonNetwork.IsMasterClient ); // called before OnPlayerLeftRoom
LoadArena();
}
}
/// <summary>
/// Called when a Photon Player got disconnected. We need to load a smaller scene.
/// </summary>
/// <param name="other">Other.</param>
public override void OnPlayerLeftRoom( Player other )
{
Debug.Log( "OnPlayerLeftRoom() " + other.NickName ); // seen when other disconnects
if ( PhotonNetwork.IsMasterClient )
{
Debug.LogFormat( "OnPlayerEnteredRoom IsMasterClient {0}", PhotonNetwork.IsMasterClient ); // called before OnPlayerLeftRoom
LoadArena();
}
}
/// <summary>
/// Called when the local player left the room. We need to load the launcher scene.
/// </summary>
public override void OnLeftRoom()
{
SceneManager.LoadScene("PunBasics-Launcher");
}
#endregion
#region Public Methods
public void LeaveRoom()
{
PhotonNetwork.LeaveRoom();
}
public void QuitApplication()
{
Application.Quit();
}
#endregion
#region Private Methods
void LoadArena()
{
if ( ! PhotonNetwork.IsMasterClient )
{
Debug.LogError( "PhotonNetwork : Trying to Load a level but we are not the master Client" );
}
Debug.LogFormat( "PhotonNetwork : Loading Level : {0}", PhotonNetwork.CurrentRoom.PlayerCount );
PhotonNetwork.LoadLevel("PunBasics-Room for "+PhotonNetwork.CurrentRoom.PlayerCount);
}
#endregion
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4433564e76b1940028e7e531f171050d
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,226 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Launcher.cs" company="Exit Games GmbH">
// Part of: Photon Unity Networking Demos
// </copyright>
// <summary>
// Used in "PUN Basic tutorial" to connect, and join/create room automatically
// </summary>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------
using UnityEngine;
using UnityEngine.UI;
using Photon.Realtime;
namespace Photon.Pun.Demo.PunBasics
{
#pragma warning disable 649
/// <summary>
/// Launch manager. Connect, join a random room or create one if none or all full.
/// </summary>
public class Launcher : MonoBehaviourPunCallbacks
{
#region Private Serializable Fields
[Tooltip("The Ui Panel to let the user enter name, connect and play")]
[SerializeField]
private GameObject controlPanel;
[Tooltip("The Ui Text to inform the user about the connection progress")]
[SerializeField]
private Text feedbackText;
[Tooltip("The maximum number of players per room")]
[SerializeField]
private byte maxPlayersPerRoom = 4;
[Tooltip("The UI Loader Anime")]
[SerializeField]
private LoaderAnime loaderAnime;
#endregion
#region Private Fields
/// <summary>
/// Keep track of the current process. Since connection is asynchronous and is based on several callbacks from Photon,
/// we need to keep track of this to properly adjust the behavior when we receive call back by Photon.
/// Typically this is used for the OnConnectedToMaster() callback.
/// </summary>
bool isConnecting;
/// <summary>
/// This client's version number. Users are separated from each other by gameVersion (which allows you to make breaking changes).
/// </summary>
string gameVersion = "1";
#endregion
#region MonoBehaviour CallBacks
/// <summary>
/// MonoBehaviour method called on GameObject by Unity during early initialization phase.
/// </summary>
void Awake()
{
if (loaderAnime==null)
{
Debug.LogError("<Color=Red><b>Missing</b></Color> loaderAnime Reference.",this);
}
// #Critical
// this makes sure we can use PhotonNetwork.LoadLevel() on the master client and all clients in the same room sync their level automatically
PhotonNetwork.AutomaticallySyncScene = true;
}
#endregion
#region Public Methods
/// <summary>
/// Start the connection process.
/// - If already connected, we attempt joining a random room
/// - if not yet connected, Connect this application instance to Photon Cloud Network
/// </summary>
public void Connect()
{
// we want to make sure the log is clear everytime we connect, we might have several failed attempted if connection failed.
feedbackText.text = "";
// keep track of the will to join a room, because when we come back from the game we will get a callback that we are connected, so we need to know what to do then
isConnecting = true;
// hide the Play button for visual consistency
controlPanel.SetActive(false);
// start the loader animation for visual effect.
if (loaderAnime!=null)
{
loaderAnime.StartLoaderAnimation();
}
// we check if we are connected or not, we join if we are , else we initiate the connection to the server.
if (PhotonNetwork.IsConnected)
{
LogFeedback("Joining Room...");
// #Critical we need at this point to attempt joining a Random Room. If it fails, we'll get notified in OnJoinRandomFailed() and we'll create one.
PhotonNetwork.JoinRandomRoom();
}else{
LogFeedback("Connecting...");
// #Critical, we must first and foremost connect to Photon Online Server.
PhotonNetwork.ConnectUsingSettings();
PhotonNetwork.GameVersion = this.gameVersion;
}
}
/// <summary>
/// Logs the feedback in the UI view for the player, as opposed to inside the Unity Editor for the developer.
/// </summary>
/// <param name="message">Message.</param>
void LogFeedback(string message)
{
// we do not assume there is a feedbackText defined.
if (feedbackText == null) {
return;
}
// add new messages as a new line and at the bottom of the log.
feedbackText.text += System.Environment.NewLine+message;
}
#endregion
#region MonoBehaviourPunCallbacks CallBacks
// below, we implement some callbacks of PUN
// you can find PUN's callbacks in the class MonoBehaviourPunCallbacks
/// <summary>
/// Called after the connection to the master is established and authenticated
/// </summary>
public override void OnConnectedToMaster()
{
// we don't want to do anything if we are not attempting to join a room.
// this case where isConnecting is false is typically when you lost or quit the game, when this level is loaded, OnConnectedToMaster will be called, in that case
// we don't want to do anything.
if (isConnecting)
{
LogFeedback("OnConnectedToMaster: Next -> try to Join Random Room");
Debug.Log("PUN Basics Tutorial/Launcher: OnConnectedToMaster() was called by PUN. Now this client is connected and could join a room.\n Calling: PhotonNetwork.JoinRandomRoom(); Operation will fail if no room found");
// #Critical: The first we try to do is to join a potential existing room. If there is, good, else, we'll be called back with OnJoinRandomFailed()
PhotonNetwork.JoinRandomRoom();
}
}
/// <summary>
/// Called when a JoinRandom() call failed. The parameter provides ErrorCode and message.
/// </summary>
/// <remarks>
/// Most likely all rooms are full or no rooms are available. <br/>
/// </remarks>
public override void OnJoinRandomFailed(short returnCode, string message)
{
LogFeedback("<Color=Red>OnJoinRandomFailed</Color>: Next -> Create a new Room");
Debug.Log("PUN Basics Tutorial/Launcher:OnJoinRandomFailed() was called by PUN. No random room available, so we create one.\nCalling: PhotonNetwork.CreateRoom");
// #Critical: we failed to join a random room, maybe none exists or they are all full. No worries, we create a new room.
PhotonNetwork.CreateRoom(null, new RoomOptions { MaxPlayers = this.maxPlayersPerRoom});
}
/// <summary>
/// Called after disconnecting from the Photon server.
/// </summary>
public override void OnDisconnected(DisconnectCause cause)
{
LogFeedback("<Color=Red>OnDisconnected</Color> "+cause);
Debug.LogError("PUN Basics Tutorial/Launcher:Disconnected");
// #Critical: we failed to connect or got disconnected. There is not much we can do. Typically, a UI system should be in place to let the user attemp to connect again.
loaderAnime.StopLoaderAnimation();
isConnecting = false;
controlPanel.SetActive(true);
}
/// <summary>
/// Called when entering a room (by creating or joining it). Called on all clients (including the Master Client).
/// </summary>
/// <remarks>
/// This method is commonly used to instantiate player characters.
/// If a match has to be started "actively", you can call an [PunRPC](@ref PhotonView.RPC) triggered by a user's button-press or a timer.
///
/// When this is called, you can usually already access the existing players in the room via PhotonNetwork.PlayerList.
/// Also, all custom properties should be already available as Room.customProperties. Check Room..PlayerCount to find out if
/// enough players are in the room to start playing.
/// </remarks>
public override void OnJoinedRoom()
{
LogFeedback("<Color=Green>OnJoinedRoom</Color> with "+PhotonNetwork.CurrentRoom.PlayerCount+" Player(s)");
Debug.Log("PUN Basics Tutorial/Launcher: OnJoinedRoom() called by PUN. Now this client is in a room.\nFrom here on, your game would be running.");
// #Critical: We only load if we are the first player, else we rely on PhotonNetwork.AutomaticallySyncScene to sync our instance scene.
if (PhotonNetwork.CurrentRoom.PlayerCount == 1)
{
Debug.Log("We load the 'Room for 1' ");
// #Critical
// Load the Room Level.
PhotonNetwork.LoadLevel("PunBasics-Room for 1");
}
}
#endregion
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4796bc1963eb34e1fa021b0a45b29df4
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,101 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Launcher.cs" company="Exit Games GmbH">
// Part of: Photon Unity Networking Demos
// </copyright>
// <summary>
// Used in PUN Basics Tutorial to connect, and join/create room automatically
// </summary>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------
using UnityEngine;
namespace Photon.Pun.Demo.PunBasics
{
/// <summary>
/// Simple behaviour to animate particles around to create a typical "Ajax Loader". this is actually very important to visual inform the user that something is happening
/// or better say that the application is not frozen, so a animation of some sort helps reassuring the user that the system is idle and well.
///
/// TODO: hide when connection failed.
///
/// </summary>
public class LoaderAnime : MonoBehaviour {
#region Public Variables
[Tooltip("Angular Speed in degrees per seconds")]
public float speed = 180f;
[Tooltip("Radius os the loader")]
public float radius = 1f;
public GameObject particles;
#endregion
#region Private Variables
Vector3 _offset;
Transform _transform;
Transform _particleTransform;
bool _isAnimating;
#endregion
#region MonoBehaviour CallBacks
/// <summary>
/// MonoBehaviour method called on GameObject by Unity during early initialization phase.
/// </summary>
void Awake()
{
// cache for efficiency
_particleTransform =particles.GetComponent<Transform>();
_transform = GetComponent<Transform>();
}
/// <summary>
/// MonoBehaviour method called on GameObject by Unity on every frame.
/// </summary>
void Update () {
// only care about rotating particles if we are animating
if (_isAnimating)
{
// we rotate over time. Time.deltaTime is mandatory to have a frame rate independant animation,
_transform.Rotate(0f,0f,speed*Time.deltaTime);
// we move from the center to the desired radius to prevent the visual artifacts of particles jumping from their current spot, it's not very nice visually
// so the particle is centered in the scene so that when it starts rotating, it doesn't jump and slowy we animate it to its final radius giving a smooth transition.
_particleTransform.localPosition = Vector3.MoveTowards(_particleTransform.localPosition, _offset, 0.5f*Time.deltaTime);
}
}
#endregion
#region Public Methods
/// <summary>
/// Starts the loader animation. Becomes visible
/// </summary>
public void StartLoaderAnimation()
{
_isAnimating = true;
_offset = new Vector3(radius,0f,0f);
particles.SetActive(true);
}
/// <summary>
/// Stops the loader animation. Becomes invisible
/// </summary>
public void StopLoaderAnimation()
{
particles.SetActive(false);
}
#endregion
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: df9597db7c55c44e885b8f74697d5ba0
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,81 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlayerAnimatorManager.cs" company="Exit Games GmbH">
// Part of: Photon Unity Networking Demos
// </copyright>
// <summary>
// Used in PUN Basics Tutorial to deal with the networked player Animator Component controls.
// </summary>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------
using UnityEngine;
namespace Photon.Pun.Demo.PunBasics
{
public class PlayerAnimatorManager : MonoBehaviourPun
{
#region Private Fields
[SerializeField]
private float directionDampTime = 0.25f;
Animator animator;
#endregion
#region MonoBehaviour CallBacks
/// <summary>
/// MonoBehaviour method called on GameObject by Unity during initialization phase.
/// </summary>
void Start ()
{
animator = GetComponent<Animator>();
}
/// <summary>
/// MonoBehaviour method called on GameObject by Unity on every frame.
/// </summary>
void Update ()
{
// Prevent control is connected to Photon and represent the localPlayer
if( photonView.IsMine == false && PhotonNetwork.IsConnected == true )
{
return;
}
// failSafe is missing Animator component on GameObject
if (!animator)
{
return;
}
// deal with Jumping
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);
// only allow jumping if we are running.
if (stateInfo.IsName("Base Layer.Run"))
{
// When using trigger parameter
if (Input.GetButtonDown("Fire2")) animator.SetTrigger("Jump");
}
// deal with movement
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
// prevent negative Speed.
if( v < 0 )
{
v = 0;
}
// set the Animator Parameters
animator.SetFloat( "Speed", h*h+v*v );
animator.SetFloat( "Direction", h, directionDampTime, Time.deltaTime );
}
#endregion
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 507e5741cec8a42dc964c8e0a4b55bd6
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,289 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlayerManager.cs" company="Exit Games GmbH">
// Part of: Photon Unity Networking Demos
// </copyright>
// <summary>
// Used in PUN Basics Tutorial to deal with the networked player instance
// </summary>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------
using UnityEngine;
using UnityEngine.EventSystems;
namespace Photon.Pun.Demo.PunBasics
{
#pragma warning disable 649
/// <summary>
/// Player manager.
/// Handles fire Input and Beams.
/// </summary>
public class PlayerManager : MonoBehaviourPunCallbacks, IPunObservable
{
#region Public Fields
[Tooltip("The current Health of our player")]
public float Health = 1f;
[Tooltip("The local player instance. Use this to know if the local player is represented in the Scene")]
public static GameObject LocalPlayerInstance;
#endregion
#region Private Fields
[Tooltip("The Player's UI GameObject Prefab")]
[SerializeField]
private GameObject playerUiPrefab;
[Tooltip("The Beams GameObject to control")]
[SerializeField]
private GameObject beams;
//True, when the user is firing
bool IsFiring;
#endregion
#region MonoBehaviour CallBacks
/// <summary>
/// MonoBehaviour method called on GameObject by Unity during early initialization phase.
/// </summary>
public void Awake()
{
if (this.beams == null)
{
Debug.LogError("<Color=Red><b>Missing</b></Color> Beams Reference.", this);
}
else
{
this.beams.SetActive(false);
}
// #Important
// used in GameManager.cs: we keep track of the localPlayer instance to prevent instanciation when levels are synchronized
if (photonView.IsMine)
{
LocalPlayerInstance = gameObject;
}
// #Critical
// we flag as don't destroy on load so that instance survives level synchronization, thus giving a seamless experience when levels load.
DontDestroyOnLoad(gameObject);
}
/// <summary>
/// MonoBehaviour method called on GameObject by Unity during initialization phase.
/// </summary>
public void Start()
{
CameraWork _cameraWork = gameObject.GetComponent<CameraWork>();
if (_cameraWork != null)
{
if (photonView.IsMine)
{
_cameraWork.OnStartFollowing();
}
}
else
{
Debug.LogError("<Color=Red><b>Missing</b></Color> CameraWork Component on player Prefab.", this);
}
// Create the UI
if (this.playerUiPrefab != null)
{
GameObject _uiGo = Instantiate(this.playerUiPrefab);
_uiGo.SendMessage("SetTarget", this, SendMessageOptions.RequireReceiver);
}
else
{
Debug.LogWarning("<Color=Red><b>Missing</b></Color> PlayerUiPrefab reference on player Prefab.", this);
}
#if UNITY_5_4_OR_NEWER
// Unity 5.4 has a new scene management. register a method to call CalledOnLevelWasLoaded.
UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded;
#endif
}
public override void OnDisable()
{
// Always call the base to remove callbacks
base.OnDisable ();
#if UNITY_5_4_OR_NEWER
UnityEngine.SceneManagement.SceneManager.sceneLoaded -= OnSceneLoaded;
#endif
}
/// <summary>
/// MonoBehaviour method called on GameObject by Unity on every frame.
/// Process Inputs if local player.
/// Show and hide the beams
/// Watch for end of game, when local player health is 0.
/// </summary>
public void Update()
{
// we only process Inputs and check health if we are the local player
if (photonView.IsMine)
{
this.ProcessInputs();
if (this.Health <= 0f)
{
GameManager.Instance.LeaveRoom();
}
}
if (this.beams != null && this.IsFiring != this.beams.activeInHierarchy)
{
this.beams.SetActive(this.IsFiring);
}
}
/// <summary>
/// MonoBehaviour method called when the Collider 'other' enters the trigger.
/// Affect Health of the Player if the collider is a beam
/// Note: when jumping and firing at the same, you'll find that the player's own beam intersects with itself
/// One could move the collider further away to prevent this or check if the beam belongs to the player.
/// </summary>
public void OnTriggerEnter(Collider other)
{
if (!photonView.IsMine)
{
return;
}
// We are only interested in Beamers
// we should be using tags but for the sake of distribution, let's simply check by name.
if (!other.name.Contains("Beam"))
{
return;
}
this.Health -= 0.1f;
}
/// <summary>
/// MonoBehaviour method called once per frame for every Collider 'other' that is touching the trigger.
/// We're going to affect health while the beams are interesting the player
/// </summary>
/// <param name="other">Other.</param>
public void OnTriggerStay(Collider other)
{
// we dont' do anything if we are not the local player.
if (!photonView.IsMine)
{
return;
}
// We are only interested in Beamers
// we should be using tags but for the sake of distribution, let's simply check by name.
if (!other.name.Contains("Beam"))
{
return;
}
// we slowly affect health when beam is constantly hitting us, so player has to move to prevent death.
this.Health -= 0.1f*Time.deltaTime;
}
#if !UNITY_5_4_OR_NEWER
/// <summary>See CalledOnLevelWasLoaded. Outdated in Unity 5.4.</summary>
void OnLevelWasLoaded(int level)
{
this.CalledOnLevelWasLoaded(level);
}
#endif
/// <summary>
/// MonoBehaviour method called after a new level of index 'level' was loaded.
/// We recreate the Player UI because it was destroy when we switched level.
/// Also reposition the player if outside the current arena.
/// </summary>
/// <param name="level">Level index loaded</param>
void CalledOnLevelWasLoaded(int level)
{
// check if we are outside the Arena and if it's the case, spawn around the center of the arena in a safe zone
if (!Physics.Raycast(transform.position, -Vector3.up, 5f))
{
transform.position = new Vector3(0f, 5f, 0f);
}
GameObject _uiGo = Instantiate(this.playerUiPrefab);
_uiGo.SendMessage("SetTarget", this, SendMessageOptions.RequireReceiver);
}
#endregion
#region Private Methods
#if UNITY_5_4_OR_NEWER
void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode loadingMode)
{
this.CalledOnLevelWasLoaded(scene.buildIndex);
}
#endif
/// <summary>
/// Processes the inputs. This MUST ONLY BE USED when the player has authority over this Networked GameObject (photonView.isMine == true)
/// </summary>
void ProcessInputs()
{
if (Input.GetButtonDown("Fire1"))
{
// we don't want to fire when we interact with UI buttons for example. IsPointerOverGameObject really means IsPointerOver*UI*GameObject
// notice we don't use on on GetbuttonUp() few lines down, because one can mouse down, move over a UI element and release, which would lead to not lower the isFiring Flag.
if (EventSystem.current.IsPointerOverGameObject())
{
// return;
}
if (!this.IsFiring)
{
this.IsFiring = true;
}
}
if (Input.GetButtonUp("Fire1"))
{
if (this.IsFiring)
{
this.IsFiring = false;
}
}
}
#endregion
#region IPunObservable implementation
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
// We own this player: send the others our data
stream.SendNext(this.IsFiring);
stream.SendNext(this.Health);
}
else
{
// Network player, receive data
this.IsFiring = (bool)stream.ReceiveNext();
this.Health = (float)stream.ReceiveNext();
}
}
#endregion
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 98fac77b304554f238a61572f5720187
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,74 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlayerNameInputField.cs" company="Exit Games GmbH">
// Part of: Photon Unity Networking Demos
// </copyright>
// <summary>
// Let the player input his name to be saved as the network player Name, viewed by alls players above each when in the same room.
// </summary>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------
using UnityEngine;
using UnityEngine.UI;
namespace Photon.Pun.Demo.PunBasics
{
/// <summary>
/// Player name input field. Let the user input his name, will appear above the player in the game.
/// </summary>
[RequireComponent(typeof(InputField))]
public class PlayerNameInputField : MonoBehaviour
{
#region Private Constants
// Store the PlayerPref Key to avoid typos
const string playerNamePrefKey = "PlayerName";
#endregion
#region MonoBehaviour CallBacks
/// <summary>
/// MonoBehaviour method called on GameObject by Unity during initialization phase.
/// </summary>
void Start () {
string defaultName = string.Empty;
InputField _inputField = this.GetComponent<InputField>();
if (_inputField!=null)
{
if (PlayerPrefs.HasKey(playerNamePrefKey))
{
defaultName = PlayerPrefs.GetString(playerNamePrefKey);
_inputField.text = defaultName;
}
}
PhotonNetwork.NickName = defaultName;
}
#endregion
#region Public Methods
/// <summary>
/// Sets the name of the player, and save it in the PlayerPrefs for future sessions.
/// </summary>
/// <param name="value">The name of the Player</param>
public void SetPlayerName(string value)
{
// #Important
if (string.IsNullOrEmpty(value))
{
Debug.LogError("Player Name is null or empty");
return;
}
PhotonNetwork.NickName = value;
PlayerPrefs.SetString(playerNamePrefKey, value);
}
#endregion
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c22ee30e9b2b34fe38b62e48c7d79dfa
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,147 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlayerUI.cs" company="Exit Games GmbH">
// Part of: Photon Unity Networking Demos
// </copyright>
// <summary>
// Used in PUN Basics Tutorial to deal with the networked player instance UI display tha follows a given player to show its health and name
// </summary>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------
using UnityEngine;
using UnityEngine.UI;
namespace Photon.Pun.Demo.PunBasics
{
#pragma warning disable 649
/// <summary>
/// Player UI. Constraint the UI to follow a PlayerManager GameObject in the world,
/// Affect a slider and text to display Player's name and health
/// </summary>
public class PlayerUI : MonoBehaviour
{
#region Private Fields
[Tooltip("Pixel offset from the player target")]
[SerializeField]
private Vector3 screenOffset = new Vector3(0f, 30f, 0f);
[Tooltip("UI Text to display Player's Name")]
[SerializeField]
private Text playerNameText;
[Tooltip("UI Slider to display Player's Health")]
[SerializeField]
private Slider playerHealthSlider;
PlayerManager target;
float characterControllerHeight;
Transform targetTransform;
Renderer targetRenderer;
CanvasGroup _canvasGroup;
Vector3 targetPosition;
#endregion
#region MonoBehaviour Messages
/// <summary>
/// MonoBehaviour method called on GameObject by Unity during early initialization phase
/// </summary>
void Awake()
{
_canvasGroup = this.GetComponent<CanvasGroup>();
this.transform.SetParent(GameObject.Find("Canvas").GetComponent<Transform>(), false);
}
/// <summary>
/// MonoBehaviour method called on GameObject by Unity on every frame.
/// update the health slider to reflect the Player's health
/// </summary>
void Update()
{
// Destroy itself if the target is null, It's a fail safe when Photon is destroying Instances of a Player over the network
if (target == null) {
Destroy(this.gameObject);
return;
}
// Reflect the Player Health
if (playerHealthSlider != null) {
playerHealthSlider.value = target.Health;
}
}
/// <summary>
/// MonoBehaviour method called after all Update functions have been called. This is useful to order script execution.
/// In our case since we are following a moving GameObject, we need to proceed after the player was moved during a particular frame.
/// </summary>
void LateUpdate () {
// Do not show the UI if we are not visible to the camera, thus avoid potential bugs with seeing the UI, but not the player itself.
if (targetRenderer!=null)
{
this._canvasGroup.alpha = targetRenderer.isVisible ? 1f : 0f;
}
// #Critical
// Follow the Target GameObject on screen.
if (targetTransform!=null)
{
targetPosition = targetTransform.position;
targetPosition.y += characterControllerHeight;
this.transform.position = Camera.main.WorldToScreenPoint (targetPosition) + screenOffset;
}
}
#endregion
#region Public Methods
/// <summary>
/// Assigns a Player Target to Follow and represent.
/// </summary>
/// <param name="target">Target.</param>
public void SetTarget(PlayerManager _target){
if (_target == null) {
Debug.LogError("<Color=Red><b>Missing</b></Color> PlayMakerManager target for PlayerUI.SetTarget.", this);
return;
}
// Cache references for efficiency because we are going to reuse them.
this.target = _target;
targetTransform = this.target.GetComponent<Transform>();
targetRenderer = this.target.GetComponentInChildren<Renderer>();
CharacterController _characterController = this.target.GetComponent<CharacterController> ();
// Get data from the Player that won't change during the lifetime of this Component
if (_characterController != null){
characterControllerHeight = _characterController.height;
}
if (playerNameText != null) {
playerNameText.text = this.target.photonView.Owner.NickName;
}
}
#endregion
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dba1a179e553446f0a08606778f559f1
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: