Created
January 24, 2016 15:49
-
-
Save NVentimiglia/126d97f5454168dadd05 to your computer and use it in GitHub Desktop.
Butter smooth Unity3D Sync Transform
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SyncTransform : SyncComponenent | |
{ | |
/// <summary> | |
/// Sync Update order | |
/// </summary> | |
public int UpdateOrder = 0; | |
[Range(0, 2)] | |
public float Smoothness = 1f; | |
public bool Rotation = true; | |
public bool Position = true; | |
protected Vector3 targPos; | |
protected Vector3 targRot; | |
protected Vector3 velRot; | |
protected Vector3 velPos; | |
public override void OnNetworkAwake(SyncEntity entity) | |
{ | |
// register for updates | |
Entity.RegisterUpdate(UpdateOrder, OnUpdate); | |
//enable only on non-local entities | |
enabled = !entity.IsMine; | |
//Good policy to disable bodies if networking | |
var rigidBody = GetComponent<Rigidbody>(); | |
if (rigidBody) | |
rigidBody.isKinematic = !entity.IsMine; | |
var rigidBody2D = GetComponent<Rigidbody2D>(); | |
if (rigidBody2D) | |
rigidBody2D.isKinematic = !entity.IsMine; | |
} | |
/// <summary> | |
/// Network Update | |
/// </summary> | |
/// <param name="stream"></param> | |
void OnUpdate(SyncUpdate stream) | |
{ | |
if (stream.IsWrite) | |
{ | |
//Is Mine | |
if (Position) | |
stream.Write(transform.localPosition); | |
if (Rotation) | |
stream.Write(transform.rotation.eulerAngles); | |
} | |
else | |
{ | |
//Is Remote | |
if (Position) | |
targPos = stream.Read<Vector3>(); | |
if (Rotation) | |
targRot = stream.Read<Vector3>(); | |
} | |
} | |
/// <summary> | |
/// Updates the position on remote clients | |
/// </summary> | |
void Update() | |
{ | |
if (Position) | |
{ | |
transform.position = Vector3.SmoothDamp(transform.position, targPos, ref velPos,Entity.UpdateRate * Smoothness); | |
} | |
if (Rotation) | |
{ | |
var r = Vector3.SmoothDamp(transform.rotation.eulerAngles, targRot, ref velRot,Entity.UpdateRate * Smoothness); | |
transform.rotation = Quaternion.Euler(r); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment