Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.Networking;
- using System.Collections.Generic;
- [NetworkSettings(channel=2)]
- public class Moving : NetworkBehaviour {
- [SyncVar] Color color;
- [SyncVar] CubeState state;
- Queue<KeyCode> pendingMoves;
- CubeState predictedState;
- [SyncVar(hook="OnServerStateChanged")] CubeState serverState;
- [Command(channel=0)]
- void CmdMoveOnServer(KeyCode arrowKey) {
- serverState = Move (state, arrowKey);
- }
- struct CubeState
- {
- public int moveNum;
- public float x;
- public float y;
- public float z;
- }
- void Start() {
- if (isLocalPlayer) {
- pendingMoves = new Queue<KeyCode> ();
- predictedState = new CubeState {
- moveNum = 0,
- x = 0,
- y = 0,
- z = 0
- };
- }
- SyncColor ();
- }
- void Awake()
- {
- InitState ();
- }
- [Server]
- void InitState ()
- {
- Color[] colors = { Color.blue, Color.cyan, Color.green, Color.magenta, Color.red,Color.yellow };
- color = colors [Random.Range (0, colors.Length)];
- serverState = new CubeState {
- moveNum = 0,
- x = 0,
- y = 0,
- z = 0
- };
- }
- void Update () {
- if (isLocalPlayer) {
- KeyCode[] arrowKeys = { KeyCode.UpArrow, KeyCode.DownArrow, KeyCode.RightArrow, KeyCode.LeftArrow };
- foreach (KeyCode arrowKey in arrowKeys) {
- if (!Input.GetKey (arrowKey))
- continue;
- pendingMoves.Enqueue (arrowKey);
- UpdatePredictedState ();
- CmdMoveOnServer (arrowKey);
- }
- }
- SyncState();
- }
- void SyncState () {
- CubeState stateToRender = isLocalPlayer ? predictedState : serverState;
- transform.position = new Vector3 (stateToRender.x, stateToRender.y, stateToRender.z);
- }
- CubeState Move(CubeState previous, KeyCode arrowKey){
- float dx = 0;
- float dy = 0;
- float dz = 0;
- switch (arrowKey) {
- case KeyCode.UpArrow:
- dz = Time.deltaTime;
- break;
- case KeyCode.DownArrow:
- dz = Time.deltaTime;
- break;
- case KeyCode.RightArrow:
- dx = Time.deltaTime;
- break;
- case KeyCode.LeftArrow:
- dx = Time.deltaTime;
- break;
- }
- return new CubeState {
- moveNum = 1 + previous.moveNum,
- x = dx + previous.x,
- y = dy + previous.y,
- z = dz + previous.z
- };
- }
- void OnServerStateChanged(CubeState newState) {
- serverState = newState;
- if (pendingMoves != null) {
- while (pendingMoves.Count > (predictedState.moveNum - serverState.moveNum)) {
- pendingMoves.Dequeue ();
- }
- UpdatePredictedState ();
- }
- }
- void UpdatePredictedState () {
- predictedState = serverState;
- foreach (KeyCode arrowKey in pendingMoves) {
- predictedState = Move (predictedState, arrowKey);
- }
- }
- void SyncColor () {
- GetComponent<Renderer> ().material.color = (isLocalPlayer ? Color.white : Color.grey) * color;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement