NetworkTransform.cs 64.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
using System;
using UnityEngine;

namespace UnityEngine.Networking
{
    /// <summary>
    /// A component to synchronize the position and rotation of networked objects.
    /// <para>The movement of game objects can be networked by this component. There are two models of authority for networked movement:</para>
    /// <para>If the object has authority on the client, then it should be controlled locally on the owning client, then movement state information will be sent from the owning client to the server, then broadcast to all of the other clients. This is common for player objects.</para>
    /// <para>If the object has authority on the server, then it should be controlled on the server and movement state information will be sent to all clients. This is common for objects not related to a specific client, such as an enemy unit.</para>
    /// </summary>
    [DisallowMultipleComponent]
    [AddComponentMenu("Network/NetworkTransform")]
    [Obsolete("The high level API classes are deprecated and will be removed in the future.")]
    public class NetworkTransform : NetworkBehaviour
    {
        /// <summary>
        /// How to synchronize an object's position.
        /// </summary>
        public enum TransformSyncMode
        {
            /// <summary>
            /// Dont synchronize.
            /// </summary>
            SyncNone = 0,
            /// <summary>
            /// Sync using the game object's base transform.
            /// </summary>
            SyncTransform = 1,
            /// <summary>
            /// Sync using the Rigidbody2D component.
            /// </summary>
            SyncRigidbody2D = 2,
            /// <summary>
            /// Sync using the Rigidbody component.
            /// </summary>
            SyncRigidbody3D = 3,
            /// <summary>
            /// Sync using the CharacterController component.
            /// </summary>
            SyncCharacterController = 4
        }

        /// <summary>
        /// An axis or set of axis.
        /// </summary>
        public enum AxisSyncMode
        {
            /// <summary>
            /// Do not sync.
            /// </summary>
            None,
            /// <summary>
            /// Only x axis.
            /// </summary>
            AxisX,
            /// <summary>
            /// Only the y axis.
            /// </summary>
            AxisY,
            /// <summary>
            /// Only the z axis.
            /// </summary>
            AxisZ,
            /// <summary>
            /// The x and y axis.
            /// </summary>
            AxisXY,
            /// <summary>
            /// The x and z axis.
            /// </summary>
            AxisXZ,
            /// <summary>
            /// The y and z axis.
            /// </summary>
            AxisYZ,
            /// <summary>
            /// The x, y and z axis.
            /// </summary>
            AxisXYZ
        }

        /// <summary>
        /// How much to compress sync data.
        /// </summary>
        public enum CompressionSyncMode
        {
            /// <summary>
            /// Do not compress.
            /// </summary>
            None,
            /// <summary>
            /// A low amount of compression that preserves accuracy.
            /// </summary>
            Low,
            /// <summary>
            /// High Compression - sacrificing accuracy.
            /// </summary>
            High
        }

        public delegate bool ClientMoveCallback3D(ref Vector3 position, ref Vector3 velocity, ref Quaternion rotation);
        public delegate bool ClientMoveCallback2D(ref Vector2 position, ref Vector2 velocity, ref float rotation);

        [SerializeField] TransformSyncMode  m_TransformSyncMode = TransformSyncMode.SyncNone;
        [SerializeField] float              m_SendInterval = 0.1f;
        [SerializeField] AxisSyncMode       m_SyncRotationAxis = AxisSyncMode.AxisXYZ;
        [SerializeField] CompressionSyncMode m_RotationSyncCompression = CompressionSyncMode.None;
        [SerializeField] bool               m_SyncSpin;
        [SerializeField] float              m_MovementTheshold = 0.001f;
        [SerializeField] float              m_VelocityThreshold = 0.0001f;

        [SerializeField] float              m_SnapThreshold = 5.0f;
        [SerializeField] float              m_InterpolateRotation = 1.0f;
        [SerializeField] float              m_InterpolateMovement = 1.0f;
        [SerializeField] ClientMoveCallback3D m_ClientMoveCallback3D;
        [SerializeField] ClientMoveCallback2D m_ClientMoveCallback2D;

        Rigidbody       m_RigidBody3D;
        Rigidbody2D     m_RigidBody2D;
        CharacterController m_CharacterController;
        bool m_Grounded = true;

        // movement smoothing

        Vector3         m_TargetSyncPosition;
        Vector3         m_TargetSyncVelocity;

        Vector3         m_FixedPosDiff;

        Quaternion      m_TargetSyncRotation3D;
        Vector3         m_TargetSyncAngularVelocity3D;

        float           m_TargetSyncRotation2D;
        float           m_TargetSyncAngularVelocity2D;

        float           m_LastClientSyncTime; // last time client received a sync from server
        float           m_LastClientSendTime; // last time client send a sync to server

        Vector3         m_PrevPosition;
        Quaternion      m_PrevRotation;
        float           m_PrevRotation2D;
        float           m_PrevVelocity;

        const float     k_LocalMovementThreshold = 0.00001f;
        const float     k_LocalRotationThreshold = 0.00001f;
        const float     k_LocalVelocityThreshold = 0.00001f;
        const float     k_MoveAheadRatio = 0.1f;

        NetworkWriter   m_LocalTransformWriter;

        // settings

