123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- using UnityEngine;
- using UnityEngine.UI;
- namespace Mirror.Examples.CouchCoop
- {
- public class CouchPlayer : NetworkBehaviour
- {
- public Rigidbody rb;
- public float movementSpeed = 3;
- public float jumpSpeed = 6;
- private float movementVelocity;
- private bool isGrounded;
- public CouchPlayerManager couchPlayerManager;
- private KeyCode jumpKey = KeyCode.Space; // Check CouchPlayerManager for controls
- private KeyCode leftKey = KeyCode.LeftArrow;
- private KeyCode rightKey = KeyCode.RightArrow;
- [SyncVar(hook = nameof(OnNumberChangedHook))]
- public int playerNumber = 0;
- public Text textPlayerNumber;
- public override void OnStartAuthority()
- {
- this.enabled = true;
- if (isOwned)
- {
- #if UNITY_2021_3_OR_NEWER
- couchPlayerManager = GameObject.FindAnyObjectByType<CouchPlayerManager>();
- #else
- // Deprecated in Unity 2023.1
- couchPlayerManager = GameObject.FindObjectOfType<CouchPlayerManager>();
- #endif
- // setup controls according to the pre-sets on CouchPlayerManager
- jumpKey = couchPlayerManager.playerKeyJump[playerNumber];
- leftKey = couchPlayerManager.playerKeyLeft[playerNumber];
- rightKey = couchPlayerManager.playerKeyRight[playerNumber];
- }
- }
- public void Start()
- {
- SetPlayerUI();
- }
- void Update()
- {
- if (!Application.isFocused) return;
- if (isOwned == false) { return; }
- // you can control all local players via arrow keys and space bar for fun testing
- // otherwise check and set individual controls in CouchPlayerManager script.
- if (isGrounded == true)
- {
- if (Input.GetKey(KeyCode.Space) || Input.GetKeyDown(jumpKey))
- {
- rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
- }
- }
- movementVelocity = 0;
- if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(leftKey))
- {
- movementVelocity = -movementSpeed;
- }
- if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(rightKey))
- {
- movementVelocity = movementSpeed;
- }
- rb.velocity = new Vector2(movementVelocity, rb.velocity.y);
- }
- [ClientCallback]
- void OnCollisionExit(Collision col)
- {
- if (isOwned == false) { return; }
- isGrounded = false;
- }
- [ClientCallback]
- void OnCollisionStay(Collision col)
- {
- if (isOwned == false) { return; }
- isGrounded = true;
- }
-
- void OnNumberChangedHook(int _old, int _new)
- {
- //Debug.Log(name + " - OnNumberChangedHook: " + playerNumber);
- SetPlayerUI();
- }
- public void SetPlayerUI()
- {
- // called from hook and in start, to solve a race condition
- if (isOwned)
- {
- textPlayerNumber.text = "Local: " + playerNumber;
- }
- else
- {
- textPlayerNumber.text = "Remote: " + playerNumber;
- }
- }
- }
- }
|