// Object spawning methods
        public int SetupLocalPlayer()
        {
            MPLogger.Log("Setting up local player");
            MPLogger.Log($"{HeroController.instance.col2d.GetType().ToString()}");

            GameObject local = new GameObject("NetworkPlayerSender");

            DontDestroyOnLoad(local);

            PhotonView    view   = local.AddComponent <PhotonView>();
            NetworkPlayer player = local.AddComponent <NetworkPlayer>();

            view.ownershipTransfer = OwnershipOption.Takeover;
            view.synchronization   = ViewSynchronization.UnreliableOnChange;
            view.viewID            = PhotonNetwork.AllocateViewID();
            view.TransferOwnership(PhotonNetwork.player);
            view.ObservedComponents = new List <Component>
            {
                player
            };

            RaiseEventOptions options = new RaiseEventOptions()
            {
                CachingOption = EventCaching.AddToRoomCache
            };

            PhotonNetwork.RaiseEvent(NetworkCallbacks.OnSetupLocalPlayer, view.viewID, true, options);

            localPlayer = player;

            needsToSetupPlayer = false;

            return(view.viewID);
        }
        public static IEnumerator CreateRoomAsync()
        {
            MPLogger.Log("Sending save data to other player...");
            if (NetworkManager.main.needsToSetupPlayer)
            {
                NetworkManager.main.SetupLocalPlayer();
            }

            Platform.current.ReadSaveSlot(GameManager.instance.profileID, delegate(byte[] dat)
            {
                NetworkManager.main.saveData = dat;
            });
            if (NetworkManager.main.saveData == null)
            {
                yield return(null);
            }

            MPLogger.Log($"Length of data: {NetworkManager.main.saveData.Length}");

            object[] data = new object[]
            {
                NetworkManager.main.saveData
            };
            RaiseEventOptions options = new RaiseEventOptions()
            {
                CachingOption = EventCaching.AddToRoomCache
            };

            PhotonNetwork.RaiseEvent(NetworkCallbacks.OnConnectedToRoom, data, true, options);
            yield break;
        }
        public void SetupOtherPlayer(PhotonPlayer player, int viewID)
        {
            MPLogger.Log($"Setting up other player: {player.NickName}");
            GameObject playerObj = new GameObject("OTHER");
            var        netSync   = playerObj.AddComponent <NetworkPlayer>();

            var view = playerObj.AddComponent <PhotonView>();

            var body = playerObj.AddComponent <Rigidbody2D>();

            body.gravityScale = 0f;
            body.constraints  = RigidbodyConstraints2D.FreezeAll;
            var box = playerObj.AddComponent <BoxCollider2D>();

            box.size        = ((BoxCollider2D)HeroController.instance.col2d).size;
            box.offset      = ((BoxCollider2D)HeroController.instance.col2d).offset;
            playerObj.layer = (int)PhysLayers.BOUNCER;
            playerObj.AddComponent <BigBouncer>();

            view.ownershipTransfer = OwnershipOption.Takeover;
            view.synchronization   = ViewSynchronization.UnreliableOnChange;
            view.viewID            = viewID;
            view.TransferOwnership(player);
            view.ObservedComponents = new List <Component>
            {
                netSync
            };

            var rend = playerObj.AddComponent <MeshRenderer>();

            playerObj.AddComponent <MeshFilter>();

            var spriteAnim = playerObj.AddComponent <tk2dSpriteAnimation>();

            spriteAnim.clips = HeroController.instance.animCtrl.animator.Library.clips;
            playerObj.AddComponent <tk2dSprite>();
            var anim       = tk2dSpriteAnimator.AddComponent(playerObj, spriteAnim, 0);
            var collection = playerObj.AddComponent <tk2dSpriteCollectionData>();

            netSync.anim     = anim;
            netSync.renderer = rend;

            collection.spriteDefinitions = HeroController.instance.animCtrl.animator.Sprite.collection.spriteDefinitions;

            anim.SetSprite(collection, 0);

            playerObj.transform.position = HeroController.instance.transform.position + (Vector3.one * 1000f);

            var txt    = CreateTextMesh(player.NickName);
            var follow = txt.gameObject.AddComponent <FollowTransform>();

            follow.target = playerObj.transform;
            follow.offset = Vector3.up;

            DontDestroyOnLoad(playerObj);
            DontDestroyOnLoad(txt.gameObject);

            playerList.Add(player, netSync);
        }
        public void CreateNailSwing(int playerID, NetAttackDir dir, bool mantis, bool longnail, bool right)
        {
            PhotonPlayer player = PhotonPlayer.Find(playerID);

            if (!playerList.ContainsKey(player))
            {
                MPLogger.Log("Got nailswing for player who hasnt been initialized!");
                return;
            }

            NailSlash original = null;
            NailSlash slash    = null;

            switch (dir)
            {
            case NetAttackDir.normal:
                original = HeroController.instance.normalSlash;
                slash    = Instantiate(original);
                break;

            case NetAttackDir.up:
                original = HeroController.instance.upSlash;
                slash    = Instantiate(original);
                break;

            case NetAttackDir.down:
                original = HeroController.instance.downSlash;
                slash    = Instantiate(original);
                break;

            case NetAttackDir.normalalt:
                original = HeroController.instance.alternateSlash;
                slash    = Instantiate(original);
                break;

            case NetAttackDir.wall:
                original = HeroController.instance.wallSlash;
                slash    = Instantiate(original);
                break;
            }

            slash.SetMantis(mantis);
            slash.SetLongnail(longnail);

            slash.StartSlash();
            slash.gameObject.layer = (int)PhysLayers.ENEMIES;

            Vector3 scale = slash.transform.localScale;

            scale.x *= right ? -1 : 1;
            slash.transform.localScale = scale;

            var follow = slash.gameObject.AddComponent <FollowTransform>();

            follow.target = NetworkManager.main.playerList[player].transform;
            follow.offset = original.transform.localPosition;

            Destroy(slash.gameObject, 2f);
        }
 public void JoinGame(string name)
 {
     if (GameManager.instance.IsMenuScene())
     {
         MPLogger.Log("Joining room...");
         PhotonNetwork.JoinRoom(name);
     }
     else
     {
         MPLogger.Log("Tried to join a room when we weren't in the menu");
     }
 }
        public void InitializePhoton()
        {
            MPLogger.Log("Initializing Photon Settings");
            ServerSettings settings = ScriptableObject.CreateInstance <ServerSettings>();

            settings.HostType  = ServerSettings.HostingOption.BestRegion;
            settings.AppID     = "91f3e558-5a8a-457c-81dd-807771c71246";
            settings.Protocol  = ExitGames.Client.Photon.ConnectionProtocol.Udp;
            settings.JoinLobby = true;

            PhotonNetwork.PhotonServerSettings = settings;
        }
        public static Texture2D LoadTextureFromBytes(byte[] data, TextureFormat format = TextureFormat.BC7)
        {
            Texture2D texture2D = new Texture2D(2, 2, format, false);

            if (texture2D.LoadImage(data))
            {
                return(texture2D);
            }
            else
            {
                MPLogger.Log("Error on LoadTextureFromFile call. Texture cannot be loaded");
            }

            return(null);
        }
        public static void OnPhotonEvent(byte code, object content, int sender)
        {
            if (code == OnConnectedToRoom)
            {
                MPLogger.Log("Recieved host game data");
                if (!PhotonNetwork.isMasterClient)
                {
                    object[] data = (object[])content;

                    byte[] saveData = (byte[])data[0];

                    Platform.Current.WriteSaveSlot(-1, saveData, delegate(bool success) { GameManager.instance.LoadGameFromUI(-1); });
                }
            }
            else if (code == OnSetupLocalPlayer)
            {
                MPLogger.Log("Recieved ID from other player");
                NetworkManager.main.setupQueue.Add(PhotonPlayer.Find(sender), (int)content);
            }
            else if (code == OnPlayerSwingNail)
            {
                object[] data = (object[])content;

                if (!NetworkManager.main.playerList.ContainsKey(PhotonPlayer.Find(sender)))
                {
                    return;
                }

                NetAttackDir dir      = (NetAttackDir)data[0];
                bool         mantis   = (bool)data[1];
                bool         longnail = (bool)data[2];
                bool         right    = (bool)data[3];

                NetworkManager.main.CreateNailSwing(sender, dir, mantis, longnail, right);
            }
            else if (code == OnEnterNewRoom)
            {
                string data = (string)content;
                MPLogger.Log($"Recieved data: {data}");

                NetworkPlayer.SerializedEnemies enemies = JsonUtility.FromJson <NetworkPlayer.SerializedEnemies>(data);

                NetworkPlayer host = NetworkManager.main.playerList[PhotonPlayer.Find(sender)];
                host.enemyIDs   = enemies.enemyIDs;
                host.enemyNames = enemies.enemyNames;
            }
        }
