Hello!
I made a rigidbody character controller and i am trying to sync it over the network but its not working, the player is on a different position on one game then the other.
Player controller
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
public float speed = 10.0f;
public float gravity = 10.0f;
public float maxVelocityChange = 10.0f;
public bool canJump = true;
public float jumpHeight = 2.0f;
public bool grounded = false;
public float smoothing = 2;
void Awake ()
{
rigidbody.freezeRotation = true;
rigidbody.useGravity = false;
}
void Start()
{
Screen.lockCursor = true;
}
void FixedUpdate ()
{
if (grounded)
{
Vector3 targetVelocity = new Vector3(Input.GetAxisRaw("Mouse X"), 0, Input.GetAxisRaw("Mouse Y"));
targetVelocity = transform.TransformDirection(targetVelocity);
targetVelocity *= speed / smoothing;
Vector3 velocity = rigidbody.velocity;
Vector3 velocityChange = (targetVelocity - velocity);
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
if (canJump && Input.GetButton("Jump"))
{
rigidbody.velocity = new Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z);
}
}
rigidbody.AddForce(new Vector3 (0, -gravity * rigidbody.mass, 0));
grounded = false;
}
void OnCollisionStay ()
{
grounded = true;
}
float CalculateJumpVerticalSpeed ()
{
return Mathf.Sqrt(2 * jumpHeight * gravity);
}
}
Network Player
using UnityEngine;
using System.Collections;
public class NetworkedPlayer : MonoBehaviour
{
private PhotonView photonView;
void Awake()
{
photonView = GetComponent<PhotonView>();
}
void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.isWriting)
{
//We own this player: send the others our data
stream.SendNext(transform.position);
stream.SendNext(transform.rotation);
}
else
{
//Network player, receive data
correctPlayerPos = (Vector3)stream.ReceiveNext();
correctPlayerRot = (Quaternion)stream.ReceiveNext();
}
}
private Vector3 correctPlayerPos = Vector3.zero; //We lerp towards this
private Quaternion correctPlayerRot = Quaternion.identity; //We lerp towards this
void Update()
{
if (!photonView.isMine)
{
//Update remote player (smooth this, this looks good, at the cost of some accuracy)
transform.position = Vector3.Lerp(transform.position, correctPlayerPos, Time.deltaTime * 5);
transform.rotation = Quaternion.Lerp(transform.rotation, correctPlayerRot, Time.deltaTime * 5);
}
}
}