-4

I created a multiplayer game with pun2 (Photon Unity Networking) but when I move and look actually changes of my character will apply to other characters, also when my friends move their changes will apply to my character

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);}

and

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();
}   
Amin
  • 31
  • 6

1 Answers1

0

For the future: Please add code as TEXT not as images to your questions!


In your Update method you listen to global keyboard events. These will be executed on all instances of that script.

You should check if the component actually belongs to your own player and otherwise ignore it or even better disable the entire component!

See 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;
        }
    
        ...
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • I used this solution but now a player who joined later than me, can control my character, and also I can control his one, when 3 persons are in the room the newest player can control the previous player, can you give me a link for an example for fps multiplayer using pun2? – Amin Jan 30 '21 at 10:08