简体   繁体   中英

Multiplayer in Unity

Below is the code for movement of player object and it works perfectly fine. But in the TellClientsToMoveClientRpc why are we doing transform.position as it refers to the the current gameobject but not every object moves, only the one which called the above Rpc moves which is desirable. But why all other gameobject do not move?

using UnityEngine;

namespace HelloWorld
{
    public class HelloWorldPlayer : NetworkBehaviour
    {
        private const float speed = 20f;

        private void Update()
        {
            if (!IsOwner)
                return;

            PlayerMove();
           
        }

        void PlayerMove()
        {
            Vector3 velocity = new(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
            if(velocity.sqrMagnitude >= 1)
            {
                TellServerToMoveClientServerRpc(velocity, NetworkManager.Singleton.LocalClientId);
            }
        }

        [ServerRpc]
        void TellServerToMoveClientServerRpc(Vector3 velocity, ulong clientId)
        {
            TellClientsToMoveClientRpc(velocity, clientId);
        }

        [ClientRpc]
        void TellClientsToMoveClientRpc(Vector3 velocity, ulong clientId)
        {
            transform.position += speed * Time.deltaTime * velocity;
        }
    }
}```

A multiplayer game like this means that there are multiple clients running the same program (the game), meaning that there is a copy of all of the same game objects on each client's instance of the game .

This means that the game object you attached your HelloWorldPlayer script on is present on each client.

When you call TellServerToMoveClientServerRpc from a client, it will execute that function on the same game object the client called the function from , but on the server.This is because you added a [ServerRPC] .

Now that the server has control over what's going to happen next, it calls TellClientsToMoveClientRpc . Now this time, since you added a [ClientRpc] , that function will be called on the same game object the original client called the function from , but now on every single client that's connected to your server.

Since it's always the same game object calling the function (just on different instances of the game, running on different computers), not all game objects move: only the one that initially called the TellServerToMoveClientServerRpc function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM