Ejemplo n.º 1
0
    // Use this for initialization
    void Start()
    {
        game_manager = GameObject.FindGameObjectWithTag("GameManager").GetComponent <GameManager>();
        RT_manager   = game_manager.GetGameSparksRTManager();
        net_manager  = game_manager.GetNetworkManager();
        nav_map      = GameObject.FindGameObjectWithTag("Map").GetComponent <NavigationMap>();

        StartCoroutine(SendTimeStamp());

        // Inform the server that the match is ready
        using (RTData data = RTData.Get())
        {
            data.SetLong(1, 0);
            RT_manager.SendData(103, GameSparks.RT.GameSparksRT.DeliveryIntent.UNRELIABLE_SEQUENCED, data, new int[] { 0 }); // send to peerId -> 0, which is the server
        }

        StartCoroutine(DelayTurnStart());

        turn_info.turn = turn_type.stop;
        curr_action    = action.wait;

        attack_button.gameObject.SetActive(false);
        finish_player_turn.gameObject.SetActive(false);
        state_text.gameObject.SetActive(false);

        card1.gameObject.SetActive(false);
        card2.gameObject.SetActive(false);
        card3.gameObject.SetActive(false);
    }
Ejemplo n.º 2
0
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(this.gameObject);
        }
        else
        {
            Destroy(gameObject);
        }

        sparkNetwork = gameObject.AddComponent <GameSparksRTUnity> ();

        SceneManager.sceneLoaded   += OnSceneLoaded;
        SceneManager.sceneUnloaded += OnSceneUnloaded;

        MatchFoundMessage.Listener    = OnMatchFound;
        MatchNotFoundMessage.Listener = OnMatchNotFound;
        MatchUpdatedMessage.Listener  = OnMatchUpdated;

        GS.GameSparksAvailable += (isAvailable) => {
            this.isAvailable = isAvailable;
        };

        Update_SparkViews();
    }
        //Starts the game session
        public void StartNewRTSession(RTSessionInfo _info)
        {
            //if the settings arent null
            if (gameSparksRTUnity == null)
            {
                Debug.Log("GSM| Creating New RT Session Instance...");
                sessionInfo       = _info;                                              //player/session information
                gameSparksRTUnity = this.gameObject.AddComponent <GameSparksRTUnity>(); //add the RT script to the manager
                GSRequestData mockedResponse = new GSRequestData();                     //create a new request
                mockedResponse.AddNumber("port", (double)_info.GetPortID());            //gets the port id
                mockedResponse.AddString("host", _info.GetHostURL());                   //gets host server
                mockedResponse.AddString("accessToken", _info.GetAccessToken());        // construct a dataset from the game-details
                FindMatchResponse response = new FindMatchResponse(mockedResponse);     //create a mock response for match

                //configures the game
                gameSparksRTUnity.Configure(response,
                                            (peerId) => { OnPlayerConnectedToGame(peerId); },
                                            (peerId) => { OnPlayerDisconnected(peerId); },
                                            (ready) => { OnRTReady(ready); },
                                            (packet) => { OnPacketReceived(packet); });
                gameSparksRTUnity.Connect(); // when the config is set, connect the game
            }
            else
            {
                Debug.LogError("Session Already Started");
            }
        }
        /// <summary>
        /// Initializes and starts a new real time session for users
        /// </summary>
        /// <param name="_info">The session information for this game</param>
        public void StartNewRTSession(RTSessionInfo _info)
        {
            Debug.Log("GSM| Creating new RT Session instance...");
            m_SessionInfo       = _info;
            m_GameSparksRTUnity = this.gameObject.AddComponent <GameSparksRTUnity>(); //Adds the RT script to the game
            //In order to create a new RT game we need a 'FindMatchResponse'
            //This would usually come from the server directly after a successful MatchmakingRequest
            //However, in our case, we want the game to be create only when all the players ready up
            //Therefore, the details from the response is passed in from the gameInfo and a mock-up of a FindMatchReponse is passed in
            GSRequestData mockedReponse = new GSRequestData()
                                          .AddNumber("port", (double)_info.GetPortID())
                                          .AddString("host", _info.GetHostURL())
                                          .AddString("accessToken", _info.GetAccessToken()); //Construct a dataset from the game-details

            FindMatchResponse response = new FindMatchResponse(mockedReponse);               //Create a match-response from that data and pass it into the game-configuration

            //So in the game-configuration method we pass in the response which gives the Instance its connection settings
            //In this example, a lambda expression is used to pass in actions for
            //OnPlayerConnect, OnPlayerDisconnect, OnReady, and OnPacket
            //The methods do exactly what they are named. For example, OnPacket gets called when a packet is received

            m_GameSparksRTUnity.Configure(response,
                                          (peerId) => { OnPlayerConnectedToGame(peerId); },
                                          (peerId) => { OnPlayerDisconnected(peerId); },
                                          (ready) => { OnRTReady(ready); },
                                          (packet) => { OnPacketReceived(packet); });
            m_GameSparksRTUnity.Connect(); //When the configuration is set, connect the game
        }
Ejemplo n.º 5
0
        public void StartNewRTSession(RTSessionInfo _info)
        {
            Debug.Log("GSM| Creating New RT Session Instance...");
            sessionInfo       = _info;
            gameSparksRTUnity = this.gameObject.AddComponent <GameSparksRTUnity>(); // Adds the RT script to the game
                                                                                    // In order to create a new RT game we need a 'FindMatchResponse' //
                                                                                    // This would usually come from the server directly after a successful MatchmakingRequest //
                                                                                    // However, in our case, we want the game to be created only when the first player decides using a button //
                                                                                    // therefore, the details from the response is passed in from the gameInfo and a mock-up of a FindMatchResponse //
                                                                                    // is passed in. //
            GSRequestData mockedResponse = new GSRequestData()
                                           .AddNumber("port", (double)_info.GetPortID())
                                           .AddString("host", _info.GetHostURL())
                                           .AddString("accessToken", _info.GetAccessToken()); // construct a dataset from the game-details

            FindMatchResponse response = new FindMatchResponse(mockedResponse);               // create a match-response from that data and pass it into the game-config

            // So in the game-config method we pass in the response which gives the instance its connection settings //
            // In this example, I use a lambda expression to pass in actions for
            // OnPlayerConnect, OnPlayerDisconnect, OnReady and OnPacket actions //
            // These methods are self-explanatory, but the important one is the OnPacket Method //
            // this gets called when a packet is received //

            gameSparksRTUnity.Configure(response,
                                        (peerId) => { OnPlayerConnectedToGame(peerId); },
                                        (peerId) => { OnPlayerDisconnected(peerId); },
                                        (ready) => { OnRTReady(ready); },
                                        (packet) => { OnPacketReceived(packet); });
            gameSparksRTUnity.Connect(); // when the config is set, connect the game
        }
