How to use NetworkServer.ReplacePlayerForConnection() to give a player control over another player object
I'm working on a game mechanic where a player (being a ghost) can take control (possess) another player. What I'm trying to achieve is that when a player take control of another, the player controls the movement and camera of that other player and see throw his camera, while the possessed player will be forced to watch is a character being controlled (like TeamViewer for example.)
I came up with the following solution: change the player object of the player playing the ghost to the player object of the player being possessed and change the player object of the possessed player to a dummy object (An empty GameObject with only a transform and Network Identity).
At first glance, it seems to work, but there seems to be strange glitches when switching the player object. This makes me question if I'm correctly using the Network Server. ReplacePlayerForConnection () method. I have the following code:
[Command]
private void CmdPossess()
{
RaycastHit hit;
if (Physics.Raycast(possessionCamera.transform.position, possessionCamera.transform.forward, out hit, possessionRange, possessionLayerMask))
{
// Stock the posssessed player
possessedPlayer = hit.transform.gameObject;
NetworkConnection ghostPlayerNetworkConnection = GetComponent<NetworkIdentity>().connectionToClient;
short ghostControllerId = GetComponent<NetworkIdentity>().playerControllerId;
NetworkConnection possessedPlayerNetworkConnection = possessedPlayer.GetComponent<NetworkIdentity>().connectionToClient;
short possessedPlayerControllerId = possessedPlayer.GetComponent<NetworkIdentity>().playerControllerId;
// Take controller of the player
NetworkServer.ReplacePlayerForConnection(possessedPlayerNetworkConnection, GameManager.GetInstance().dummyPlayerInstance, possessedPlayerControllerId);
NetworkServer.ReplacePlayerForConnection(ghostPlayerNetworkConnection, possessedPlayer, ghostControllerId);
possessedPlayer.GetComponent<NetworkIdentity>().AssignClientAuthority(ghostPlayerNetworkConnection);
}
}
Your answer
Follow this Question
Related Questions
Unet Game on Phton Server? 0 Answers
Unity Network for RTS 0 Answers
[UNET 5.2] Multiple local authority for 1 object? 0 Answers
Pull Playfab users list 0 Answers
How to use a script to control the nickname of online players 0 Answers