Beispiel #1
0
 public void SendRTData(OpCodes opcode, GameSparksRT.DeliveryIntent intent)
 {
     using (RTData data = RTData.Get())
     {
         SendRTData(opcode, intent, data);
     }
 }
        /// <summary>
        /// Send and set  up to 4 float value(s). The float value(s) will then be processed by a user defined function.
        /// A switch and case statement system can be used to create a function that can handle more than just 4 floats
        /// if that is needed
        /// GameSparks does not provide the capability to send a float array, but they do allow a Vector4. Therefore,
        /// this function actually converts the user's float array into a vector4, meaning if the array contains more
        /// than four floats, those floats will be lost. There is a way to serialize data and send an array that way
        /// https://docs.gamesparks.com/tutorials/database-access-and-cloud-storage/c-sharp-object-serialization-for-gamesparks.html
        /// But until it is determined that implementing such a method is necessary, it will not be implemented in ASL
        /// </summary>
        /// <param name="f">The float value to be passed to all users</param>
        /// <example>
        /// <code>
        /// void SomeFunction()
        /// {
        ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetClaim(() =>
        ///     {
        ///         float[] myValue = new float[1];
        ///         myValue[0] = 3.5;
        ///         gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendFloat4(myValue); //In this example, playerHealth would be updated to 3.5 for all users
        ///     });
        /// }
        /// </code><code>
        /// The same gameobject would then also have these qualities:
        ///
        /// void Start()
        /// {
        ///     //Or if this object was created dynamically, then to have this function assigned on creation instead of in start like this one is
        ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;()._LocallySetFloatCallback(UserDefinedFunction)
        /// }
        /// public void UserDefinedFunction(float[] f)
        /// {
        ///     //Update some value for all users based on f.
        ///     //Example:
        ///     playerHealth = f[0]; //Where playerHealth is shown to kept track/shown to all users
        /// }
        ///</code>
        /// It is possible to use this function to send more than 4 variables if the user sets up the function to execute upon receiving SendFloat4 to include a switch/case statement
        /// with the final value in the float array being what determines how the other three values are handled. See below for an example
        /// <code>
        /// //For example, use this function to update player stats using the same SendFloat4 UserDefinedFunction that can also update velocity and score
        /// void SomeFunction()
        /// {
        ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetClaim(() =>
        ///     {
        ///         float[] myValue = new float[1];
        ///         myValue[0] = 3.5;
        ///         myValue[1] = 0;
        ///         myValue[2] = 1.2
        ///         myValue[3] = 2
        ///         //In this example, playerHealth would be updated to 3.5 for all users, playerArmor to 0, playerSpeedBuff to 1.2, and the switch case to properly assign these values, 2
        ///         gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendFloat4(myValue);
        ///     });
        /// }
        /// //For example, use this function to update velocity using the same SendFloat4 UserDefinedFunction that can also update player stats and score
        /// void SomeOtherFunction()
        /// {
        ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetClaim(() =>
        ///     {
        ///         float[] myValue = new float[1];
        ///         myValue[0] = 17.8;
        ///         myValue[1] = 180.2;
        ///         myValue[3] = 1
        ///         //In this example, velocity would be set to 17.8 and direction to 180.2
        ///         gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendFloat4(myValue);
        ///     });
        /// }
        ///
        /// void Start()
        /// {
        ///     //Or if this object was created dynamically, then to have this function assigned on creation instead of in start like this one is
        ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;()._LocallySetFloatCallback(UserDefinedFunction)
        /// }
        /// public void UserDefinedFunction(float[] f)
        /// {
        ///     //Update some value for all users based on f.
        ///     //Example:
        ///     switch (f[3])
        ///     {
        ///         case 0:
        ///             //Update score based on f[0] for example
        ///         break;
        ///         case 1:
        ///             //Update player velocity and direction with f[0] and f[1] for example
        ///             playerVelocity = f[0]; //Velocity gets set to 17.8
        ///             playerDirection = f[1]; //Player Direction gets set to 180.2
        ///         break;
        ///         case 2:
        ///             playerHealth = f[0]; //Health gets assigned to 3.5
        ///             playerArmor = f[1]; //Armor gets assigned to 0
        ///             playerSpeedBuff = f[2]; SpeedBuff gets assigned to 1.2
        ///         break;
        ///     }
        /// }
        /// </code>
        ///</example>
        public void SendFloat4(float[] f)
        {
            if (m_Mine) //Can only send a transform if we own the object
            {
                if (f.Length > 4)
                {
                    Debug.LogWarning("SendFloat4 float array cannot have a length greater than 4 due to GameSpark restrictions. See documentation for details.");
                }
                using (RTData data = RTData.Get())
                {
                    Vector4 floats = Vector4.zero;
                    //Manually convert float[] to Vector4
                    if (f.Length >= 1)
                    {
                        floats.x = f[0];
                    }
                    if (f.Length >= 2)
                    {
                        floats.y = f[1];
                    }
                    if (f.Length >= 3)
                    {
                        floats.z = f[2];
                    }
                    if (f.Length >= 4)
                    {
                        floats.w = f[3];
                    }

                    data.SetString((int)GameController.DataCode.Id, m_Id);
                    data.SetVector4((int)GameController.DataCode.MyFloats, floats);
                    GameSparksManager.Instance().GetRTSession().SendData((int)GameSparksManager.OpCode.SetFloat, GameSparksRT.DeliveryIntent.RELIABLE, data);
                }
            }
        }
Beispiel #3
0
 public void SendRTData(OpCodes opcode, GameSparksRT.DeliveryIntent intent, int[] targetPeers)
 {
     using (RTData data = RTData.Get())
     {
         SendRTData(opcode, intent, data, targetPeers);
     }
 }
Beispiel #4
0
    public void SendPlayerPos(string id, int pos_x, int pos_y, int shadow_x, int shadow_y, bool attack, bool reveled, int num_cards)
    {
        GameObject player        = null;
        Player     player_script = null;

        player = GetPlayerById(id);

        if (player != null)
        {
            player_script = player.GetComponent <Player>();

            player_script.SetTargetPos(new Vector2(pos_x, pos_y));

            using (RTData data = RTData.Get())
            {
                data.SetString(1, id);
                data.SetInt(2, pos_x);
                data.SetInt(3, pos_y);
                data.SetInt(4, shadow_x);
                data.SetInt(5, shadow_y);
                data.SetString(6, attack.ToString().ToLower());
                data.SetString(7, reveled.ToString().ToLower());
                data.SetInt(9, num_cards);

                RT_manager.SendData(122, GameSparks.RT.GameSparksRT.DeliveryIntent.UNRELIABLE_SEQUENCED, data, new int[] { 0 }); // send to peerId -> 0, which is the server

                Debug.Log("Sending position to x:" + pos_x + ", y:" + pos_y);
            }
        }
    }
Beispiel #5
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);
    }
 /// <summary>
 /// Claims an object for the user until someone steals it or the passed in claim time is reached. Changing the time you hold onto an object and
 /// deciding to reset or not the current amount of time you have held it is generally not recommended, but does have occasional applications
 /// </summary>
 /// <param name="callback">The callback to be called when the claim is approved by the server</param>
 /// <param name="claimTimeOut">The amount of time in milliseconds the user will own this object. If set to less than 0,
 /// then the user will own the object until it gets stolen.</param>
 /// /// <param name="resetClaimTimeout">Flag indicating whether or not a claim should reset the claim timer for this object</param>
 /// <example><code>
 /// void SomeFunction()
 /// {
 ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetClaim(() =>
 ///     {
 ///         //Whatever code we want to execute after we have successfully claimed this object, such as:
 ///         gameobject.GetComponent&lt;ASL.ASLObject&gt;().DeleteObject(); //Delete our object
 ///         //or
 ///         gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetLocalPosition(new Vector3(5, 0, -2)); //Move our object in its local space to 5, 0, -2
 ///     });
 /// }
 /// </code>
 /// <code>
 /// void SomeFunction()
 /// {
 ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetClaim(ActionToTake);
 /// }
 /// private void ActionToTake()
 /// {
 ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().DeleteObject(); //Delete our object
 /// }
 /// void SomeOtherFunction()
 /// {
 ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetClaim(ADifferentActionToTake, 2000); //Hold onto this object before releasing it to the server for 2 seconds
 /// }
 /// private void ADifferentActionToTake()
 /// {
 ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetLocalPosition(new Vector3(5, 0, -2)); //Move our object in its local space to 5, 0, -2
 /// }
 /// </code>
 /// <code>
 /// void SomeFunction()
 /// {
 ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetClaim(() =>
 ///     {
 ///         //Whatever code we want to execute after we have successfully claimed this object, such as:
 ///         gameobject.GetComponent&lt;ASL.ASLObject&gt;().DeleteObject(); //Delete our object
 ///         //or
 ///         gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetLocalPosition(new Vector3(5, 0, -2)); //Move our object in its local space to 5, 0, -2
 ///     }, 0); //Hold onto this object until someone steals it
 /// }
 /// </code>
 /// <code>
 /// void SomeFunction()
 /// {
 ///     //Claim an object for 1 second, but don't reset whatever our current time length of time we have already held on to it for.
 ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetClaim(SomeActionToTake, 1000, false);
 /// }
 /// private void SomeActionToTake()
 /// {
 ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().DeleteObject(); //Delete our object
 /// }
 /// </code>
 /// <code>
 /// void SomeFunction()
 /// {
 ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetClaim(() =>
 ///     {
 ///         //Whatever code we want to execute after we have successfully claimed this object, such as:
 ///         gameobject.GetComponent&lt;ASL.ASLObject&gt;().DeleteObject(); //Delete our object
 ///         //or
 ///         gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetLocalPosition(new Vector3(5, 0, -2)); //Move our object in its local space to 5, 0, -2
 ///     }, 0, false); //Hold on to this object until someone steals it, but don't reset whatever our current length of time we have already held on to it for
 /// }
 /// </code></example>
 public void SendAndSetClaim(ClaimCallback callback, int claimTimeOut = 1000, bool resetClaimTimeout = true)
 {
     if (!m_Mine) //If we already own the object, don't send anything and instead call our callback right away
     {
         //Debug.Log("Outstanding Claims: " + m_OutStandingClaims);
         if (!m_OutStandingClaims)
         {
             m_OutStandingClaims = true;
             using (RTData data = RTData.Get())
             {
                 data.SetString((int)GameController.DataCode.Id, m_Id);
                 GameSparksManager.Instance().GetRTSession().SendData((int)GameSparksManager.OpCode.Claim, GameSparksRT.DeliveryIntent.RELIABLE, data);
             }
         }
         m_ClaimCallback += callback;
         m_OutstandingClaimCallbackCount++;
     }
     else
     {
         callback();
     }
     if (resetClaimTimeout)
     {
         m_ClaimReleaseTimer = 0;            //Reset release timer
         m_ClaimTime         = claimTimeOut; //Reset claim length
     }
 }
Beispiel #7
0
        /// <summary>
        /// Releases an object so another user can claim it. This function will also call this object's release function if it exists.
        /// This function is triggered by a packet received from the relay server.
        /// </summary>
        /// <param name="_packet">The packet containing the id of the object that another player wants to claim</param>
        public void ReleaseClaimedObject(RTPacket _packet)
        {
            if (ASLHelper.m_ASLObjects.TryGetValue(_packet.Data.GetString((int)DataCode.Id) ?? string.Empty, out ASLObject myObject))
            {
                if (GameSparksManager.m_PlayerIds.TryGetValue(_packet.Data.GetString((int)DataCode.OldPlayer), out bool currentOwner))
                {
                    if (currentOwner) //If this client is the current owner
                    {
                        //Send a packet to new owner informing them that the previous owner (this client) no longer owns the object
                        //So they can do whatever they want with it now.
                        using (RTData data = RTData.Get())
                        {
                            data.SetString((int)DataCode.Id, myObject.m_Id);
                            data.SetString((int)DataCode.Player, _packet.Data.GetString((int)DataCode.Player));
                            GameSparksManager.Instance().GetRTSession().SendData((int)GameSparksManager.OpCode.ClaimFromPlayer,
                                                                                 GameSparksRT.DeliveryIntent.RELIABLE, data, (int)_packet.Data.GetInt((int)DataCode.PlayerPeerId));
                        }
                        myObject.m_ReleaseFunction?.Invoke(myObject.gameObject); //If user wants to do something before object is released - let them do so
                        myObject._LocallyRemoveReleaseCallback();

                        myObject._LocallySetClaim(false);
                        myObject._LocallyRemoveClaimCallbacks();
                    }
                }
            }
        }
    /// <summary>
    /// Finishes caching data and then sends it over through the network. Used internally.
    /// </summary>
    /// <param name="info">Info.</param>
    private void Finish(SparkMessageInfo info)
    {
        if (IsEmpty)
        {
            return;
        }

        bool equal = networkVariables.OrderBy(pair => pair.Key).SequenceEqual(previousVariables.OrderBy(pair => pair.Key));

        if (equal)
        {
            return;
        }

        IsWriting = false;

        using (RTData data = RTData.Get())
        {
            data.SetString(1, SparkExtensions.Serialize(this));
            data.SetString(2, SparkExtensions.Serialize(info));

            SparkManager.instance.sparkNetwork.SendData(1, observeMethod, data);
        }

        sendCount         = 0;
        previousVariables = networkVariables;
        networkVariables.Clear();

        IsWriting = true;
    }
Beispiel #9
0
    /// <summary>
    /// Sends the player position, rotation and velocity
    /// </summary>
    /// <returns>The player movement.</returns>
    private IEnumerator SendPlayerMovement()
    {
        // we don't want to send position updates until we are actually moving //
        // so we check that the axis-input values are greater or less than zero before sending //
        if ((this.transform.position != m_prevPos) || (Mathf.Abs(Input.GetAxis("Vertical")) > 0) || (Mathf.Abs(Input.GetAxis("Horizontal")) > 0))
        {
            using (RTData data = RTData.Get())
            {
                // we put a using statement here so that we can dispose of the RTData objects once the packet is sent

                // Send Position Data
                data.SetVector3(1, new Vector3(m_transform.position.x, m_transform.position.y, m_transform.position.z)); // add the position at key 1

                // Send Rotation Data
                data.SetFloat(2, m_transform.eulerAngles.y); // add the rotation at key 2

                //data.SetVector2(3, new Vector2(this.strafeMagnitude, this.direction));

                GameSparksManager.Instance().GetRTSession().SendData(2, GameSparks.RT.GameSparksRT.DeliveryIntent.UNRELIABLE_SEQUENCED, data); // send the data
            }
            m_prevPos = this.transform.position;                                                                                               // record position for any discrepancies
        }

        yield return(updateWait);

        StartCoroutine(SendPlayerMovement());
    }
Beispiel #10
0
    private void SendMessage()
    {
        if (messageInput.text != string.Empty)
        { // first check to see if there is any message to send
          // for all RT-data we are sending, we use an instance of the RTData object //
          // this is a disposable object, so we wrap it in this using statement to make sure it is returned to the pool //
            using (RTData data = RTData.Get())
            {
                data.SetString(1, messageInput.text);                            // we add the message data to the RTPacket at key '1', so we know how to key it when the packet is receieved
                data.SetString(2, DateTime.Now.ToString());                      // we are also going to send the time at which the user sent this message

                UpdateChatLog("Me", messageInput.text, DateTime.Now.ToString()); // we will update the chat-log for the current user to display the message they just sent

                messageInput.text = string.Empty;                                // and we clear the message window

                DebugTool.Instance().SetMessage(new DebugMessage("Sending Message to All Players... \n" + messageInput.text, DebugMessageType.Error));

                // for this example we are sending RTData, but there are other methods for sending data we will look at later //
                // the first parameter we use is the op-code. This is used to index the type of data being send, and so we can identify to ourselves which packet this is when it is received //
                // the second parameter is the delivery intent. The intent we are using here is 'reliable', which means it will be send via TCP. This is because we aren't concerned about //
                // speed when it comes to these chat messages, but we very much want to make sure the whole packet is received //
                // the final parameter is the RTData object itself //
                GameSparksRTController.Instance().GetRtSession().SendData(1, GameSparks.RT.GameSparksRT.DeliveryIntent.RELIABLE, data);
            }
        }
        else
        {
            DebugTool.Instance().SetMessage(new DebugMessage("Not Chat Message To Send...", DebugMessageType.Error));
        }
    }
Beispiel #11
0
        /// <summary>
        /// Find all ASL Objects in the scene and have the relay server create a unique ID for them as well as add this object to our ASLObject dictionary
        /// This function is triggered when this script is first loaded. This function will keep the timeScale at 0 until all objects have been ID.
        /// All objects are ID in the SetObjectID(RTPacket _packet) function.
        /// </summary>
        private void SyncronizeID(Scene _scene, LoadSceneMode _mode)
        {
            ASLObject[] m_StartingASLObjects = FindObjectsOfType(typeof(ASLObject)) as ASLObject[];

            //If there are ASL objects to initialize - pause until done
            if (m_StartingASLObjects.Length > 0)
            {
                Time.timeScale = 0; //"Pause" the game until all object's have their id's set
                m_PauseCanvas.SetActive(true);
            }
            //Sort by name + sqrt(transform components + localPosition * Dot(rotation, scale))
            m_StartingASLObjects = m_StartingASLObjects.OrderBy(aslObj => aslObj.name +
                                                                ((aslObj.transform.localPosition + new Vector3(aslObj.transform.localRotation.x, aslObj.transform.localRotation.y, aslObj.transform.localRotation.z) +
                                                                  aslObj.transform.localScale) + (aslObj.transform.localPosition + Vector3.Dot(new Vector3(aslObj.transform.localRotation.x, aslObj.transform.localRotation.y, aslObj.transform.localRotation.z),
                                                                                                                                               aslObj.transform.localScale) * Vector3.one)).sqrMagnitude)
                                   .ToArray();

            int startingObjectCount = 0;

            foreach (ASLObject _ASLObject in m_StartingASLObjects)
            {
                if (_ASLObject.m_Id == string.Empty || _ASLObject.m_Id == null) //If object does not have an ID
                {
                    m_ObjectIDAssignedCount++;
                    using (RTData data = RTData.Get())
                    {
                        //Have the RT server create an ID and send it back to everyone
                        GameSparksManager.Instance().GetRTSession().SendData((int)GameSparksManager.OpCode.ServerSetId, GameSparksRT.DeliveryIntent.RELIABLE, data);
                        //Add the starting objects to our dictionary without a key. Key will be added later to ensure all clients have the same key
                        ASLHelper.m_ASLObjects.Add(startingObjectCount.ToString(), _ASLObject);
                    }
                    startingObjectCount++;
                }
            }
        }
Beispiel #12
0
    /// <summary>
    /// Sends the RPC.
    /// </summary>
    /// <param name="code">Code.</param>
    /// <param name="methodName">Method name.</param>
    /// <param name="targetPlayer">Target player.</param>
    /// <param name="isBuffered">If set to <c>true</c> is buffered.</param>
    /// <param name="isLocal">If set to <c>true</c> is local.</param>
    /// <param name="parameters">Parameters.</param>
    private void SendEvent_RPC(Guid netGuid, SparkManager.OpCode code, string methodName, int[] receiverIds, bool isBuffered, bool isLocal, params object[] parameters)
    {
        SparkRPC rpc = new SparkRPC(netGuid, methodName, receiverIds, SparkManager.instance.LocalPlayer, parameters);

        using (RTData data = RTData.Get())
        {
            data.SetString(1, SparkExtensions.Serialize(rpc));

            SparkManager.instance.sparkNetwork.SendData(Convert.ToInt32(code), GameSparksRT.DeliveryIntent.RELIABLE, data, receiverIds);
        }

        if (isBuffered)
        {
            if (isLocal)
            {
                LocalRPC_Buffer.Add(rpc);
                LocalRPC("Add_LocalRPC_Buffer", SparkTargets.Others, false, rpc);
            }
            else
            {
                RPC_Buffer.Add(rpc);
                LocalRPC("Add_RPC_Buffer", SparkTargets.Others, false, rpc);
            }
        }
    }
Beispiel #13
0
    private void MultiplayerSpawnEnemy(int id, EnemyBehavior behavior)
    {
        if (behavior == null)
        {
            return;
        }
        Transform   enemyTransform = behavior.transform;
        Rigidbody2D rigidbody      = behavior.GetComponent <Rigidbody2D>();

        using (RTData data = RTData.Get())
        {
            Vector2 pos     = enemyTransform.position;
            Signs   posSign = SignsExt.GetSign(pos);
            Vector2 vel     = rigidbody.velocity;
            Signs   velSign = SignsExt.GetSign(vel);
            data.SetInt(1, id);
            data.SetVector2(3, pos);
            data.SetInt(4, (int)posSign);
            data.SetFloat(5, enemyTransform.rotation.eulerAngles.z);
            data.SetVector2(6, vel);
            data.SetInt(7, (int)velSign);
            gameSparksManager.RTSession.SendData(
                MultiplayerCodes.ENEMY_SPAWN.Int(),
                GameSparksRT.DeliveryIntent.RELIABLE,
                data
                );
        }
    }
Beispiel #14
0
    IEnumerator SendTransformUpdates()
    {
        // To be safe
        if (!_transform)
        {
            _transform = transform;
        }
        if (!_rigidbody)
        {
            _rigidbody = GetComponent <Rigidbody2D>();
        }

        while (true)
        {
            using (RTData data = RTData.Get())
            {
                Vector3 pos = _transform.position;
                Vector2 vel = _rigidbody.velocity;
                data.SetVector3(1, pos);
                Signs posSign = SignsExt.GetSign(pos);
                data.SetInt(2, (int)posSign);
                data.SetFloat(3, _transform.eulerAngles.z);
                data.SetVector2(4, vel);
                data.SetInt(5, (int)SignsExt.GetSign(vel));
                _gameSparksManager.RTSession.SendData(
                    MultiplayerCodes.PLAYER_POSITION.Int(),
                    GameSparksRT.DeliveryIntent.UNRELIABLE_SEQUENCED,
                    data
                    );
            }
            yield return(new WaitForSeconds(UpdateRate));
        }
    }
 public void SendString(int code, uint index, string value)
 {
     using (RTData data = RTData.Get())
     {
         data.SetString(index, value);
         SendPacket(code, data, GameSparksRT.DeliveryIntent.RELIABLE);
     }
 }
 public void SendFloat(uint index, float value)
 {
     using (RTData data = RTData.Get())
     {
         data.SetFloat(index, value);
         SendPacket(data, GameSparksRT.DeliveryIntent.RELIABLE);
     }
 }
 public void SendPacket(int code, GameSparksRT.DeliveryIntent intent = GameSparksRT.DeliveryIntent.RELIABLE)
 {
     using (RTData data = RTData.Get())
     {
         data.SetInt((int)NetworkManager.DataIndex.ObjectCode, code);
         SendPacket(data, intent);
     }
 }
Beispiel #18
0
 //Function for Sending the damage on player hit
 public void SendHit(int dmg, int peerID)
 {
     using (RTData data = RTData.Get()) {                                                                                               // we put a using statement here so that we can dispose of the RTData objects once the packet is sent
         data.SetInt(1, dmg);                                                                                                           // add the position at key 1
         data.SetInt(2, peerID);
         GameSparksManager.Instance().GetRTSession().SendData(3, GameSparks.RT.GameSparksRT.DeliveryIntent.UNRELIABLE_SEQUENCED, data); // send the data
     }
 }
Beispiel #19
0
 /// <summary>
 /// Change scene for all players. This function is called by a user.
 /// </summary>
 /// <param name="_sceneName">The name of the scene to change to</param>
 /// <example><code>
 /// void SomeFunction()
 /// {
 ///     ASL.ASLHelper.SendAndSetNewScene("YourSceneName");
 /// }
 /// </code></example>
 public static void SendAndSetNewScene(string _sceneName)
 {
     using (RTData data = RTData.Get())
     {
         data.SetString((int)GameController.DataCode.SceneName, _sceneName);
         GameSparksManager.Instance().GetRTSession().SendData((int)GameSparksManager.OpCode.LoadScene, GameSparksRT.DeliveryIntent.RELIABLE, data);
     }
 }
Beispiel #20
0
        /// <summary>
        /// CoRoutine that resolves the cloud anchor
        /// </summary>
        /// <param name="_objectId">The ASLObject tied to this cloud anchor</param>
        /// <param name="anchorID">The cloud anchor to resolve</param>
        /// <param name="_setWorldOrigin">Whether or not to set the world origin</param>
        /// <param name="_waitForAllUsersToResolve">Whether or not to wait for all users before creating the cloud anchor</param>
        /// <returns>yield wait for - until tracking</returns>
        private IEnumerator ResolveCloudAnchor(string _objectId, string anchorID, string _setWorldOrigin, string _waitForAllUsersToResolve)
        {
            //If not the device is currently not tracking, wait to resolve the anchor
            while (Session.Status != SessionStatus.Tracking)
            {
                yield return(new WaitForEndOfFrame());
            }
            Debug.Log("in:");
            XPSession.ResolveCloudAnchor(anchorID).ThenAction((Action <CloudAnchorResult>)(result =>
            {
                //If failed to resolve
                if (result.Response != CloudServiceResponse.Success)
                {
                    Debug.LogError("Could not resolve Cloud Anchor: " + anchorID + " " + result.Response);
                }

                Debug.Log("Successfully Resolved cloud anchor: " + anchorID);
                //Now have at least one cloud anchor in the scene
                ASLObject anchorObjectPrefab;
                if (ASLHelper.m_ASLObjects.TryGetValue(_objectId ?? string.Empty, out ASLObject myObject)) //if user has ASL object -> ASL Object was created before linking to cloud anchor
                {
                    anchorObjectPrefab = myObject;
                    anchorObjectPrefab._LocallySetAnchorID(result.Anchor.CloudId);
                    anchorObjectPrefab.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f); //Set scale to be 10 cm
                }
                else //ASL Object was created to link to cloud anchor - do the same here
                {
                    //Uncomment the line below to aid in visual debugging (helps display the cloud anchor)
                    //anchorObjectPrefab = GameObject.CreatePrimitive(PrimitiveType.Cube).AddComponent<ASLObject>(); //if null, then create empty game object
                    anchorObjectPrefab = new GameObject().AddComponent <ASLObject>();
                    anchorObjectPrefab._LocallySetAnchorID(result.Anchor.CloudId); //Add ASLObject component to this anchor and set its anchor id variable
                    anchorObjectPrefab._LocallySetID(result.Anchor.CloudId);       //Locally set the id of this object to be that of the anchor id (which is unique)

                    //Add this anchor object to our ASL dictionary using the anchor id as its key. All users will do this once they resolve this cloud anchor to ensure they still in sync.
                    ASLHelper.m_ASLObjects.Add(result.Anchor.CloudId, anchorObjectPrefab.GetComponent <ASLObject>());
                    //anchorObjectPrefab.GetComponent<Material>().color = Color.magenta;
                    anchorObjectPrefab.transform.localScale = new Vector3(0.04f, 0.04f, 0.04f); //Set scale to be 10 cm
                }

                if (bool.Parse(_waitForAllUsersToResolve))
                {
                    Debug.Log("Sent resolved");
                    //Send packet to relay server letting it know this user is ready
                    using (RTData data = RTData.Get())
                    {
                        data.SetString((int)DataCode.Id, anchorObjectPrefab.m_Id);
                        GameSparksManager.Instance().GetRTSession().SendData((int)GameSparksManager.OpCode.ResolvedCloudAnchor, GameSparksRT.DeliveryIntent.RELIABLE, data);
                    }
                    //Wait for others
                    anchorObjectPrefab.StartWaitForAllUsersToResolveCloudAnchor(result, bool.Parse(_setWorldOrigin), null);
                }
                else
                {
                    anchorObjectPrefab._LocallySetCloudAnchorResolved(true);
                    anchorObjectPrefab.StartWaitForAllUsersToResolveCloudAnchor(result, bool.Parse(_setWorldOrigin), null);
                }
            }));
        }
 public void SendPacket_Ring(OnlinePacket packet)
 {
     using (RTData data = RTData.Get()) {
         data.SetVector3(1, packet.position);
         data.SetVector3(2, packet.rotation);
         data.SetVector3(3, packet.velocity);
         session.SendData(101, GameSparksRT.DeliveryIntent.RELIABLE, data);
     }
 }
 /// <summary>
 /// Send and set the AR anchor point for this object for all users.
 /// </summary>
 /// <param name="_anchorPoint">The anchor point for this object to reference</param>
 /// <example><code>
 /// void SomeFunction()
 /// {
 ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetClaim(() =>
 ///     {
 ///         gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetAnchorPoint("Your Anchor Point Here");
 ///     });
 /// }
 /// </code></example>
 public void SendAndSetAnchorPoint(string _anchorPoint)
 {
     using (RTData data = RTData.Get())
     {
         data.SetString((int)GameController.DataCode.Id, m_Id);
         data.SetString((int)GameController.DataCode.AnchorPoint, _anchorPoint);
         GameSparksManager.Instance().GetRTSession().SendData((int)GameSparksManager.OpCode.AnchorPointUpdate, GameSparksRT.DeliveryIntent.RELIABLE, data);
     }
 }
Beispiel #23
0
 public void SetPlayerLoaded()
 {
     Debug.Log("GameSparksManager::SetPlayerLoaded");
     using (RTData data = RTData.Get())
     {
         data.SetInt(1, PeerId());
         SendRTData(OpCodes.PlayerLoaded, GameSparksRT.DeliveryIntent.RELIABLE, data, new int[] { 0 });
     }
 }
 public void SendPacket_Field(OnlinePacket packet)
 {
     using (RTData data = RTData.Get()) {
         data.SetInt(1, packet.cola_score);
         data.SetInt(2, packet.pepsi_score);
         data.SetString(3, packet.cola_bottles);
         data.SetString(4, packet.pepsi_bottles);
         session.SendData(102, GameSparksRT.DeliveryIntent.RELIABLE, data);
     }
 }
 public void sendMovementPacket(Vector3 pos, string animName, int isFlipped)
 {
     using (RTData data = RTData.Get())
     {
         data.SetVector2(1, pos);
         data.SetString(2, animName);
         data.SetInt(3, isFlipped);
         RTClass.SendData(100, GameSparksRT.DeliveryIntent.UNRELIABLE_SEQUENCED, data);
     }
 }
 public void sendDamagePacket(char hurtType, Vector2 hitDir, float damage, Vector2 hitLoc, int player)
 {
     using (RTData data = RTData.Get())
     {
         data.SetString(1, hurtType.ToString());
         data.SetVector2(2, hitDir);
         data.SetFloat(3, damage);
         data.SetVector2(4, hitLoc);
         RTClass.SendData(110, GameSparksRT.DeliveryIntent.UNRELIABLE_SEQUENCED, data, player);
     }
 }
 /// <summary>
 /// Deletes this object for all users
 /// </summary>
 /// <example><code>
 /// void SomeFunction()
 /// {
 ///     gameobject.GetComponent&lt;ASL.ASLObject&gt;().SendAndSetClaim(() =>
 ///     {
 ///         gameobject.GetComponent&lt;ASL.ASLObject&gt;().DeleteObject();
 ///     });
 /// }
 /// </code></example>
 public void DeleteObject()
 {
     if (gameObject && m_Mine)
     {
         using (RTData data = RTData.Get())
         {
             data.SetString((int)GameController.DataCode.Id, m_Id);
             GameSparksManager.Instance().GetRTSession().SendData((int)GameSparksManager.OpCode.DeleteObject, GameSparksRT.DeliveryIntent.RELIABLE, data);
         }
     }
 }
Beispiel #28
0
    private IEnumerator DelayTurnStart()
    {
        yield return(new WaitForSeconds(5f));

        using (RTData data = RTData.Get()) //send player ready to start the match to the server
        {
            Debug.Log("Send Ready to server..");
            data.SetLong(1, 0);
            RT_manager.SendData(104, GameSparks.RT.GameSparksRT.DeliveryIntent.UNRELIABLE_SEQUENCED, data, new int[] { 0 }); // send to peerId -> 0, which is the server
        }
    }
Beispiel #29
0
    private IEnumerator SendTimeStamp()
    {
        // send a packet with our current time
        using (RTData data = RTData.Get())
        {
            data.SetLong(1, (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds);                  // get the current time as unix timestamp
            RT_manager.SendData(101, GameSparks.RT.GameSparksRT.DeliveryIntent.UNRELIABLE_SEQUENCED, data, new int[] { 0 }); // send to peerId -> 0, which is the server
        }
        yield return(new WaitForSeconds(2f));                                                                                // wait 5 seconds

        StartCoroutine(SendTimeStamp());                                                                                     // send the timestamp again
    }
Beispiel #30
0
 void SendHealthUpdate(float hp)
 {
     using (RTData data = RTData.Get())
     {
         data.SetFloat(1, hp);
         GameSparks.RTSession.SendData(
             MultiplayerCodes.PLAYER_HEALTH.Int(),
             GameSparksRT.DeliveryIntent.RELIABLE,
             data
             );
     }
 }