Beispiel #9
0
        public static string TrimFromName(GameObject obj)
        {
            MPLogger.Log($"Checking name of : {obj.name}");

            string name = obj.name;

            name.TrimGameObjectName();
            name.Trim();

            while (name.EndsWith("(Clone)"))
            {
                name.TrimGameObjectName();
                name.Trim();
            }

            return(name);
        }
Beispiel #10
0
        public static void AddEnemy(GameObject enemy)
        {
            string name = TrimFromName(enemy);

            if (enemies.ContainsKey(name))
            {
                return;
            }

            GameObject clone = GameObject.Instantiate(enemy, null);

            clone.SetActive(false);
            GameObject.DontDestroyOnLoad(clone);

            clone.name = name;
            enemies.Add(name, clone);
            MPLogger.Log($"ADDED {name} TO DATABASE");
        }
        /// <summary>
        /// Creates a new <see cref="Texture2D" /> from an image file.
        /// </summary>
        /// <param name="filePathToImage">The path to the image file.</param>
        /// <param name="format">
        /// <para>The texture format. By default, this uses <see cref="TextureFormat.BC7" />.</para>
        /// <para>https://docs.unity3d.com/ScriptReference/TextureFormat.BC7.html</para>
        /// <para>Don't change this unless you really know what you're doing.</para>
        /// </param>
        /// <returns>Will return a new <see cref="Texture2D"/> instance if the file exists; Otherwise returns null.</returns>
        /// <remarks>
        /// Ripped from: https://github.com/RandyKnapp/SubnauticaModSystem/blob/master/SubnauticaModSystem/Common/Utility/ImageUtils.cs
        /// </remarks>
        public static Texture2D LoadTextureFromFile(string filePathToImage, TextureFormat format = TextureFormat.BC7)
        {
            if (File.Exists(filePathToImage))
            {
                byte[]    imageBytes = File.ReadAllBytes(filePathToImage);
                Texture2D texture2D  = new Texture2D(2, 2, format, false);
                if (texture2D.LoadImage(imageBytes))
                {
                    return(texture2D);
                }
                else
                {
                    MPLogger.Log("Error on LoadTextureFromFile call. Texture cannot be loaded: " + filePathToImage);
                }
            }
            else
            {
                MPLogger.Log("Error on LoadTextureFromFile call. File not found at " + filePathToImage);
            }

            return(null);
        }
        public void CreateGame()
        {
            if (GameManager.instance.IsGameplayScene())
            {
                MPLogger.Log("Creating room...");

                RoomOptions options = new RoomOptions()
                {
                    CustomRoomProperties = new ExitGames.Client.Photon.Hashtable()
                    {
                        { "IsPublic", true },
                        { "Name", PhotonNetwork.playerName },
                    },
                    CustomRoomPropertiesForLobby = new string[] { "IsPublic", "Name" }
                };

                PhotonNetwork.CreateRoom(new Guid().ToString(), options, PhotonNetwork.lobby);
            }
            else
            {
                MPLogger.Log("Tried to create room, but we weren't in the game!");
            }
        }
 public void OnConnectedToMaster()
 {
     MPLogger.Log("Connected to master server");
 }
 public void OnFailedToConnectToPhoton(DisconnectCause cause)
 {
     MPLogger.Log($"Failed to connect: {cause.ToString()}");
 }
 public void OnJoinedLobby()
 {
     MPLogger.Log("Connected to lobby successfully");
     PhotonNetwork.FindFriends(NetworkManager.main.friends.ToArray());
 }
 // Connection methods
 public void ConnectToLobby()
 {
     MPLogger.Log("Connecting to Photon");
     PhotonNetwork.ConnectUsingSettings("0.0.2");
 }
 public void OnJoinedRoom()
 {
     MPLogger.Log("Joined room successfully!");
     NetworkManager.main.needsToSetupPlayer = true;
 }
 public void OnConnectionFail(DisconnectCause cause)
 {
     MPLogger.Log($"Connection Failed: {cause.ToString()}");
 }
 public void OnPhotonPlayerConnected(PhotonPlayer newPlayer)
 {
     MPLogger.Log("Other player joined");
 }
