using UnityEngine;
using TNet;
public class PlayerInput : TNBehaviour {
public enum CharacterState {
idle,
walking
}
public CharacterState _state;
public string idleAnimName;
public string walkAnimName;
public int turnSpeed;
public int moveSpeed;
private float h;
private float v;
void Start() {
animation.wrapMode = WrapMode.Loop;
if (!tno.isMine) {
GetComponentInChildren<Camera>().enabled = false; // disable the camera of the non-owned Player;
GetComponentInChildren<AudioListener>().enabled = false; // Disables AudioListener of non-owned Player - prevents multiple AudioListeners from being present in scene.
}
}
void FixedUpdate() {
if (tno.isMine)
{
InputMovement();
CheckKey();
} else {
SyncedMovement();
}
if (!tno.isMine)
{
tno.Send("InputMovement", Target.OthersSaved, h, v);
}
}
[RFC]
void InputMovement() {
h = Input.GetAxis("Horizontal");
v = Input.GetAxis("Vertical");
transform.Rotate( 0, h * turnSpeed * Time.deltaTime, 0 );
Vector3 moveAmount = transform.forward * v * moveSpeed;
rigidbody.MovePosition( transform.position + moveAmount * Time.deltaTime );
rigidbody
.velocity = moveAmount
+ Vector3
.Scale(rigidbody
.velocity,
new Vector3
(0,
1,
0)); }
void CheckKey()
{
if(Input.GetKeyDown(KeyCode.W)) {
_state = CharacterState.walking;
} else if (Input.GetKeyUp(KeyCode.W)) {
_state = CharacterState.idle;
}
SyncAnimation();
}
void PlayAnimation() {
tno.SendQuickly("SyncAnimation",TNet.Target.AllSaved, _state);
}
//[RFC]
void SyncAnimation() {
switch(_state)
{
case CharacterState.idle:
animation.CrossFade(idleAnimName);
break;
case CharacterState.walking:
animation.CrossFade(walkAnimName);
break;
}
}
private float lastSynchronizationTime = 0f;
private float syncDelay = 0f;
private float syncTime = 0f;
private Vector3 syncStartPosition = Vector3.zero;
private Vector3 syncEndPosition = Vector3.zero;
private void SyncedMovement() {
syncTime += Time.deltaTime;
rigidbody.position = Vector3.Lerp(syncStartPosition, syncEndPosition, syncTime / syncDelay);
}
void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info) {
Vector3 syncPosition = Vector3.zero;
Vector3 syncVelocity = Vector3.zero;
Quaternion syncRotation = Quaternion.Euler(0,0,0);
if (stream.isWriting)
{
syncPosition = rigidbody.position;
stream.Serialize(ref syncPosition);
syncVelocity = rigidbody.velocity;
stream.Serialize(ref syncVelocity);
syncRotation = transform.rotation;
stream.Serialize(ref syncRotation);
}
else
{
stream.Serialize(ref syncPosition);
stream.Serialize(ref syncVelocity);
syncTime = 0f;
syncDelay = Time.time - lastSynchronizationTime;
lastSynchronizationTime = Time.time;
syncEndPosition = syncPosition + syncVelocity * syncDelay;
syncStartPosition = rigidbody.position;
stream.Serialize(ref syncRotation);
transform.rotation = syncRotation;
}
}
}