Need help with 2D Networking

Updated on March 7, 2017 in  [R] Scripts
Share on Facebook0Tweet about this on Twitter0Share on Google+0Share on Reddit0
3 on March 6, 2017

Hi there.

I learned a lot from Brackey’s tutorial on uNet network programming and his tutorial videos are awesome to understand, especially when I am assigned to network programming for our future project.

This leads me, however, to my concern. You see, I just made a test 2D simple platform project for practicing my uNet programming skills. Below are links to some screenshots from my project along with explanations for each picture:

http://imgur.com/O464url — This is the lobby scene, where you either create or join a room. This is pretty much based on Brackey’s lobby from his tutorial videos. Hahaha!

http://imgur.com/a/50c6w — This is the main game scene, where you simply walk and jump around. The controls are simple: you can press the on-screen D-pad and press the on-screen A button to jump or use the arrow keys to move around and press the up arrow or space bar to jump. This is just a test project, so there is nothing fancy.

The following are the scripts used in my test project. Credits to Prime31 for his/her awesome CharacterController2D.cs script. It solved my problem on using CharacterController in 2D games: https://github.com/prime31/CharacterController2D

PlayerControls.cs

 using UnityEngine;
 using System.Collections;
 using Brackeys;
 namespace Prime31
 {
 public class PlayerControls : MonoBehaviour
 {
 #region PUBLIC VARIABLES
 // movement config
 public float gravity = -25f;
 public float runSpeed = 8f;
 public float groundDamping = 20f; // how fast do we change direction? higher means faster
 public float inAirDamping = 5f;
 public float jumpHeight = 3f;
 #endregion
 #region PRIVATE VARIABLES
 private float normalizedHorizontalSpeed = 0;
 private CharacterController2D _controller;
 private Animator _animator;
 private RaycastHit2D _lastControllerColliderHit;
 private Vector3 _velocity;
 #endregion
 #region PROPERTY VARIABLES
 public float NormalizedHorizontalSpeed
 {
 get { return normalizedHorizontalSpeed; }
 set { normalizedHorizontalSpeed = value; }
 }
 #endregion
 #region MONOBEHAVIOUR CALLBACKS
 void Awake()
 {
 _animator = GetComponent();
 _controller = GetComponent();
 // listen to some events for illustration purposes
 _controller.onControllerCollidedEvent += onControllerCollider;
 _controller.onTriggerEnterEvent += onTriggerEnterEvent;
 _controller.onTriggerExitEvent += onTriggerExitEvent;
 }
 // the Update loop contains a very simple example of moving the character around and controlling the animation
 void Update()
 {
 #region OTHER CONTROLS
 if (Input.GetKeyDown(KeyCode.P) || Input.GetKeyDown(KeyCode.Escape))
 TogglePauseMenu();
 if (PauseMenu.IsOn)
 return;
 #endregion
 #region HORIZONTAL MOVEMENT
 // Arrow keys to move
 if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
 normalizedHorizontalSpeed = -1;
 else if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
 normalizedHorizontalSpeed = 1;
 else if (!Input.anyKey) // No keys are pressed.
 normalizedHorizontalSpeed = 0;
 HorizontalMovement();
 // apply horizontal speed smoothing it. dont really do this with Lerp. Use SmoothDamp or something that provides more control
 var smoothedMovementFactor = _controller.isGrounded ? groundDamping : inAirDamping; // how fast do we change direction?
 _velocity.x = Mathf.Lerp(_velocity.x, normalizedHorizontalSpeed * runSpeed, Time.deltaTime * smoothedMovementFactor);
 #endregion
 #region VERTICAL MOVEMENT
 // Stop vertical movement when the character lands or is on the ground.
 if (_controller.isGrounded)
 _velocity.y = 0;
 // Arrow keys to jump
 if (Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space))
 Jump();
 // apply gravity before moving
 _velocity.y += gravity * Time.deltaTime;
 // if holding down bump up our movement amount and turn off one way platform detection for a frame.
 // this lets us jump down through one way platforms
 if (_controller.isGrounded && Input.GetKey(KeyCode.DownArrow))
 {
 _velocity.y *= 3f;
 _controller.ignoreOneWayPlatformsThisFrame = true;
 }
 #endregion
 _controller.move(_velocity * Time.deltaTime);
 // grab our current _velocity to use as a base for all calculations
 _velocity = _controller.velocity;
 }
 #endregion
 #region PUBLIC METHODS
 public void Jump()
 {
 if (_controller.isGrounded)
 {
 _velocity.y = Mathf.Sqrt(2f * jumpHeight * -gravity);
 _animator.Play(Animator.StringToHash("Jump"));
 _controller.move(_velocity * Time.deltaTime);
 // grab our current _velocity to use as a base for all calculations
 _velocity = _controller.velocity;
 }
 }
 public void TogglePauseMenu()
 {
 GameObject pauseMenu = GameObject.Find("PauseMenuCanvas").transform.GetChild(0).gameObject;
 pauseMenu.SetActive(!pauseMenu.activeSelf);
 PauseMenu.IsOn = pauseMenu.activeSelf;
 }
 #endregion
 #region PRIVATE METHODS
 private void HorizontalMovement()
 {
 if (normalizedHorizontalSpeed != 0)
 {
 if (normalizedHorizontalSpeed == -1)
 {
 if (transform.localScale.x > 0f)
 transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
 }
 else if (normalizedHorizontalSpeed == 1)
 {
 if (transform.localScale.x < 0f)
 transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
 }
 else
 {
 Debug.LogError("Please set your value to -1 for left movement or 1 for right movement only.");
 return;
 }
 if (_controller.isGrounded)
 _animator.Play(Animator.StringToHash("Run"));
 }
 else
 {
 if (_controller.isGrounded)
 _animator.Play(Animator.StringToHash("Idle"));
 }
 }
 private void VerticalMovement()
 {
 }
 #endregion
 #region EVENT LISTENERS
 void onControllerCollider(RaycastHit2D hit)
 {
 // bail out on plain old ground hits cause they arent very interesting
 if (hit.normal.y == 1f)
 return;
 // logs any collider hits if uncommented. it gets noisy so it is commented out for the demo
 //Debug.Log( "flags: " + _controller.collisionState + ", hit.normal: " + hit.normal );
 }
 void onTriggerEnterEvent(Collider2D col)
 {
 Debug.Log("onTriggerEnterEvent: " + col.gameObject.name);
 }
 void onTriggerExitEvent(Collider2D col)
 {
 Debug.Log("onTriggerExitEvent: " + col.gameObject.name);
 }
 #endregion
 }
 }
 