        /// <summary>
        /// What method to use to sync the object's position.
        /// </summary>
        public TransformSyncMode    transformSyncMode { get { return m_TransformSyncMode; } set { m_TransformSyncMode = value; } }
        /// <summary>
        /// The sendInterval controls how often state updates are sent for this object.
        /// <para>Unlike most NetworkBehaviour scripts, for NetworkTransform this is implemented at a per-object level rather than at the per-script level. This allows more flexibility as this component is used in various situation.</para>
        /// <para>If sendInterval is non-zero, then transform state updates are send at most once every sendInterval seconds. However, if an object is stationary, no updates are sent.</para>
        /// <para>If sendInterval is zero, then no automatic updates are sent. In this case, calling SetDirtyBits() on the NetworkTransform will cause an updates to be sent. This could be used for objects like bullets that have a predictable trajectory.</para>
        /// </summary>
        public float                sendInterval { get { return m_SendInterval; } set { m_SendInterval = value; } }
        /// <summary>
        /// Which axis should rotation by synchronized for.
        /// </summary>
        public AxisSyncMode         syncRotationAxis { get { return m_SyncRotationAxis; } set { m_SyncRotationAxis = value; } }
        /// <summary>
        /// How much to compress rotation sync updates.
        /// </summary>
        public CompressionSyncMode  rotationSyncCompression { get { return m_RotationSyncCompression; } set { m_RotationSyncCompression = value; } }
        public bool                 syncSpin { get { return m_SyncSpin; }  set { m_SyncSpin = value; } }
        /// <summary>
        /// The distance that an object can move without sending a movement synchronization update.
        /// </summary>
        public float                movementTheshold { get { return m_MovementTheshold; } set { m_MovementTheshold = value; } }
        /// <summary>
        /// The minimum velocity difference that will be synchronized over the network.
        /// </summary>
        public float                velocityThreshold { get { return m_VelocityThreshold; } set { m_VelocityThreshold = value; } }
        /// <summary>
        /// If a movement update puts an object further from its current position that this value, it will snap to the position instead of moving smoothly.
        /// </summary>
        public float                snapThreshold { get { return m_SnapThreshold; } set { m_SnapThreshold = value; } }
        /// <summary>
        /// Enables interpolation of the synchronized rotation.
        /// <para>If this is not set, object will snap to the new rotation. The larger this number is, the faster the object will interpolate to the target facing direction.</para>
        /// </summary>
        public float                interpolateRotation { get { return m_InterpolateRotation; } set { m_InterpolateRotation = value; } }
        /// <summary>
        /// Enables interpolation of the synchronized movement.
        /// <para>The larger this number is, the faster the object will interpolate to the target position.</para>
        /// </summary>
        public float                interpolateMovement { get { return m_InterpolateMovement; } set { m_InterpolateMovement = value; } }
        /// <summary>
        /// A callback that can be used to validate on the server, the movement of client authoritative objects.
        /// <para>This version of the callback works with objects that use 3D physics. The callback function may return false to reject the movement request completely. It may also modify the movement parameters - which are passed by reference.</para>
        /// <para>The example below set the callback in OnStartServer, and will disconnect a client that moves an object into an invalid position after a number of failures.</para>
        /// <code>
        /// using UnityEngine;
        /// using UnityEngine.Networking;
        ///
        /// public class MyMover : NetworkManager
        /// {
        ///    public int cheatCount = 0;
        ///
        ///    public bool ValidateMove(ref Vector3 position, ref Vector3 velocity, ref Quaternion rotation)
        ///    {
        ///        Debug.Log("pos:" + position);
        ///        if (position.y &gt; 9)
        ///        {
        ///            position.y = 9;
        ///            cheatCount += 1;
        ///            if (cheatCount == 10)
        ///            {
        ///                Invoke("DisconnectCheater", 0.1f);
        ///            }
        ///        }
        ///        return true;
        ///    }
        ///
        ///    void DisconnectCheater()
        ///    {
        ///        GetComponent&lt;<see cref="NetworkIdentity">NetworkIdentity</see>&gt;().connectionToClient.Disconnect();
        ///    }
        ///
        ///    public override void OnStartServer()
        ///    {
        ///        GetComponent&lt;<see cref="NetworkTransform">NetworkTransform</see>&gt;().clientMoveCallback3D = ValidateMove;
        ///    }
        /// }
        /// </code>
        /// This kind of server-side movement validation should be used in conjunction with client side movement validation. The callback should only detect a failure if a client is by-passing client side movement checks - by cheating.
        /// </summary>
        public ClientMoveCallback3D clientMoveCallback3D { get { return m_ClientMoveCallback3D; } set { m_ClientMoveCallback3D = value; } }
        /// <summary>
        /// A callback that can be used to validate on the server, the movement of client authoritative objects.
        /// <para>This version of the callback works with objects that use 2D physics. The callback function may return false to reject the movement request completely. It may also modify the movement parameters - which are passed by reference.</para>
        /// <para>The example below set the callback in OnStartServer, and will disconnect a client that moves an object into an invalid position after a number of failures.</para>
        /// <code>
        /// using UnityEngine;
        /// using UnityEngine.Networking;
        /// 
        /// public class MyMover : NetworkManager
        /// {
        ///    public int cheatCount = 0;
        /// 
        ///    public bool ValidateMove(ref Vector2 position, ref Vector2 velocity, ref float rotation)
        ///    {
        ///        Debug.Log("pos:" + position);
        ///        if (position.y > 9)
        ///        {
        ///            position.y = 9;
        ///            cheatCount += 1;
        ///            if (cheatCount == 10)
        ///            {
        ///                Invoke("DisconnectCheater", 0.1f);
        ///            }
        ///        }
        ///        return true;
        ///    }
        ///
        ///    void DisconnectCheater()
        ///    {
        ///        GetComponent&lt;<see cref="NetworkIdentity">NetworkIdentity</see>&gt;().connectionToClient.Disconnect();
        ///    }
        ///
        ///    public override void OnStartServer()
        ///    {
        ///        GetComponent&lt;<see cref="NetworkTransform">NetworkTransform</see>&gt;().clientMoveCallback2D = ValidateMove;
        ///    }
        /// }
        /// </code>
        /// This kind of server-side movement validation should be used in conjunction with client side movement validation. The callback should only detect a failure if a client is by-passing client side movement checks - by cheating.
        /// </summary>
        public ClientMoveCallback2D clientMoveCallback2D { get { return m_ClientMoveCallback2D; } set { m_ClientMoveCallback2D = value; } }

        // runtime data

        /// <summary>
        /// Cached CharacterController.
        /// </summary>
        public CharacterController  characterContoller { get { return m_CharacterController; } }
        /// <summary>
        /// Cached Rigidbody.
        /// </summary>
        public Rigidbody            rigidbody3D { get { return m_RigidBody3D; } }
        /// <summary>
        /// Cached Rigidbody2D.
        /// </summary>
#pragma warning disable 109
        new public Rigidbody2D          rigidbody2D { get { return m_RigidBody2D; } }
#pragma warning restore 109
        /// <summary>
        /// The most recent time when a movement synchronization packet arrived for this object.
        /// </summary>
        public float                lastSyncTime { get { return m_LastClientSyncTime; } }
        /// <summary>
        /// The target position interpolating towards.
        /// </summary>
        public Vector3              targetSyncPosition { get { return m_TargetSyncPosition; } }
        /// <summary>
        /// The velocity send for synchronization.
        /// </summary>
        public Vector3              targetSyncVelocity { get { return m_TargetSyncVelocity; } }
        /// <summary>
        /// The target position interpolating towards.
        /// </summary>
        public Quaternion           targetSyncRotation3D { get { return m_TargetSyncRotation3D; } }
        /// <summary>
        /// The target rotation interpolating towards.
        /// </summary>
        public float                targetSyncRotation2D { get { return m_TargetSyncRotation2D; } }
        /// <summary>
        /// Tells the NetworkTransform that it is on a surface (this is the default).
        /// <para>Object that are NOT grounded will not interpolate their vertical velocity. This avoid the problem of interpolation fighting with gravity on non-authoritative objects. This only works for RigidBody2D physics objects.</para>
        /// </summary>
        public bool                 grounded { get { return m_Grounded; } set { m_Grounded = value; } }