Beispiel #20
0
        public static void Init()
        {
            SceneManager.sceneLoaded += (scene, mode) =>
            {
                foreach (HealthManager hm in GameObject.FindObjectsOfType <HealthManager>())
                {
                    if (hm.gameObject.IsGameEnemy())
                    {
                        EnemyDatabase.AddEnemy(hm.gameObject);
                    }
                }

                foreach (EnemySpawner enemy in GameObject.FindObjectsOfType <EnemySpawner>())
                {
                    if (enemy.enemyPrefab.IsGameEnemy())
                    {
                        EnemyDatabase.AddEnemy(enemy.enemyPrefab);
                    }
                }
            };

            On.GameManager.FinishedEnteringScene += (orig, self) =>
            {
                orig(self);
                return;


                if (!GameManager.instance.IsGameplayScene() || !PhotonNetwork.inRoom)
                {
                    return;
                }

                bool          isHost    = true;
                NetworkPlayer sceneHost = null;

                foreach (NetworkPlayer player in NetworkManager.main.playerList.Values)
                {
                    if (player.levelName == GameManager.instance.GetSceneNameString())
                    {
                        isHost    = false;
                        sceneHost = player;
                    }
                }

                NetworkManager.main.localPlayer.isSceneHost = isHost;
                MPLogger.Log(isHost ? "We are the host!" : "Someone else is the host!");

                HealthManager[] enemies    = GameObject.FindObjectsOfType <HealthManager>();
                List <string>   enemyNames = new List <string>();
                List <int>      enemyIDs   = new List <int>();
                foreach (HealthManager enemy in enemies)
                {
                    if (enemy.gameObject.IsGameEnemy())
                    {
                        if (isHost)
                        {
                            string name = EnemyDatabase.TrimFromName(enemy.gameObject);
                            MPLogger.Log($"Setting up enemy for network: {name}");

                            enemyNames.Add(name);

                            NetworkEnemy netEnemy = enemy.gameObject.AddComponent <NetworkEnemy>();
                            enemy.gameObject.AddComponent <PhotonView>();

                            MPLogger.Log(enemy.animator == null ? "ANIMATOR IS NULL" : "ANIMATOR IS FINE");

                            netEnemy.anim = enemy.animator;

                            var view = netEnemy.photonView;

                            view.ownershipTransfer = OwnershipOption.Takeover;
                            view.synchronization   = ViewSynchronization.UnreliableOnChange;
                            view.viewID            = PhotonNetwork.AllocateViewID();
                            view.TransferOwnership(PhotonNetwork.player);
                            view.ObservedComponents = new List <Component>
                            {
                                netEnemy
                            };

                            enemyIDs.Add(view.viewID);
                        }
                        else
                        {
                            GameObject.Destroy(enemy.gameObject);
                        }
                    }
                }

                if (!isHost)
                {
                    MPLogger.Log("Spawning other player's enemies");

                    enemyIDs   = sceneHost.enemyIDs;
                    enemyNames = sceneHost.enemyNames;

                    if (enemyNames != null && enemyNames.Count > 0)
                    {
                        for (int i = 0; i < enemyIDs.Count; i++)
                        {
                            string     name  = enemyNames[i];
                            GameObject enemy = EnemyDatabase.SpawnEnemy(name, Vector3.zero);

                            PhotonView   view     = enemy.AddComponent <PhotonView>();
                            NetworkEnemy netEnemy = enemy.AddComponent <NetworkEnemy>();
                            netEnemy.anim          = enemy.GetComponent <HealthManager>().animator;
                            view.ownershipTransfer = OwnershipOption.Takeover;
                            view.synchronization   = ViewSynchronization.UnreliableOnChange;
                            view.viewID            = enemyIDs[i];
                            view.TransferOwnership(sceneHost.photonView.owner);
                            view.ObservedComponents = new List <Component>
                            {
                                netEnemy
                            };
                        }
                    }
                }
                else
                {
                    var serializeData = new NetworkPlayer.SerializedEnemies()
                    {
                        enemyIDs   = enemyIDs,
                        enemyNames = enemyNames
                    };

                    string dataToSend = JsonUtility.ToJson(serializeData);
                    MPLogger.Log($"Sending data: {dataToSend}");

                    PhotonNetwork.RaiseEvent(NetworkCallbacks.OnEnterNewRoom, dataToSend, true, new RaiseEventOptions()
                    {
                        CachingOption = EventCaching.AddToRoomCache,
                        Receivers     = ReceiverGroup.Others
                    });
                }
            };

            On.GameManager.BeginSceneTransition += (orig, self, info) =>
            {
                orig(self, info);

                // Leaving a scene, transition owner
            };

            On.GameManager.ReturnToMainMenu += (orig, self, saveMode, callback) =>
            {
                var result = orig(self, saveMode, callback);

                if (PhotonNetwork.inRoom)
                {
                    PhotonNetwork.LeaveRoom();
                }

                return(result);
            };

            On.GameManager.EmergencyReturnToMenu += (orig, self, callback) =>
            {
                orig(self, callback);
                if (PhotonNetwork.inRoom)
                {
                    PhotonNetwork.LeaveRoom();
                }
            };

            On.HeroController.Attack += (orig, self, attackDir) =>
            {
                orig(self, attackDir);

                if (PhotonNetwork.inRoom)
                {
                    NetAttackDir direction = NetAttackDir.normal;

                    if (self.cState.wallSliding)
                    {
                        direction = NetAttackDir.wall;
                    }
                    else if (self.cState.downAttacking)
                    {
                        direction = NetAttackDir.down;
                    }
                    else if (self.cState.upAttacking)
                    {
                        direction = NetAttackDir.up;
                    }
                    else if (!self.cState.altAttack)
                    {
                        direction = NetAttackDir.normalalt;
                    }

                    object[] data = new object[4];
                    data[0] = direction;
                    data[1] = HeroController.instance.playerData.equippedCharm_13;
                    data[2] = HeroController.instance.playerData.equippedCharm_18;
                    data[3] = HeroController.instance.cState.facingRight;

                    PhotonNetwork.RaiseEvent(NetworkCallbacks.OnPlayerSwingNail, data, true, new RaiseEventOptions());
                }
            };

            On.MenuStyleTitle.SetTitle += (orig, self, index) =>
            {
                self.Title.sprite = Sprite.Create(HKMP.logo, new Rect(0, 0, HKMP.logo.width, HKMP.logo.height), new Vector2(0.5f, 0.5f));
                self.Title.transform.localScale = Vector3.one * 2f;
            };
        }
 public void OnConnectedToPhoton()
 {
     MPLogger.Log("Connected to Photon main");
 }