Unity Multiplayer Multijugador Tutorial - Photon 2 (Part 2) (BEGINNER-FRIENDLY - Para Principiantes)

Unity Multiplayer Multijugador Tutorial – Photon 2 (Part 2) (BEGINNER-FRIENDLY – Para Principiantes)

0
(0)

Bienvenido a esta nueva serie de tutoriales sobre la creación de videojuegos multijugador en Unity usando el complemento Photon 2 PUN. Para esta lección, le mostraremos cómo descargar, instalar y configurar el complemento Photon 2 en sus proyectos de Unity. Antes de seguir con cualquiera de las otras lecciones de esta serie de tutoriales, debe completar este video. Proporcionaremos los complementos descargables para todos los demás videos de esta serie, pero estos complementos no incluirán el complemento Photon original. Debe obtenerlo del sitio web oficial de Photon.

 

Lo primero que deberá hacer en esta lección es crear una cuenta de Photon. Una vez que haya registrado una cuenta, deberá crear un nuevo proyecto de aplicación Photon. Luego deberás completar información sobre tu juego multijugador y luego harás clic en crear. Después de crear una nueva aplicación, deberá copiar el ID de aplicación para más adelante.

De vuelta en Unity, deberá ir a Unity Asset Store y buscar el complemento gratuito PUN 2. Deberá descargar e instalar este complemento en su proyecto. Después de importar este complemento, aparecerá una nueva ventana. Este es el asistente de PUN y debe pegar su AppID de proyecto en esta ventana y luego hará clic en configurar proyecto. Lo siguiente que haremos es establecer nuestra primera conexión con el servidor maestro Photon. Para hacer esto, necesitaremos crear un nuevo script. En este nuevo script, lo único que haremos para este tutorial es inicializar la conexión de red.

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.

 

Únete a nuestro Discord

 

Twitter

 

Facebook

 

Instagram

 

Linkedin

 

Pinterest

¿Qué tan útil fue esta publicación?

¡Haz clic en una estrella para calificarla!

Puntuación media 0 / 5. Recuento de votos: 0

No hay votos hasta ahora! Sé el primero en calificar esta publicación.

¡Lamentamos que esta publicación no te haya sido útil!

¡Permítanos mejorar esta publicación!

¿Cuéntanos cómo podemos mejorar esta publicación?

Foto de perfil de Facebook

Written by 

Founder of ZoeGeop Technologies. Apasionado por la tecnología, emprendedor, investigador y player innato. Creyente de la posibilidad que todos tenemos para lograr lo que nos propongamos con una pizca de enfoque y disciplina.