        void OnValidate()
        {
            if (m_TransformSyncMode < TransformSyncMode.SyncNone || m_TransformSyncMode > TransformSyncMode.SyncCharacterController)
            {
                m_TransformSyncMode = TransformSyncMode.SyncTransform;
            }

            if (m_SendInterval < 0)
            {
                m_SendInterval = 0;
            }

            if (m_SyncRotationAxis < AxisSyncMode.None || m_SyncRotationAxis > AxisSyncMode.AxisXYZ)
            {
                m_SyncRotationAxis = AxisSyncMode.None;
            }

            if (m_MovementTheshold < 0)
            {
                m_MovementTheshold = 0.00f;
            }

            if (m_VelocityThreshold < 0)
            {
                m_VelocityThreshold = 0.00f;
            }

            if (m_SnapThreshold < 0)
            {
                m_SnapThreshold = 0.01f;
            }

            if (m_InterpolateRotation < 0)
            {
                m_InterpolateRotation = 0.01f;
            }

            if (m_InterpolateMovement < 0)
            {
                m_InterpolateMovement  = 0.01f;
            }
        }

        void Awake()
        {
            m_RigidBody3D = GetComponent<Rigidbody>();
            m_RigidBody2D = GetComponent<Rigidbody2D>();
            m_CharacterController = GetComponent<CharacterController>();
            m_PrevPosition = transform.position;
            m_PrevRotation = transform.rotation;
            m_PrevVelocity = 0;

            // cache these to avoid per-frame allocations.
            if (localPlayerAuthority)
            {
                m_LocalTransformWriter = new NetworkWriter();
            }
        }

        public override void OnStartServer()
        {
            m_LastClientSyncTime = 0;
        }

        public override bool OnSerialize(NetworkWriter writer, bool initialState)
        {
            if (initialState)
            {
                // always write initial state, no dirty bits
            }
            else if (syncVarDirtyBits == 0)
            {
                writer.WritePackedUInt32(0);
                return false;
            }
            else
            {
                // dirty bits
                writer.WritePackedUInt32(1);
            }

            switch (transformSyncMode)
            {
                case TransformSyncMode.SyncNone:
                {
                    return false;
                }
                case TransformSyncMode.SyncTransform:
                {
                    SerializeModeTransform(writer);
                    break;
                }
                case TransformSyncMode.SyncRigidbody3D:
                {
                    SerializeMode3D(writer);
                    break;
                }
                case TransformSyncMode.SyncRigidbody2D:
                {
                    SerializeMode2D(writer);
                    break;
                }
                case TransformSyncMode.SyncCharacterController:
                {
                    SerializeModeCharacterController(writer);
                    break;
                }
            }
            return true;
        }

        void SerializeModeTransform(NetworkWriter writer)
        {
            // position
            writer.Write(transform.position);

            // no velocity

            // rotation
            if (m_SyncRotationAxis != AxisSyncMode.None)
            {
                SerializeRotation3D(writer, transform.rotation, syncRotationAxis, rotationSyncCompression);
            }

            // no spin

            m_PrevPosition = transform.position;
            m_PrevRotation = transform.rotation;
            m_PrevVelocity = 0;
        }

        void VerifySerializeComponentExists()
        {
            bool throwError = false;
            Type componentMissing = null;

            switch (transformSyncMode)
            {
                case TransformSyncMode.SyncCharacterController:
                    if (!m_CharacterController && !(m_CharacterController = GetComponent<CharacterController>()))
                    {
                        throwError = true;
                        componentMissing = typeof(CharacterController);
                    }
                    break;

                case TransformSyncMode.SyncRigidbody2D:
                    if (!m_RigidBody2D && !(m_RigidBody2D = GetComponent<Rigidbody2D>()))
                    {
                        throwError = true;
                        componentMissing = typeof(Rigidbody2D);
                    }
                    break;

                case TransformSyncMode.SyncRigidbody3D:
                    if (!m_RigidBody3D && !(m_RigidBody3D = GetComponent<Rigidbody>()))
                    {
                        throwError = true;
                        componentMissing = typeof(Rigidbody);
                    }
                    break;
            }

            if (throwError && componentMissing != null)
            {
                throw new InvalidOperationException(string.Format("transformSyncMode set to {0} but no {1} component was found, did you call NetworkServer.Spawn on a prefab?", transformSyncMode, componentMissing.Name));
            }
        }

        void SerializeMode3D(NetworkWriter writer)
        {
            VerifySerializeComponentExists();

            if (isServer && m_LastClientSyncTime != 0)
            {
                // target position
                writer.Write(m_TargetSyncPosition);

                // target velocity
                SerializeVelocity3D(writer, m_TargetSyncVelocity, CompressionSyncMode.None);

                if (syncRotationAxis != AxisSyncMode.None)
                {
                    // target rotation
                    SerializeRotation3D(writer, m_TargetSyncRotation3D, syncRotationAxis, rotationSyncCompression);
                }
            }
            else
            {
                // current position
                writer.Write(m_RigidBody3D.position);

                // current velocity
                SerializeVelocity3D(writer, m_RigidBody3D.velocity, CompressionSyncMode.None);

                if (syncRotationAxis != AxisSyncMode.None)
                {
                    // current rotation
                    SerializeRotation3D(writer, m_RigidBody3D.rotation, syncRotationAxis, rotationSyncCompression);
                }
            }

            // spin
            if (m_SyncSpin)
            {
                SerializeSpin3D(writer, m_RigidBody3D.angularVelocity, syncRotationAxis, rotationSyncCompression);
            }

            m_PrevPosition = m_RigidBody3D.position;
            m_PrevRotation = transform.rotation;
            m_PrevVelocity = m_RigidBody3D.velocity.sqrMagnitude;
        }

        void SerializeModeCharacterController(NetworkWriter writer)
        {
            VerifySerializeComponentExists();

            if (isServer && m_LastClientSyncTime != 0)
            {
                // target position
                writer.Write(m_TargetSyncPosition);

                // no velocity

                if (syncRotationAxis != AxisSyncMode.None)
                {
                    // target rotation
                    SerializeRotation3D(writer, m_TargetSyncRotation3D, syncRotationAxis, rotationSyncCompression);
                }
            }
            else
            {
                // current position
                writer.Write(transform.position);

                // no velocity

                if (syncRotationAxis != AxisSyncMode.None)
                {
                    // current rotation
                    SerializeRotation3D(writer, transform.rotation, syncRotationAxis, rotationSyncCompression);
                }
            }

            // no spin

            m_PrevPosition = transform.position;
            m_PrevRotation = transform.rotation;
            m_PrevVelocity = 0;
        }