Ejemplo n.º 6
0
    /*------------------------------------------------------------------------------------------------------------------------------------------------------
     * -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     * -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     * -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     * * -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     *
     *                                                                              REALTIME
     *
     * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

    public void StartNewRtSession(RtSessionInfo info,
                                  GameSparksRTController.OnPlayerConnectedToGame onPlayerConnectedToGame,
                                  GameSparksRTController.OnPlayerDisconnected onPlayerDisconnected,
                                  GameSparksRTController.OnRTReady onRtReady,
                                  GameSparksRTController.OnPacketReceived onPacketReceived,
                                  ref RtSessionInfo sessionInfo, ref GameSparksRTUnity gameSparksRtUnity)
    {
    }
Ejemplo n.º 7
0
    IEnumerator SendClockTimeStamp()
    {
        GameSparksRTUnity rtSession = MyGameSparksManager.Instance().GetRTUnitySession();

        PacketsFactory.SendTimeStamp(rtSession);

        yield return(new WaitForSeconds(m_sendTimeStampRatioInSeconds));

        StartCoroutine(SendClockTimeStamp());
    }
Ejemplo n.º 8
0
    public void Disconnect(string returnScene)
    {
        GameSparksRTUnity session = m_gameSparksManager.RTSession;

        if (session != null)
        {
            session.Disconnect();
        }
        m_switchScene.Switch(returnScene);
    }
 private static void InstallServices(
     AsyncProcessor a,
     DiContainer c,
     GameSparksRTUnity gs,
     SparkRtService.Settings s)
 {
     c.Bind <AsyncProcessor>().FromInstance(a);
     c.Bind <RtQosService>().AsSingle();
     c.Bind <PrefabBuilder>().AsSingle();
     c.Bind <SparkRtService>().AsSingle();
     c.Bind <CsvWriterService>().AsSingle();
     c.Bind <SparkRtService.Settings>().FromInstance(s).AsSingle();
     c.Bind <GameSparksRTUnity>().FromInstance(gs).AsSingle();
 }
Ejemplo n.º 10
0
 public void createSession()
 {
     if (RTClass == null)
     {
         RTClass = gameObject.AddComponent <GameSparksRTUnity>();
     }
     RTClass.Configure(host, port, accessToken, OnPacket: pack => packetReceived(pack),
                       OnPlayerConnect: pack => playerConnected(pack),
                       OnPlayerDisconnect: pack => playerDisconnected(pack),
                       OnReady: pack => playersReady(pack));
     RTClass.Connect();
     connectedToSession = true;
     fighterScript.StartCoroutine(fighterScript.positionSendToPacket());
 }
Ejemplo n.º 11
0
    private void StartNewSession(RTSessionInfo sessionInfo, MatchFoundMessage resp)
    {
        Debug.Log("GSM| Creating New RT Session Instance...");

        RtGS = gameObject.AddComponent <GameSparksRTUnity>();

        RtGS.Configure(resp,
                       (peerId) => { OnPlayerConnectedToGame(peerId); },
                       (peerId) => { OnPlayerDisconnected(peerId); },
                       (ready) => { OnRTReady(ready); },
                       (packet) => { OnPacketReceived(packet); }
                       );
        RtGS.Connect();
    }
Ejemplo n.º 12
0
    public static void SendTimeStamp(GameSparksRTUnity rtSession)
    {
        if (rtSession == null)
        {
            return;
        }

        using (RTData data = RTData.Get())
        {
            long unixTime = GetUnixTime();
            data.SetLong(1, (long)unixTime);

            rtSession.SendData((int)OpCodes.TimeStamp, GameSparksRT.DeliveryIntent.UNRELIABLE, data, SERVER_PEER_ID);
        }
    }
Ejemplo n.º 13
0
    public static void SendPlayerMovement(Survivor survivor, GameSparksRTUnity rtSession)
    {
        using (RTData data = RTData.Get())
        {
            data.SetVector3(1, survivor.transform.position);
            data.SetVector3(2, survivor.transform.rotation.eulerAngles);
            data.SetVector3(3, survivor.GetComponent <Rigidbody>().velocity);

            data.SetVector4(4, survivor.UserControl.Move);

            float jumpFloat   = survivor.UserControl.Jump ? 1 : 0;
            float crouchFloat = survivor.UserControl.Crouch ? 1 : 0;
            data.SetVector2(5, new Vector2(jumpFloat, crouchFloat));

            rtSession.SendData((int)OpCodes.PlayerTransform, GameSparksRT.DeliveryIntent.UNRELIABLE_SEQUENCED, data);
        }
    }
Ejemplo n.º 14
0
    private IEnumerator SendMovement(bool debug)
    {
        bool hasSpeed           = m_rigidbody.velocity.magnitude > VELOCITY_THRESHOLD;
        bool movingStateChanged = hasSpeed != m_wasMoving;
        bool crouchStateChanged = UserControl.Crouch != m_wasCrouch;
        bool jumpStateChanged   = UserControl.Jump != m_wasJumping;

        if (hasSpeed ||
            movingStateChanged ||
            crouchStateChanged ||
            jumpStateChanged)
        {
            if (!debug)
            {
                GameSparksRTUnity rtSession = MyGameSparksManager.Instance().GetRTUnitySession();
                PacketsFactory.SendPlayerMovement(this, rtSession);
            }
            else
            {
                m_debugOnlinePlayer.SendMovement(this);
            }
        }

        if (hasSpeed)
        {
            Debug.Log("SENDING: " + m_rigidbody.velocity + " TIME: " + Time.time);
        }

        if (!hasSpeed && m_wasMoving)
        {
            Debug.LogError("STOP MOVING " + Time.time);
        }

        //Debug.Log("isMoving: "+isMoving+" movingStateChanged: "+movingStateChanged+" crouchStateChanged: "+crouchStateChanged+" jumpStateChanged: "+jumpStateChanged);

        m_wasMoving      = hasSpeed;
        m_wasJumping     = UserControl.Jump;
        m_wasCrouch      = UserControl.Crouch;
        previousPosition = transform.position;

        yield return(new WaitForSeconds(GameController.UPDATE_RATE));

        StartCoroutine(SendMovement(debug));
    }
Ejemplo n.º 15
0
    public void StartNewRTSession(RTSessionInfo _info)
    {
        Debug.Log("GSM| Creating New RT Session Instance...");
        sessionInfo       = _info;
        gameSparksRTUnity = this.gameObject.AddComponent <GameSparksRTUnity>();

        GSRequestData mockedResponse = new GSRequestData()
                                       .AddNumber("port", (double)_info.GetPortID())
                                       .AddString("host", _info.GetHostURL())
                                       .AddString("accessToken", _info.GetAccessToken());

        FindMatchResponse response = new FindMatchResponse(mockedResponse);

        gameSparksRTUnity.Configure(response,
                                    (peerId) => { OnPlayerConnectedToGame(peerId); },
                                    (peerId) => { OnPlayerDisconnected(peerId); },
                                    (ready) => { OnRTReady(ready); },
                                    (packet) => { OnPacketReceived(packet); });
        gameSparksRTUnity.Connect();
    }
Ejemplo n.º 16
0
    public void StartNewRealTimeSession(RTSessionInfo sessionInfo)
    {
        m_rtSessionInfo   = sessionInfo;
        gameSparksRTUnity = gameObject.AddComponent <GameSparksRTUnity>();

        GSRequestData mockedResponse = new GSRequestData()
                                       .AddNumber("port", (double)sessionInfo.GetPortId())
                                       .AddString("host", sessionInfo.GetHostUrl())
                                       .AddString("accessToken", sessionInfo.GetAccessToken());

        FindMatchResponse response = new FindMatchResponse(mockedResponse);


        gameSparksRTUnity.Configure(response,
                                    OnPlayerConnect,
                                    OnPlayerDisconnect,
                                    OnReady,
                                    OnPacket);

        gameSparksRTUnity.Connect();
    }
Ejemplo n.º 17
0
    private void OnMatchFound(GameSparks.Api.Messages.MatchFoundMessage _message)
    {
        Debug.Log("Match Found!...");

        curr_text.text = "Match Found!...";

        curr_text.alignment = TextAnchor.MiddleCenter;

        searching_ball.gameObject.SetActive(false);

        GameManager       game_manager = GameObject.FindGameObjectWithTag("GameManager").GetComponent <GameManager>();
        GameSparksRTUnity RT_manager   = game_manager.GetGameSparksRTManager();
        NetworkManager    net_manager  = game_manager.GetNetworkManager();

        net_manager.match = new MatchInfo(_message);

        RT_manager.Configure(_message,
                             (peerID) => { net_manager.OnPlayerConnectedToGame(peerID); },
                             (peerID) => { net_manager.OnPlayerDisconnected(peerID); },
                             (ready) => { net_manager.OnRTReady(ready); },
                             (packet) => { net_manager.OnPacketReceived(packet); });
        RT_manager.Connect();



        //Uncoment that to Debug the Match info

        /*Debug.Log("Match Found...");
         * Debug.Log("Host URL:" + _message.Host);
         * Debug.Log("Port:" + _message.Port);
         * Debug.Log("Access Token:" + _message.AccessToken);
         * Debug.Log("MatchId:" + _message.MatchId);
         * Debug.Log("Opponents:" + _message.Participants.Count());
         * Debug.Log("_________________");
         *
         * foreach (GameSparks.Api.Messages.MatchFoundMessage._Participant player in _message.Participants)
         * {
         *  Debug.Log("Player:" + player.PeerId + " User Name:" + player.DisplayName); // add the player number and the display name to the list
         * }*/
    }