OnScreenController.cs

 using UnityEngine;
 using Prime31;
 public class OnScreenController : MonoBehaviour
 {
 private PlayerControls _character;
 public void SetHorizontalMovement(float _value)
 {
 GetPlayerControls();
 if (_character != null)
 _character.NormalizedHorizontalSpeed = _value;
 else
 Debug.LogError("Please look for a prefab with component PlayerControls.");
 }
 public void SetVerticalMovement(float _value)
 {
 }
 public void SetJumpMovement()
 {
 GetPlayerControls();
 if (_character != null)
 _character.Jump();
 else
 Debug.LogError("Please look for a prefab with component PlayerControls.");
 }
 public void SetPauseGame()
 {
 GetPlayerControls();
 if (_character != null)
 _character.TogglePauseMenu();
 else
 Debug.LogError("Please look for a prefab with component PlayerControls.");
 }
 private void GetPlayerControls()
 {
 _character = GameObject.FindObjectOfType().GetComponent();
 }
 }
 

The rest of the scripts are from Brackeys’ tutorial videos on networking. Please check them out.

So here is my problem. Whenever I leave a room and re-enter another room, I can no longer control my character. I tried my best to find a solution but to no avail.

I appreciate your constructive and prompt answers, help, and feedback. Thank you very much!

  • Liked by
Reply
2 on March 6, 2017

Let us know what you’ve tried if you can!
E.g. The controller script is still enabled, it doesn’t think the game is paused etc.
the more you narrow it down the better we can assist :)

on March 7, 2017

I already figured it out!

When I leave the room, I forgot to set IsOn from Brackeys’ PauseMenu.cs script to false so that the player can control the character when he/she creates or enters another room.

Thank you for your reply! 😀

Devoted
on March 7, 2017

Ah so it was what I guessed in the end :)

No prob!

Show more replies
  • Liked by
Reply
Cancel