        void SerializeMode2D(NetworkWriter writer)
        {
            VerifySerializeComponentExists();

            if (isServer && m_LastClientSyncTime != 0)
            {
                // target position
                writer.Write((Vector2)m_TargetSyncPosition);

                // target velocity
                SerializeVelocity2D(writer, m_TargetSyncVelocity, CompressionSyncMode.None);

                // target rotation
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    float orientation = m_TargetSyncRotation2D % 360;
                    if (orientation < 0) orientation += 360;
                    SerializeRotation2D(writer, orientation, rotationSyncCompression);
                }
            }
            else
            {
                // current position
                writer.Write(m_RigidBody2D.position);

                // current velocity
                SerializeVelocity2D(writer, m_RigidBody2D.velocity, CompressionSyncMode.None);

                // current rotation
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    float orientation = m_RigidBody2D.rotation % 360;
                    if (orientation < 0) orientation += 360;
                    SerializeRotation2D(writer, orientation, rotationSyncCompression);
                }
            }

            // spin
            if (m_SyncSpin)
            {
                SerializeSpin2D(writer, m_RigidBody2D.angularVelocity, rotationSyncCompression);
            }

            m_PrevPosition = m_RigidBody2D.position;
            m_PrevRotation = transform.rotation;
            m_PrevVelocity = m_RigidBody2D.velocity.sqrMagnitude;
        }

        public override void OnDeserialize(NetworkReader reader, bool initialState)
        {
            if (isServer && NetworkServer.localClientActive)
                return;

            if (!initialState)
            {
                if (reader.ReadPackedUInt32() == 0)
                    return;
            }

            switch (transformSyncMode)
            {
                case TransformSyncMode.SyncNone:
                {
                    return;
                }
                case TransformSyncMode.SyncTransform:
                {
                    UnserializeModeTransform(reader, initialState);
                    break;
                }
                case TransformSyncMode.SyncRigidbody3D:
                {
                    UnserializeMode3D(reader, initialState);
                    break;
                }
                case TransformSyncMode.SyncRigidbody2D:
                {
                    UnserializeMode2D(reader, initialState);
                    break;
                }
                case TransformSyncMode.SyncCharacterController:
                {
                    UnserializeModeCharacterController(reader, initialState);
                    break;
                }
            }
            m_LastClientSyncTime = Time.time;
        }

        void UnserializeModeTransform(NetworkReader reader, bool initialState)
        {
            if (hasAuthority)
            {
                // this component must read the data that the server wrote, even if it ignores it.
                // otherwise the NetworkReader stream will still contain that data for the next component.

                // position
                reader.ReadVector3();

                if (syncRotationAxis != AxisSyncMode.None)
                {
                    UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }
                return;
            }

            if (isServer && m_ClientMoveCallback3D != null)
            {
                var pos = reader.ReadVector3();
                var vel = Vector3.zero;
                var rot = Quaternion.identity;
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    rot = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }

                if (m_ClientMoveCallback3D(ref pos, ref vel, ref rot))
                {
                    transform.position = pos;
                    if (syncRotationAxis != AxisSyncMode.None)
                    {
                        transform.rotation = rot;
                    }
                }
                else
                {
                    // rejected by callback
                    return;
                }
            }
            else
            {
                // position
                transform.position = reader.ReadVector3();

                // no velocity

                // rotation
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    transform.rotation = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }

                // no spin
            }
        }

        void UnserializeMode3D(NetworkReader reader, bool initialState)
        {
            if (hasAuthority)
            {
                // this component must read the data that the server wrote, even if it ignores it.
                // otherwise the NetworkReader stream will still contain that data for the next component.

                // position
                reader.ReadVector3();

                // velocity
                reader.ReadVector3();

                if (syncRotationAxis != AxisSyncMode.None)
                {
                    UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }
                if (syncSpin)
                {
                    UnserializeSpin3D(reader, syncRotationAxis, rotationSyncCompression);
                }
                return;
            }

            if (isServer && m_ClientMoveCallback3D != null)
            {
                var pos = reader.ReadVector3();
                var vel = reader.ReadVector3();
                Quaternion rot = Quaternion.identity;
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    rot = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }

                if (m_ClientMoveCallback3D(ref pos, ref vel, ref rot))
                {
                    m_TargetSyncPosition = pos;
                    m_TargetSyncVelocity = vel;
                    if (syncRotationAxis != AxisSyncMode.None)
                    {
                        m_TargetSyncRotation3D = rot;
                    }
                }
                else
                {
                    // rejected by callback
                    return;
                }
            }
            else
            {
                // position
                m_TargetSyncPosition = reader.ReadVector3();

                // velocity
                m_TargetSyncVelocity = reader.ReadVector3();

                // rotation
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    m_TargetSyncRotation3D = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }
            }
            // spin
            if (syncSpin)
            {
                m_TargetSyncAngularVelocity3D = UnserializeSpin3D(reader, syncRotationAxis, rotationSyncCompression);
            }

            if (m_RigidBody3D == null)
                return;

            if (isServer && !isClient)
            {
                // dedicated server needs to apply immediately, there is no interpolation
                m_RigidBody3D.MovePosition(m_TargetSyncPosition);
                m_RigidBody3D.MoveRotation(m_TargetSyncRotation3D);
                m_RigidBody3D.velocity = m_TargetSyncVelocity;
                return;
            }

            // handle zero send rate
            if (GetNetworkSendInterval() == 0)
            {
                m_RigidBody3D.MovePosition(m_TargetSyncPosition);
                m_RigidBody3D.velocity = m_TargetSyncVelocity;
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    m_RigidBody3D.MoveRotation(m_TargetSyncRotation3D);
                }
                if (syncSpin)
                {
                    m_RigidBody3D.angularVelocity = m_TargetSyncAngularVelocity3D;
                }
                return;
            }

            // handle position snap threshold
            float dist = (m_RigidBody3D.position - m_TargetSyncPosition).magnitude;
            if (dist > snapThreshold)
            {
                m_RigidBody3D.position = m_TargetSyncPosition;
                m_RigidBody3D.velocity = m_TargetSyncVelocity;
            }

            // handle no rotation interpolation
            if (interpolateRotation == 0 && syncRotationAxis != AxisSyncMode.None)
            {
                m_RigidBody3D.rotation = m_TargetSyncRotation3D;
                if (syncSpin)
                {
                    m_RigidBody3D.angularVelocity = m_TargetSyncAngularVelocity3D;
                }
            }

            // handle no movement interpolation
            if (m_InterpolateMovement == 0)
            {
                m_RigidBody3D.position = m_TargetSyncPosition;
            }

            if (initialState && syncRotationAxis != AxisSyncMode.None)
            {
                m_RigidBody3D.rotation = m_TargetSyncRotation3D;
            }
        }

        void UnserializeMode2D(NetworkReader reader, bool initialState)
        {
            if (hasAuthority)
            {
                // this component must read the data that the server wrote, even if it ignores it.
                // otherwise the NetworkReader stream will still contain that data for the next component.

                // position
                reader.ReadVector2();

                // velocity
                reader.ReadVector2();

                if (syncRotationAxis != AxisSyncMode.None)
                {
                    UnserializeRotation2D(reader, rotationSyncCompression);
                }

                if (syncSpin)
                {
                    UnserializeSpin2D(reader, rotationSyncCompression);
                }
                return;
            }

            if (m_RigidBody2D == null)
                return;

            if (isServer && m_ClientMoveCallback2D != null)
            {
                Vector2 pos = reader.ReadVector2();
                Vector2 vel = reader.ReadVector2();
                float rot = 0;
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    rot = UnserializeRotation2D(reader, rotationSyncCompression);
                }

                if (m_ClientMoveCallback2D(ref pos, ref vel, ref rot))
                {
                    m_TargetSyncPosition = pos;
                    m_TargetSyncVelocity = vel;
                    if (syncRotationAxis != AxisSyncMode.None)
                    {
                        m_TargetSyncRotation2D = rot;
                    }
                }
                else
                {
                    // rejected by callback
                    return;
                }
            }
            else
            {
                // position
                m_TargetSyncPosition = reader.ReadVector2();

                // velocity
                m_TargetSyncVelocity = reader.ReadVector2();

                // rotation
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    m_TargetSyncRotation2D = UnserializeRotation2D(reader, rotationSyncCompression);
                }
            }

            // spin
            if (syncSpin)
            {
                m_TargetSyncAngularVelocity2D = UnserializeSpin2D(reader, rotationSyncCompression);
            }

            if (isServer && !isClient)
            {
                // dedicated server needs to apply immediately, there is no interpolation
                transform.position = m_TargetSyncPosition;
                m_RigidBody2D.MoveRotation(m_TargetSyncRotation2D);
                m_RigidBody2D.velocity = m_TargetSyncVelocity;
                return;
            }

            // handle zero send rate
            if (GetNetworkSendInterval() == 0)
            {
                // NOTE: cannot use m_RigidBody2D.MovePosition() and set velocity in the same frame, so use transform.position
                transform.position = m_TargetSyncPosition;
                m_RigidBody2D.velocity = m_TargetSyncVelocity;
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    m_RigidBody2D.MoveRotation(m_TargetSyncRotation2D);
                }
                if (syncSpin)
                {
                    m_RigidBody2D.angularVelocity = m_TargetSyncAngularVelocity2D;
                }
                return;
            }

            // handle position snap threshold
            float dist = (m_RigidBody2D.position - (Vector2)m_TargetSyncPosition).magnitude;
            if (dist > snapThreshold)
            {
                m_RigidBody2D.position = m_TargetSyncPosition;
                m_RigidBody2D.velocity = m_TargetSyncVelocity;
            }

            // handle no rotation interpolation
            if (interpolateRotation == 0 && syncRotationAxis != AxisSyncMode.None)
            {
                m_RigidBody2D.rotation = m_TargetSyncRotation2D;
                if (syncSpin)
                {
                    m_RigidBody2D.angularVelocity = m_TargetSyncAngularVelocity2D;
                }
            }

            // handle no movement interpolation
            if (m_InterpolateMovement == 0)
            {
                m_RigidBody2D.position = m_TargetSyncPosition;
            }

            if (initialState)
            {
                m_RigidBody2D.rotation = m_TargetSyncRotation2D;
            }
        }

        void UnserializeModeCharacterController(NetworkReader reader, bool initialState)
        {
            if (hasAuthority)
            {
                // this component must read the data that the server wrote, even if it ignores it.
                // otherwise the NetworkReader stream will still contain that data for the next component.

                // position
                reader.ReadVector3();

                if (syncRotationAxis != AxisSyncMode.None)
                {
                    UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }
                return;
            }

            if (isServer && m_ClientMoveCallback3D != null)
            {
                var pos = reader.ReadVector3();
                Quaternion rot = Quaternion.identity;
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    rot = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }

                if (m_CharacterController == null)
                    return;

                // no velocity in packet, use current local velocity
                var vel = m_CharacterController.velocity;

                if (m_ClientMoveCallback3D(ref pos, ref vel, ref rot))
                {
                    m_TargetSyncPosition = pos;
                    m_TargetSyncVelocity = vel;
                    if (syncRotationAxis != AxisSyncMode.None)
                    {
                        m_TargetSyncRotation3D = rot;
                    }
                }
                else
                {
                    // rejected by callback
                    return;
                }
            }
            else
            {
                // position
                m_TargetSyncPosition = reader.ReadVector3();

                // no velocity

                // rotation
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    m_TargetSyncRotation3D = UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }

                // no spin
            }

            if (m_CharacterController == null)
                return;

            // total distance away the target position is
            var totalDistToTarget = (m_TargetSyncPosition - transform.position); // 5 units
            var perSecondDist = totalDistToTarget / GetNetworkSendInterval();
            m_FixedPosDiff = perSecondDist * Time.fixedDeltaTime;

            if (isServer && !isClient)
            {
                // dedicated server needs to apply immediately, there is no interpolation
                transform.position = m_TargetSyncPosition;
                transform.rotation = m_TargetSyncRotation3D;
                return;
            }

            // handle zero send rate
            if (GetNetworkSendInterval() == 0)
            {
                transform.position = m_TargetSyncPosition;
                //m_RigidBody3D.velocity = m_TargetSyncVelocity;
                if (syncRotationAxis != AxisSyncMode.None)
                {
                    transform.rotation = m_TargetSyncRotation3D;
                }
                return;
            }

            // handle position snap threshold
            float dist = (transform.position - m_TargetSyncPosition).magnitude;
            if (dist > snapThreshold)
            {
                transform.position = m_TargetSyncPosition;
            }

            // handle no rotation interpolation
            if (interpolateRotation == 0 && syncRotationAxis != AxisSyncMode.None)
            {
                transform.rotation = m_TargetSyncRotation3D;
            }

            // handle no movement interpolation
            if (m_InterpolateMovement == 0)
            {
                transform.position = m_TargetSyncPosition;
            }

            if (initialState && syncRotationAxis != AxisSyncMode.None)
            {
                transform.rotation = m_TargetSyncRotation3D;
            }
        }

        void FixedUpdate()
        {
            if (isServer)
            {
                FixedUpdateServer();
            }
            if (isClient)
            {
                FixedUpdateClient();
            }
        }

        void FixedUpdateServer()
        {
            if (syncVarDirtyBits != 0)
                return;

            // dont run if network isn't active
            if (!NetworkServer.active)
                return;

            // dont run if we haven't been spawned yet
            if (!isServer)
                return;

            // dont' auto-dirty if no send interval
            if (GetNetworkSendInterval() == 0)
                return;

            float distance = (transform.position - m_PrevPosition).magnitude;
            if (distance < movementTheshold)
            {
                distance = Quaternion.Angle(m_PrevRotation, transform.rotation);
                if (distance < movementTheshold)
                {
                    if (!CheckVelocityChanged())
                    {
                        return;
                    }
                }
            }

            // This will cause transform to be sent
            SetDirtyBit(1);
        }

        bool CheckVelocityChanged()
        {
            switch (transformSyncMode)
            {
                case TransformSyncMode.SyncRigidbody2D:
                    if (m_RigidBody2D && m_VelocityThreshold > 0)
                    {
                        return Mathf.Abs(m_RigidBody2D.velocity.sqrMagnitude - m_PrevVelocity) >= m_VelocityThreshold;
                    }
                    else
                    {
                        return false;
                    }

                case TransformSyncMode.SyncRigidbody3D:
                    if (m_RigidBody3D && m_VelocityThreshold > 0)
                    {
                        return Mathf.Abs(m_RigidBody3D.velocity.sqrMagnitude - m_PrevVelocity) >= m_VelocityThreshold;
                    }
                    else
                    {
                        return false;
                    }

                default:
                    return false;
            }
        }

        void FixedUpdateClient()
        {
            // dont run if we haven't received any sync data
            if (m_LastClientSyncTime == 0)
                return;

            // dont run if network isn't active
            if (!NetworkServer.active && !NetworkClient.active)
                return;

            // dont run if we haven't been spawned yet
            if (!isServer && !isClient)
                return;

            // dont run if not expecting continuous updates
            if (GetNetworkSendInterval() == 0)
                return;

            // dont run this if this client has authority over this player object
            if (hasAuthority)
                return;

            // interpolate on client
            switch (transformSyncMode)
            {
                case TransformSyncMode.SyncNone:
                {
                    return;
                }
                case TransformSyncMode.SyncTransform:
                {
                    return;
                }
                case TransformSyncMode.SyncRigidbody3D:
                {
                    InterpolateTransformMode3D();
                    break;
                }
                case TransformSyncMode.SyncRigidbody2D:
                {
                    InterpolateTransformMode2D();
                    break;
                }

                case TransformSyncMode.SyncCharacterController:
                {
                    InterpolateTransformModeCharacterController();
                    break;
                }
            }
        }

        void InterpolateTransformMode3D()
        {
            if (m_InterpolateMovement != 0)
            {
                Vector3 newVelocity = (m_TargetSyncPosition - m_RigidBody3D.position) * m_InterpolateMovement / GetNetworkSendInterval();
                m_RigidBody3D.velocity = newVelocity;
            }

            if (interpolateRotation != 0)
            {
                m_RigidBody3D.MoveRotation(Quaternion.Slerp(
                    m_RigidBody3D.rotation,
                    m_TargetSyncRotation3D,
                    Time.fixedDeltaTime * interpolateRotation));

                //m_TargetSyncRotation3D *= Quaternion.Euler(m_TargetSyncAngularVelocity3D * Time.fixedDeltaTime);

                // move sync rotation slightly in rotation direction
                //m_TargetSyncRotation3D += (m_TargetSyncAngularVelocity3D * Time.fixedDeltaTime * moveAheadRatio);
            }

            // move sync position slightly in the position of velocity
            m_TargetSyncPosition += (m_TargetSyncVelocity * Time.fixedDeltaTime * k_MoveAheadRatio);
        }

        void InterpolateTransformModeCharacterController()
        {
            if (m_FixedPosDiff == Vector3.zero && m_TargetSyncRotation3D == transform.rotation)
                return;

            if (m_InterpolateMovement != 0)
            {
                m_CharacterController.Move(m_FixedPosDiff * m_InterpolateMovement);
            }

            if (interpolateRotation != 0)
            {
                transform.rotation = Quaternion.Slerp(
                    transform.rotation,
                    m_TargetSyncRotation3D,
                    Time.fixedDeltaTime * interpolateRotation * 10);
            }
            if (Time.time - m_LastClientSyncTime > GetNetworkSendInterval())
            {
                // turn off interpolation if we go out of the time window for a new packet
                m_FixedPosDiff = Vector3.zero;

                var diff = m_TargetSyncPosition - transform.position;
                m_CharacterController.Move(diff);
            }
        }

        void InterpolateTransformMode2D()
        {
            if (m_InterpolateMovement != 0)
            {
                Vector2 oldVelocity = m_RigidBody2D.velocity;
                Vector2 newVelocity = (((Vector2)m_TargetSyncPosition - m_RigidBody2D.position)) * m_InterpolateMovement / GetNetworkSendInterval();
                if (!m_Grounded && newVelocity.y < 0)
                {
                    newVelocity.y = oldVelocity.y;
                }
                m_RigidBody2D.velocity = newVelocity;
            }

            if (interpolateRotation != 0)
            {
                float orientation = m_RigidBody2D.rotation % 360;
                if (orientation < 0)
                {
                    orientation += 360;
                }

                Quaternion newRotation = Quaternion.Slerp(
                    transform.rotation,
                    Quaternion.Euler(0, 0, m_TargetSyncRotation2D),
                    Time.fixedDeltaTime * interpolateRotation / GetNetworkSendInterval());

                m_RigidBody2D.MoveRotation(newRotation.eulerAngles.z);

                // move sync rotation slightly in rotation direction
                m_TargetSyncRotation2D += (m_TargetSyncAngularVelocity2D * Time.fixedDeltaTime * k_MoveAheadRatio);
            }

            // move sync position slightly in the position of velocity
            m_TargetSyncPosition += (m_TargetSyncVelocity * Time.fixedDeltaTime * k_MoveAheadRatio);
        }

        // --------------------- local transform sync  ------------------------

        void Update()
        {
            if (!hasAuthority)
                return;

            if (!localPlayerAuthority)
                return;

            if (NetworkServer.active)
                return;

            if (Time.time - m_LastClientSendTime > GetNetworkSendInterval())
            {
                SendTransform();
                m_LastClientSendTime = Time.time;
            }
        }

        bool HasMoved()
        {
            float diff = 0;

            // check if position has changed
            if (m_RigidBody3D != null)
            {
                diff = (m_RigidBody3D.position - m_PrevPosition).magnitude;
            }
            else if (m_RigidBody2D != null)
            {
                diff = (m_RigidBody2D.position - (Vector2)m_PrevPosition).magnitude;
            }
            else
            {
                diff = (transform.position - m_PrevPosition).magnitude;
            }

            if (diff > k_LocalMovementThreshold)
            {
                return true;
            }

            // check if rotation has changed
            if (m_RigidBody3D != null)
            {
                diff = Quaternion.Angle(m_RigidBody3D.rotation, m_PrevRotation);
            }
            else if (m_RigidBody2D != null)
            {
                diff = Math.Abs(m_RigidBody2D.rotation - m_PrevRotation2D);
            }
            else
            {
                diff = Quaternion.Angle(transform.rotation, m_PrevRotation);
            }
            if (diff > k_LocalRotationThreshold)
            {
                return true;
            }

            // check if velocty has changed
            if (m_RigidBody3D != null)
            {
                diff = Mathf.Abs(m_RigidBody3D.velocity.sqrMagnitude - m_PrevVelocity);
            }
            else if (m_RigidBody2D != null)
            {
                diff = Mathf.Abs(m_RigidBody2D.velocity.sqrMagnitude - m_PrevVelocity);
            }
            if (diff > k_LocalVelocityThreshold)
            {
                return true;
            }


            return false;
        }

        [Client]
        void SendTransform()
        {
            if (!HasMoved() || ClientScene.readyConnection == null)
            {
                return;
            }

            m_LocalTransformWriter.StartMessage(MsgType.LocalPlayerTransform);
            m_LocalTransformWriter.Write(netId);

            switch (transformSyncMode)
            {
                case TransformSyncMode.SyncNone:
                {
                    return;
                }
                case TransformSyncMode.SyncTransform:
                {
                    SerializeModeTransform(m_LocalTransformWriter);
                    break;
                }
                case TransformSyncMode.SyncRigidbody3D:
                {
                    SerializeMode3D(m_LocalTransformWriter);
                    break;
                }
                case TransformSyncMode.SyncRigidbody2D:
                {
                    SerializeMode2D(m_LocalTransformWriter);
                    break;
                }
                case TransformSyncMode.SyncCharacterController:
                {
                    SerializeModeCharacterController(m_LocalTransformWriter);
                    break;
                }
            }

            if (m_RigidBody3D != null)
            {
                m_PrevPosition = m_RigidBody3D.position;
                m_PrevRotation = m_RigidBody3D.rotation;
                m_PrevVelocity = m_RigidBody3D.velocity.sqrMagnitude;
            }
            else if (m_RigidBody2D != null)
            {
                m_PrevPosition = m_RigidBody2D.position;
                m_PrevRotation2D = m_RigidBody2D.rotation;
                m_PrevVelocity = m_RigidBody2D.velocity.sqrMagnitude;
            }
            else
            {
                m_PrevPosition = transform.position;
                m_PrevRotation = transform.rotation;
            }

            m_LocalTransformWriter.FinishMessage();

#if UNITY_EDITOR
            Profiler.IncrementStatOutgoing(MsgType.LocalPlayerTransform, "6:LocalPlayerTransform");
#endif
            ClientScene.readyConnection.SendWriter(m_LocalTransformWriter, GetNetworkChannel());
        }

        static public void HandleTransform(NetworkMessage netMsg)
        {
            NetworkInstanceId netId = netMsg.reader.ReadNetworkId();

#if UNITY_EDITOR
            Profiler.IncrementStatIncoming(MsgType.LocalPlayerTransform, "6:LocalPlayerTransform");
#endif

            GameObject foundObj = NetworkServer.FindLocalObject(netId);
            if (foundObj == null)
            {
                if (LogFilter.logError) { Debug.LogError("Received NetworkTransform data for GameObject that doesn't exist"); }
                return;
            }
            NetworkTransform foundSync = foundObj.GetComponent<NetworkTransform>();
            if (foundSync == null)
            {
                if (LogFilter.logError) { Debug.LogError("HandleTransform null target"); }
                return;
            }
            if (!foundSync.localPlayerAuthority)
            {
                if (LogFilter.logError) { Debug.LogError("HandleTransform no localPlayerAuthority"); }
                return;
            }
            if (netMsg.conn.clientOwnedObjects == null)
            {
                if (LogFilter.logError) { Debug.LogError("HandleTransform object not owned by connection"); }
                return;
            }

            if (netMsg.conn.clientOwnedObjects.Contains(netId))
            {
                switch (foundSync.transformSyncMode)
                {
                    case TransformSyncMode.SyncNone:
                    {
                        return;
                    }
                    case TransformSyncMode.SyncTransform:
                    {
                        foundSync.UnserializeModeTransform(netMsg.reader, false);
                        break;
                    }
                    case TransformSyncMode.SyncRigidbody3D:
                    {
                        foundSync.UnserializeMode3D(netMsg.reader, false);
                        break;
                    }
                    case TransformSyncMode.SyncRigidbody2D:
                    {
                        foundSync.UnserializeMode2D(netMsg.reader, false);
                        break;
                    }
                    case TransformSyncMode.SyncCharacterController:
                    {
                        foundSync.UnserializeModeCharacterController(netMsg.reader, false);
                        break;
                    }
                }
                foundSync.m_LastClientSyncTime = Time.time;
                return;
            }

            if (LogFilter.logWarn) { Debug.LogWarning("HandleTransform netId:" + netId + " is not for a valid player"); }
        }

        // --------------------- Compression Helper functions ------------------------

        static void WriteAngle(NetworkWriter writer, float angle, CompressionSyncMode compression)
        {
            switch (compression)
            {
                case CompressionSyncMode.None:
                {
                    writer.Write(angle);
                    break;
                }
                case CompressionSyncMode.Low:
                {
                    writer.Write((short)angle);
                    break;
                }
                case CompressionSyncMode.High:
                {
                    //TODO
                    writer.Write((short)angle);
                    break;
                }
            }
        }

        static float ReadAngle(NetworkReader reader, CompressionSyncMode compression)
        {
            switch (compression)
            {
                case CompressionSyncMode.None:
                {
                    return reader.ReadSingle();
                }
                case CompressionSyncMode.Low:
                {
                    return reader.ReadInt16();
                }
                case CompressionSyncMode.High:
                {
                    //TODO
                    return reader.ReadInt16();
                }
            }
            return 0;
        }

        // --------------------- Serialization Helper functions ------------------------

        static public void SerializeVelocity3D(NetworkWriter writer, Vector3 velocity, CompressionSyncMode compression)
        {
            writer.Write(velocity);
        }

        static public void SerializeVelocity2D(NetworkWriter writer, Vector2 velocity, CompressionSyncMode compression)
        {
            writer.Write(velocity);
        }

        static public void SerializeRotation3D(NetworkWriter writer, Quaternion rot, AxisSyncMode mode, CompressionSyncMode compression)
        {
            switch (mode)
            {
                case AxisSyncMode.None:
                    break;

                case AxisSyncMode.AxisX:
                    WriteAngle(writer, rot.eulerAngles.x, compression);
                    break;

                case AxisSyncMode.AxisY:
                    WriteAngle(writer, rot.eulerAngles.y, compression);
                    break;

                case AxisSyncMode.AxisZ:
                    WriteAngle(writer, rot.eulerAngles.z, compression);
                    break;

                case AxisSyncMode.AxisXY:
                    WriteAngle(writer, rot.eulerAngles.x, compression);
                    WriteAngle(writer, rot.eulerAngles.y, compression);
                    break;

                case AxisSyncMode.AxisXZ:
                    WriteAngle(writer, rot.eulerAngles.x, compression);
                    WriteAngle(writer, rot.eulerAngles.z, compression);
                    break;

                case AxisSyncMode.AxisYZ:
                    WriteAngle(writer, rot.eulerAngles.y, compression);
                    WriteAngle(writer, rot.eulerAngles.z, compression);
                    break;

                case AxisSyncMode.AxisXYZ:
                    WriteAngle(writer, rot.eulerAngles.x, compression);
                    WriteAngle(writer, rot.eulerAngles.y, compression);
                    WriteAngle(writer, rot.eulerAngles.z, compression);
                    break;
            }
        }

        static public void SerializeRotation2D(NetworkWriter writer, float rot, CompressionSyncMode compression)
        {
            WriteAngle(writer, rot, compression);
        }

        static public void SerializeSpin3D(NetworkWriter writer, Vector3 angularVelocity, AxisSyncMode mode, CompressionSyncMode compression)
        {
            switch (mode)
            {
                case AxisSyncMode.None:
                    break;

                case AxisSyncMode.AxisX:
                    WriteAngle(writer, angularVelocity.x, compression);
                    break;

                case AxisSyncMode.AxisY:
                    WriteAngle(writer, angularVelocity.y, compression);
                    break;

                case AxisSyncMode.AxisZ:
                    WriteAngle(writer, angularVelocity.z, compression);
                    break;

                case AxisSyncMode.AxisXY:
                    WriteAngle(writer, angularVelocity.x, compression);
                    WriteAngle(writer, angularVelocity.y, compression);
                    break;

                case AxisSyncMode.AxisXZ:
                    WriteAngle(writer, angularVelocity.x, compression);
                    WriteAngle(writer, angularVelocity.z, compression);
                    break;

                case AxisSyncMode.AxisYZ:
                    WriteAngle(writer, angularVelocity.y, compression);
                    WriteAngle(writer, angularVelocity.z, compression);
                    break;

                case AxisSyncMode.AxisXYZ:
                    WriteAngle(writer, angularVelocity.x, compression);
                    WriteAngle(writer, angularVelocity.y, compression);
                    WriteAngle(writer, angularVelocity.z, compression);
                    break;
            }
        }

        static public void SerializeSpin2D(NetworkWriter writer, float angularVelocity, CompressionSyncMode compression)
        {
            WriteAngle(writer, angularVelocity, compression);
        }

        static public Vector3 UnserializeVelocity3D(NetworkReader reader, CompressionSyncMode compression)
        {
            return reader.ReadVector3();
        }

        static public Vector3 UnserializeVelocity2D(NetworkReader reader, CompressionSyncMode compression)
        {
            return reader.ReadVector2();
        }

        static public Quaternion UnserializeRotation3D(NetworkReader reader, AxisSyncMode mode, CompressionSyncMode compression)
        {
            Quaternion rotation = Quaternion.identity;
            Vector3 rotv = Vector3.zero;

            switch (mode)
            {
                case AxisSyncMode.None:
                    break;

                case AxisSyncMode.AxisX:
                    rotv.Set(ReadAngle(reader, compression), 0, 0);
                    rotation.eulerAngles = rotv;
                    break;

                case AxisSyncMode.AxisY:
                    rotv.Set(0, ReadAngle(reader, compression), 0);
                    rotation.eulerAngles = rotv;
                    break;

                case AxisSyncMode.AxisZ:
                    rotv.Set(0, 0, ReadAngle(reader, compression));
                    rotation.eulerAngles = rotv;
                    break;

                case AxisSyncMode.AxisXY:
                    rotv.Set(ReadAngle(reader, compression), ReadAngle(reader, compression), 0);
                    rotation.eulerAngles = rotv;
                    break;

                case AxisSyncMode.AxisXZ:
                    rotv.Set(ReadAngle(reader, compression), 0, ReadAngle(reader, compression));
                    rotation.eulerAngles = rotv;
                    break;

                case AxisSyncMode.AxisYZ:
                    rotv.Set(0, ReadAngle(reader, compression), ReadAngle(reader, compression));
                    rotation.eulerAngles = rotv;
                    break;

                case AxisSyncMode.AxisXYZ:
                    rotv.Set(ReadAngle(reader, compression), ReadAngle(reader, compression), ReadAngle(reader, compression));
                    rotation.eulerAngles = rotv;
                    break;
            }
            return rotation;
        }

        static public float UnserializeRotation2D(NetworkReader reader, CompressionSyncMode compression)
        {
            return ReadAngle(reader, compression);
        }

        static public Vector3 UnserializeSpin3D(NetworkReader reader, AxisSyncMode mode, CompressionSyncMode compression)
        {
            Vector3 spin = Vector3.zero;
            switch (mode)
            {
                case AxisSyncMode.None:
                    break;

                case AxisSyncMode.AxisX:
                    spin.Set(ReadAngle(reader, compression), 0, 0);
                    break;

                case AxisSyncMode.AxisY:
                    spin.Set(0, ReadAngle(reader, compression), 0);
                    break;

                case AxisSyncMode.AxisZ:
                    spin.Set(0, 0, ReadAngle(reader, compression));
                    break;

                case AxisSyncMode.AxisXY:
                    spin.Set(ReadAngle(reader, compression), ReadAngle(reader, compression), 0);
                    break;

                case AxisSyncMode.AxisXZ:
                    spin.Set(ReadAngle(reader, compression), 0, ReadAngle(reader, compression));
                    break;

                case AxisSyncMode.AxisYZ:
                    spin.Set(0, ReadAngle(reader, compression), ReadAngle(reader, compression));
                    break;

                case AxisSyncMode.AxisXYZ:
                    spin.Set(ReadAngle(reader, compression), ReadAngle(reader, compression), ReadAngle(reader, compression));
                    break;
            }
            return spin;
        }

        static public float UnserializeSpin2D(NetworkReader reader, CompressionSyncMode compression)
        {
            return ReadAngle(reader, compression);
        }

        public override int GetNetworkChannel()
        {
            return Channels.DefaultUnreliable;
        }

        public override float GetNetworkSendInterval()
        {
            return m_SendInterval;
        }

        public override void OnStartAuthority()
        {
            // must reset this timer, or the server will continue to send target position instead of current position
            m_LastClientSyncTime = 0;
        }
    }
}