双关语 2 同步

Pun 2 Synchronizing

我用 pun2 (Photon Unity Networking) 创建了一个多人游戏,但是当我移动并查看时,我角色的变化实际上会应用到其他角色,当我的朋友移动时,他们的变化也会应用到我的角色

void Update(){

isGrounded = Physic.CheckSqhere(groundCheck.position,groundDistance, LayeMask);

if (isGrounded && velocity.y<0)
{
    velocity.y=-1f;
}

float x = Input.GetAxis("Horizontal");

float z = Input.GetAxis("Vertical");

if (Input.GetButtonDown("Jump") && isGrounded)
{
    velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}

Vector3 Movement = transform.right * x * transform.forward *z;

if (isGrounded)
{
    characterController.Move(Movement * speed * Time.deltaTime)
}
else{
    characterController.Move(Movement * speedOnJumping * Time.deltaTime)
}

velocity.y +=gravity * Time.deltaTime;
characterController.Move(velocity * Time.deltaTime);}

void Start(){
PhotonNetwork.ConnectUsingsettings();
}

public override void onConnectedToMaster(){
PhotonNetwork. AutomaticallySyncScene = true;
createButton.onclick.AddListener(()=>{
    PhotonNetwork.createRoom("Amin's Room");
});

joinButton.onclick.AddListener(()=>{
    PhotonNetwork.JoinRoom("Amin'sRoom");
});
base.OnConnectedToMaster();
}
public override void OnJoinedRoom(){
if (PhotonNetwork.IsMasterClient){
    Debug.Log("you are the master");
    PhotonNetwork.LoadLevel(1);
}
base.OnJoined Room();
}   

对于未来:请将代码添加为 TEXT,而不是作为图像添加到您的问题中!


在您的 Update 方法中,您监听全局键盘事件。这些将在该脚本的 all 个实例上执行。

您应该检查该组件是否真的属于您自己的播放器,否则请忽略它,或者最好禁用整个组件!

Photon User Input Management

// Note that inheriting from MonoBehaviourPun instead of MonoBehaviour is mandatory!
public class YourClass : MonoBehaviourPun
{
    ...

    private void Update()
    {
        // As also described in the link the IsConnected is checked in order to allow 
        // offline debugging of your behavior without being in a network session
        if(PhotonNetwork.IsConnected && !photonView.IsMine)
        {
            // optional but why keep an Update method running of a script that 
            // shall anyway only be handled by the local player?
            //enabled = false;
            // Or you could even remove the entire component
            //Destroy(this);
    
            // Do nothing else
            return;
        }
    
        ...
    }
}