Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.Networking;
- namespace AnySync.Examples
- {
- /// <summary>
- /// Basic example using the easiest possible techniques.
- /// Some best practices are ignored in favor of shorter code.
- /// </summary>
- public class UNetRigidbody2DSync : NetworkBehaviour
- {
- // Up to 10 messages per second.
- private const float MinimumSendInterval = 0.1f;
- private const float CharacterSpeed = 3f;
- private const float JumpVelocity = 7f;
- private readonly MotionGenerator _motionGenerator = new MotionGenerator();
- private float _timeSinceLastSync;
- private void Update()
- {
- if (hasAuthority)
- {
- // Local movement.
- var rigidbody2DComponent = GetComponent<Rigidbody2D>();
- // Get original velocity.
- var rigidbody2DVelocity = rigidbody2DComponent.velocity;
- // Modify velocity according to input.
- rigidbody2DVelocity.x = Input.GetAxisRaw("Horizontal") * CharacterSpeed;
- if (Input.GetButtonDown("Jump"))
- rigidbody2DVelocity.y = JumpVelocity;
- // Apply velocity change.
- rigidbody2DComponent.velocity = rigidbody2DVelocity;
- // Sync position.
- _timeSinceLastSync += Time.deltaTime;
- if (_timeSinceLastSync >= MinimumSendInterval)
- {
- CmdSync(_timeSinceLastSync, transform.position);
- _timeSinceLastSync = 0f;
- }
- }
- else
- {
- // Proxy movement.
- // Avoid warnings if syncBuffer is empty.
- if (_motionGenerator.HasKeyframes)
- {
- // Update playback and apply new position.
- _motionGenerator.UpdatePlayback(Time.deltaTime);
- transform.position = _motionGenerator.Position;
- }
- }
- }
- [Command]
- private void CmdSync(float interpolationTime, Vector2 position)
- {
- // Add keyframe to buffer on server.
- _motionGenerator.AddKeyframe(interpolationTime, position);
- // Send it to other clients.
- RpcSync(interpolationTime, position);
- }
- [ClientRpc]
- private void RpcSync(float interpolationTime, Vector2 position)
- {
- // Prevent receiving keyframes on owner client and host.
- if (isLocalPlayer || isServer)
- return;
- // Add keyframe to buffer on clients.
- _motionGenerator.AddKeyframe(interpolationTime, position);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement