En ésta oportunidad comenzamos con la configuración inicial y la realización de la lógica de creación de salas unión a salas, y ubicación de objeto player en la escena en ésta serie abarcaremos la creación de nuestro videojuego TPS en la modalidad Multijugador con Photon 2 en Unity 3D. La implementación multijugador es independiente del juego la haremos así para que puedas utilizarla en cualquier otro proyecto que requieras.
La baja latencia es un requisito esencial en los juegos multijugador en tiempo real. Por esta razón, Photon Cloud está alojado en todas las principales regiones del mundo para brindar a sus jugadores una latencia mínima.
Los juegos que dependen de una latencia baja, como los tipos de juegos FPS o RTS, conectan a los jugadores con la región más cercana. Los juegos que pueden manejar una mayor latencia, como los juegos por turnos, pueden conectar a todos los jugadores a la misma región.
PlayerMovement
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private PhotonView PV;
private CharacterController myCC;
public float movementSpeed;
public float rotationSpeed;
// Start is called before the first frame update
void Start()
{
PV = GetComponent<PhotonView>();
myCC = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
if(PV.IsMine && PhotonNetwork.IsConnected)
{
BasicMovement();
BasicRotation();
}
}
void BasicMovement()
{
if(Input.GetKey(KeyCode.W))
{
myCC.Move(transform.forward * Time.deltaTime * movementSpeed);
}
if (Input.GetKey(KeyCode.A))
{
myCC.Move(transform.right * Time.deltaTime * movementSpeed);
}
if (Input.GetKey(KeyCode.S))
{
myCC.Move(transform.forward * Time.deltaTime * movementSpeed);
}
if (Input.GetKey(KeyCode.D))
{
myCC.Move(transform.right * Time.deltaTime * movementSpeed);
}
}
void BasicRotation()
{
float mouseX = Input.GetAxis("Mouse X") * Time.deltaTime * rotationSpeed;
transform.Rotate(new Vector3(0, mouseX, 0));
}
}
PhotonLobby
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
public class PhotonLobby : MonoBehaviourPunCallbacks
{
// Start is called before the first frame update
public static PhotonLobby lobby;
public GameObject battleButton;
RoomInfo[] room;
public GameObject cancelButtom;
private void Awake()
{
lobby = this;
}
void Start()
{
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
Debug.Log("the conection is stablished");
PhotonNetwork.AutomaticallySyncScene = true;
battleButton.SetActive(true);
}
public void OnBattleButtonClicked()
{
Debug.Log("llego aca paso algo en la el battle button click");
battleButton.SetActive(false);
cancelButtom.SetActive(true);
PhotonNetwork.JoinRandomRoom();
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
//base.OnJoinRandomFailed(returnCode, message);
Debug.Log("failed joining the room");
CreateRoom();
}
void CreateRoom()
{
Debug.Log("llego a CreateRoom");
int randomRoomName = Random.Range(0, 10000);
RoomOptions roomOps = new RoomOptions()
{
IsVisible = true,
IsOpen = true,
MaxPlayers = (byte)MultiplayerSettings.multiplayerSettings.maxPlayers
};
PhotonNetwork.CreateRoom("Room" + randomRoomName, roomOps, null);
}
public override void OnCreateRoomFailed(short returnCode, string message)
{
//base.OnCreateRoomFailed(returnCode, message);
Debug.Log("failed creating the room");
CreateRoom();
}
public void OnCancelButtonCliked()
{
Debug.Log("Llego OnCancelButtonCliked");
battleButton.SetActive(false);
cancelButtom.SetActive(true);
PhotonNetwork.LeaveRoom();
}
}
PhotonPlayer
using Photon.Pun;
using System.IO;
using UnityEngine;
public class PhotonPlayer : MonoBehaviour
{
// Start is called before the first frame update
private PhotonView PV;
public GameObject myAvatar;
public GameObject myMainCamera;
void Start()
{
PV = GetComponent<PhotonView>();
int spawnPicker = Random.Range(0, GameSetUp.GS.spawnPoints.Length);
if (PV.IsMine)
{
myAvatar = PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "PlayerAvatar"), GameSetUp.GS.spawnPoints[spawnPicker].position,
GameSetUp.GS.spawnPoints[spawnPicker].rotation, 0);
/*myAvatar = PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "Character 1"), GameSetUp.GS.spawnPoints[spawnPicker].position,
GameSetUp.GS.spawnPoints[spawnPicker].rotation, 0);*/
}
}
}
PhotonRoom
using Photon.Pun;
using Photon.Realtime;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PhotonRoom : MonoBehaviourPunCallbacks, IInRoomCallbacks
{
// Start is called before the first frame update
public static PhotonRoom room;
private PhotonView PV;
public bool IsGameLoaded;
public int currentScene;
private Photon.Realtime.Player[] photonPlayers;
public int playersInRoom;
public int myNumberInRoom;
public int playerInGame;
private bool readyToCount;
private bool readyToStart;
public float startingTime;
private float lessThanMaxPlayer;
private float atMaxPlayer;
private float timeToStart;
private void Awake()
{
if(PhotonRoom.room == null)
{
PhotonRoom.room = this;
}
else
{
if(PhotonRoom.room != this)
{
Destroy(PhotonRoom.room.gameObject);
PhotonRoom.room = this;
}
}
DontDestroyOnLoad(this.gameObject);
}
public override void OnEnable()
{
base.OnEnable();
PhotonNetwork.AddCallbackTarget(this);
SceneManager.sceneLoaded += OnSceneFinishedLoading;
}
public override void OnDisable()
{
base.OnDisable();
PhotonNetwork.RemoveCallbackTarget(this);
SceneManager.sceneLoaded -= OnSceneFinishedLoading;
}
void Start()
{
PV = GetComponent<PhotonView>();
readyToCount = false;
readyToStart = false;
lessThanMaxPlayer = startingTime;
atMaxPlayer = 6;
timeToStart = startingTime;
}
// Update is called once per frame
void Update()
{
if (MultiplayerSettings.multiplayerSettings.delayStart)
{
if(playersInRoom == 1)
{
RestartTimer();
}
if (!IsGameLoaded)
{
if (readyToStart)
{
atMaxPlayer -= Time.deltaTime;
lessThanMaxPlayer = atMaxPlayer;
timeToStart = atMaxPlayer;
}
else if (readyToCount)
{
lessThanMaxPlayer -= Time.deltaTime;
timeToStart = lessThanMaxPlayer;
}
Debug.Log("Displayer time to start to the players " + timeToStart );
if (timeToStart <=0)
{
StartGame();
}
}
}
}
public override void OnJoinedRoom()
{
base.OnJoinedRoom();
Debug.Log("Se Unio a OnJoinedRoom");
photonPlayers = PhotonNetwork.PlayerList;
playersInRoom = photonPlayers.Length;
myNumberInRoom = playersInRoom;
PhotonNetwork.NickName = myNumberInRoom.ToString();
if (MultiplayerSettings.multiplayerSettings.delayStart)
{
Debug.Log("Displayer players in room out of max players possible ("+playersInRoom+":"+MultiplayerSettings.multiplayerSettings.maxPlayers+")");
if(playersInRoom > 1)
{
readyToCount = true;
}
if (playersInRoom == MultiplayerSettings.multiplayerSettings.maxPlayers)
{
readyToStart = true;
if (PhotonNetwork.IsMasterClient)
{
return;
}
PhotonNetwork.CurrentRoom.IsOpen = false;
}
}
else
{
StartGame();
}
}
public override void OnPlayerEnteredRoom(Photon.Realtime.Player newPlayer)
{
base.OnPlayerEnteredRoom(newPlayer);
Debug.Log("A new player has joined the room");
photonPlayers = PhotonNetwork.PlayerList;
playersInRoom++;
if(MultiplayerSettings.multiplayerSettings.delayStart)
{
Debug.Log("Displayer players in room out of max players possible (" + playersInRoom + ":" + MultiplayerSettings.multiplayerSettings.maxPlayers + ")");
if (playersInRoom > 1)
{
readyToCount = true;
}
if (playersInRoom == MultiplayerSettings.multiplayerSettings.maxPlayers)
{
readyToStart = true;
if (!PhotonNetwork.IsMasterClient)
{
return;
}
PhotonNetwork.CurrentRoom.IsOpen = false;
}
}
}
void StartGame()
{
IsGameLoaded = true;
if (!PhotonNetwork.IsMasterClient)
return;
if(MultiplayerSettings.multiplayerSettings.delayStart)
{
PhotonNetwork.CurrentRoom.IsOpen = false;
}
PhotonNetwork.LoadLevel(MultiplayerSettings.multiplayerSettings.multiplayerScene);
}
void RestartTimer()
{
lessThanMaxPlayer = startingTime;
timeToStart = startingTime;
atMaxPlayer = 6;
readyToCount = false;
readyToStart = false;
}
void OnSceneFinishedLoading(Scene scene, LoadSceneMode mode)
{
currentScene = scene.buildIndex;
if (currentScene ==MultiplayerSettings.multiplayerSettings.multiplayerScene)
{
IsGameLoaded = true;
if (MultiplayerSettings.multiplayerSettings.delayStart)
{
PV.RPC("RPC_loadedGameScene", RpcTarget.MasterClient);
}
else
{
RPC_CreatePlayer();
}
}
}
[PunRPC]
private void RPC_LoadedGameScene()
{
playerInGame++;
if (playerInGame == PhotonNetwork.PlayerList.Length)
{
PV.RPC("RPC_CreatePlayer",RpcTarget.All);
}
}
[PunRPC]
private void RPC_CreatePlayer()
{
PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "PhotonNetworkPlayer"), transform.position, Quaternion
.identity, 0);
}
}
GameSetUp
using UnityEngine;
public class GameSetUp : MonoBehaviour
{
// Start is called before the first frame update
public static GameSetUp GS;
public Transform[] spawnPoints;
private void OnEnable()
{
if (GameSetUp.GS == null)
{
GameSetUp.GS = this;
}
}
}
MultiplayerSettings
using UnityEngine;
public class MultiplayerSettings : MonoBehaviour
{
// Start is called before the first frame update
public static MultiplayerSettings multiplayerSettings;
public bool delayStart;
public int maxPlayers;
public int menuScene;
public int multiplayerScene;
private void Awake()
{
if(MultiplayerSettings.multiplayerSettings == null)
{
MultiplayerSettings.multiplayerSettings = this;
}
else
{
if(MultiplayerSettings.multiplayerSettings != this)
{
Destroy(this.gameObject);
}
}
DontDestroyOnLoad(this.gameObject);
}
}
¿Quieres publicar tus propios proyectos?. ¡Pues que esperas!

ZoeGeop Technologies
MarketPlace
Crea tu cuenta
Suscríbete
[latest-selected-content output=»slider» limit=»4″ date_limit=»1″ date_start=»2″ date_start_type=»months» image=»medium» css=»four-columns tall as-overlay light» type=»post» status=»publish» taxonomy=»category» orderby=»dateD» show_extra=»category» slidermode=»fade» slideslides=»1″ slidescroll=»1″ sliderinfinite=»true» slidercontrols=»true» sliderauto=»true» sliderspeed=»3000″ chrlimit=»120″ url=»yes»]
Suscríbete a nuestro canal de YouTube
Síguenos en nuestro canal de YouTube dedicado a tecnología, marketplace de proyectos tecnológicos, cursos online y tutoriales de desarrollo de videojuegos. Ofrecemos consultoría en desarrollo de software, marketing online, servicios de TI, hosting web, dominios web y más.
Siguenos en Patreon
Si quieres contribuir con cualquier aporte o donación hacia nuestros proyectos y el canal puedes hacerlo a través de nuestra cuenta en Patreon.



