Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class RigWalker : MonoBehaviour {
- public float speed = 5f;
- public float jumpMul = 4f;
- bool grounded = false;
- GameObject Cam;
- //Network Variables
- Vector3 objPos;
- Quaternion objRot;
- Vector3 rigVel;
- Vector3 angVel;
- Vector3 CamForward;
- Vector3 CamRight;
- float AxisVertical = 0f;
- float AxisHorizontal = 0f;
- // Use this for initialization
- void Start () {
- if(Network.isClient && networkView.isMine)
- {
- Cam = GameObject.Find("MainCamera");
- Cam.transform.parent = gameObject.transform;
- }
- }
- void OnCollisionStay()
- {
- grounded = true;
- }
- // Update is called once per frame
- void FixedUpdate () {
- if(Network.isServer)
- {
- Vector3 walkVec = CamForward * AxisVertical + CamRight * AxisHorizontal;
- walkVec = new Vector3(walkVec.x, 0, walkVec.z) * speed;
- Vector3 velocity = rigidbody.velocity;
- Vector3 velChange = (walkVec - velocity);
- velChange.y = 0;
- rigidbody.AddForce(velChange, ForceMode.VelocityChange);
- if(grounded && Input.GetButton("Jump"))
- rigidbody.AddForce(new Vector3(0, jumpMul * 10, 0));
- }
- grounded = false;
- }
- void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
- {
- if(stream.isWriting) //Sending information
- {
- if(Network.isServer) //Server -> Client
- {
- objPos = rigidbody.transform.position;
- objRot = rigidbody.transform.rotation;
- rigVel = rigidbody.velocity;
- angVel = rigidbody.angularVelocity;
- stream.Serialize(ref objPos);
- stream.Serialize(ref objRot);
- stream.Serialize(ref rigVel);
- stream.Serialize(ref angVel);
- }
- else if(Network.isClient) //Client -> Server
- {
- if(networkView.isMine) //Me -> Server
- {
- AxisVertical = Input.GetAxis("Vertical");
- AxisHorizontal = Input.GetAxis("Horizontal");
- CamForward = Cam.transform.forward;
- CamRight = Cam.transform.right;
- stream.Serialize(ref AxisVertical);
- stream.Serialize(ref AxisHorizontal);
- stream.Serialize(ref CamForward);
- stream.Serialize(ref CamRight);
- }
- }
- }
- else if(stream.isReading) //Receiving information
- {
- if(Network.isServer) //Client -> Server
- {
- stream.Serialize(ref AxisVertical);
- stream.Serialize(ref AxisHorizontal);
- stream.Serialize(ref CamForward);
- stream.Serialize(ref CamRight);
- }
- else if(Network.isClient) //Server -> Client
- {
- stream.Serialize(ref objPos);
- stream.Serialize(ref objRot);
- stream.Serialize(ref rigVel);
- stream.Serialize(ref angVel);
- rigidbody.MovePosition(objPos);
- rigidbody.MoveRotation(objRot);
- rigidbody.velocity = rigVel;
- rigidbody.angularVelocity = angVel;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment