Search Unity

Multiplayer 2D movement UNet

Discussion in 'UNet' started by Nexxy, Dec 31, 2018.

  1. Nexxy

    Nexxy

    Joined:
    Mar 17, 2017
    Posts:
    2
    Hey guys! I'm new with the Unity2D networking, and I have a trouble with the movement. There are two simple moving players, in one server, the moving got messed up, and if i move my player right, the other client moves to the right. There is my movement script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class playerManager : MonoBehaviour
    6. {
    7.    
    8.     private bool isGrounded;
    9.     public Transform feetPos;
    10.     public float checkRadius;
    11.     public LayerMask whatIsGround;
    12.     public float jumpForce;
    13.    
    14.     private Rigidbody2D myRigidbody;
    15.    
    16.     [SerializeField]
    17.     private float movementSpeed;
    18.    
    19.    
    20.     void Start()
    21.     {
    22.         myRigidbody = GetComponent<Rigidbody2D>();
    23.     }
    24.  
    25.     void Update() {
    26.        
    27.         isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
    28.        
    29.         if(isGrounded == true && Input.GetKeyDown(KeyCode.Space))
    30.         {
    31.            
    32.             myRigidbody.velocity = Vector2.up * jumpForce;
    33.            
    34.         }
    35.        
    36.     }
    37.    
    38.    
    39.     void FixedUpdate()
    40.     {
    41.         float horizontal = Input.GetAxisRaw("Horizontal");
    42.        
    43.         HandleMovement(horizontal);
    44.     }
    45.    
    46.     private void HandleMovement(float horizontal)
    47.     {
    48.         myRigidbody.velocity = new Vector2(horizontal * movementSpeed,myRigidbody.velocity.y);
    49.     }
    50.    
    51. }
    52.  
    I got a NetworkManager GameObject with NetworkManager and NetworkManagerHUD components in it.
    And in the player prefab, there is a NetworkIdentity and a NetworkTransform. I set in the "Local Player Authorit" in my player.
    So help me! Why the other clients moving with me? How can I fix it?
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    In Update you are not checking if this script is attached to the correct player before checking input and applying velocity. Update, FixedUpdate, etc, will run on the server and all clients for all of the gameobjects in the scene, including objects for players that represent other clients.
     
    Last edited: Jan 9, 2019
  3. Groone

    Groone

    Joined:
    Mar 17, 2018
    Posts:
    7
    I think you do something like this

    Code (CSharp):
    1. if (!isLocalPlayer) return;
    2. HandleMovement(horizontal);