How do I sync head rotation over network?
The whole answer can be found below.
Try Our
Documentation
Please check if you can find an answer in our extensive documentation on PUN.
Join Us
on Discord
Meet and talk to our staff and the entire Photon-Community via Discord.
Read More on
Stack Overflow
Find more information on Stack Overflow (for Circle members only).
How do I sync head rotation over network?
Luca
2021-09-01 20:36:16
So I got this code to make my head rotate vertically with my mouse, I tried syncing this over the network but can't seem to get this to work. I've seen alot of threads on this and Unity's forum but still haven't got a good solution, this guy figured it out 'https://forum.photonengine.com/discussion/18057/moving-a-bone-on-a-humanoid-character-best-way-to-do-this-in-pun', But I don't really understand it.
Here is the code I use which works locally:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class HeadTilt : MonoBehaviourPunCallbacks, IPunObservable
{
public Camera cameraRot;
PhotonView view;
private Vector3 objRot;
public Transform head;
// Use this for initialization
void Start()
{
view = GetComponent<PhotonView>();
}
void LateUpdate()
{
if (view.IsMine)
{
Vector3 tmp = cameraRot.transform.localEulerAngles;
tmp = cameraRot.transform.localEulerAngles;
tmp.x -= cameraRot.transform.localEulerAngles.z;
tmp.y = 0f;
tmp.z = 0f;
objRot = tmp;
head.transform.localEulerAngles = objRot;
}
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
stream.SendNext(objRot);
}
else
{
this.objRot = (Vector3)stream.ReceiveNext();
}
}
}
Comments
The LateUpdate checks IsMine. So the code in that block will only run on the controlling player's client.
Is that intended?
Yes, I want every individual player to have their head rotate up and down with mouse input
There is no code that applies the rotation for non-local players. OnPhotonSerializeView reads the incoming value into a local variable and that's it.
Found a solution. for everyone trying the same thing, put this script on your character:
private Quaternion server_head;
[SerializeField] private Transform Head;
private void LateUpdate()
{
if (photonView.IsMine == false)
{
Head.localRotation = server_head;
}
}
private void FixedUpdate()
{
if (photonView.IsMine == true)
{
photonView.RPC("RPC_UpdateBoneRotations", RpcTarget.AllBuffered, Head.localRotation);
}
}
[PunRPC]
private void RPC_UpdateBoneRotations(Quaternion h)
{
server_head = h;
}
RPCs are very ineffective to do this. You waste quite a bit of network traffic and messages/sec this way.
Better use OnPhotonSerializeView.