Ejemplo n.º 18
0
    void InstantiatePlayers(RTSessionInfo session)
    {
        Transform         thisTransform     = transform;
        List <RTPlayer>   players           = session.PlayerList;
        GameSparksRTUnity gameSparksSession = m_gameSparksManager.RTSession;
        EnemyGenerator    enemyGenerator    = GameObject.Find("EnemyGenerator").GetComponent <EnemyGenerator>();
        int count = players.Count;

        enemyGenerator.players = new Rigidbody2D[count];

        m_players      = new PlayerController[count];
        m_turrets      = new Turret[count];
        m_playerHealth = new PlayerHealth[count];

        if (PlayerPrefabs.Length < count)
        {
            Debug.LogError("Player prefabs less than connected players!");
            return;
        }
        if (m_spawnPoints.Length < count)
        {
            Debug.LogError("Spawn points less than connected players!");
            return;
        }
        players.Sort((p, p2) => (p.PeerId.CompareTo(p2.PeerId)));

        for (int i = 0; i < count; ++i)
        {
            // Spawn Player
            GameObject player = Instantiate(
                PlayerPrefabs[i],
                m_spawnPoints[i].position,
                m_spawnPoints[i].rotation
                );
            Transform        playerTransform  = player.transform;
            PlayerController playerController = player.GetComponent <PlayerController>();
            m_playerHealth[i]         = player.GetComponent <PlayerHealth>();
            m_turrets[i]              = player.GetComponent <Turret>();
            enemyGenerator.players[i] = player.GetComponent <Rigidbody2D>();
            player.name                 = "Player " + players[i].PeerId.ToString();
            playerController.PeerID     = players[i].PeerId;
            playerController.UpdateRate = _playerUpdateRate;
            playerTransform.SetParent(thisTransform);
            m_turrets[i].BulletContainer   = m_bulletContainer;
            m_turrets[i].ParticleContainer = m_particleContainer;


            bool isPlayer = players[i].PeerId == gameSparksSession.PeerId;
            if (isPlayer)
            {
                m_camera.ObjectToFollow = playerTransform;
            }

            playerController.GameSparks = m_gameSparksManager;
            playerController.SetupMultiplayer(m_spawnPoints[i], isPlayer);

            // Set player multiplayer component instead...
            m_players[i] = playerController;

            // Spawn HpBar
            GameObject hpBar = Instantiate(m_hpBarPrefab);
            hpBar.transform.SetParent(UiCanvas);
            hpBar.GetComponent <FollowTarget>().target = playerTransform;
            HpBarUi hpBarUi = hpBar.GetComponent <HpBarUi>();
            hpBarUi.Health = m_playerHealth[i];
            m_playerHealth[i]._onPlayerHpModified.AddListener(hpBarUi.UpdateHealth);
            m_playerHealth[i]._onPlayerDeath.AddListener(PlayerDead);
        }

        // Don't generate if not host
        m_enemyGenerator.GameSparksManager = m_gameSparksManager;
        IsHost = m_gameSparksManager.RTSession.PeerId == 1;
        m_enemyGenerator.SetupMultiplayer(IsHost);
        m_playerScore.MultiplayerManager = this;
    }
Ejemplo n.º 19
0
 void Awake()
 {
     instance = this;
     DontDestroyOnLoad(gameObject);
 }
Ejemplo n.º 20
0
 void Awake()
 {
     instance = this;
     DontDestroyOnLoad(gameObject);
 }
 public SparkRtService(Settings settings, GameSparksRTUnity gameSparksRtUnity)
 {
     _rtConnected       = false;
     _settings          = settings;
     _gameSparksRtUnity = gameSparksRtUnity;
 }