I’m working in a complex racing simulator wich i need to make it multiplayer.
I have been trying all sort of different things based on both Badumna and Unity networking with no luck.
The game it self as a stand alone works great. but when i have 2 instances of the car (player and remote) the CPU load spikes to the roof. It even crash my testing second computer. By the looks of it each client is computing all the scripts from both cars or something like that.
I try disabling all scripts from the remote instanced car and i get all sort of really wierd things like wheels collider not working…
What i want to do is to have all the script and physics calculations on the client and brodcast positions data only.
So the remote player would be a simple graphic representation of the remote car…
Can anyone give me some hints on this matter?? please i need help really bad.
How are you currently instantiating the cars? Are you using Network.Instantiate?
What sorts of things do your car scripts currently do that makes you suspect they are causing the CPU load? If the car script is not too big you could post it here.
I’m instatiating them via Network.instatiate (wich i need to get rid on the future cause i need the car to be loaded in a previus level)
The bigger scripts are the wheel’s (4) wich among other things it has Pacejka tire friction formulas forces and such.
The other big one is the Engine script that do al sort of calculation based on technical data like bore, stroke, compression chamer, etc… Thing is as a stand alone it runs nice and smooth. but when i have a second car over network my test computer over loads and crashes. Even runing two istances of the game locaclly i get a very very bumpy connection.
I could be wrong but does the calculation of Vectors over the net is that CPU consuming?? Btw i am using the unity’s tutorial “NetworkRigidbody”.
I did get some errors at first refering to some AddForceAtPosition inside the wheels script when the remote player was spawned. So that means the client is computing all scripts in the world wether is local or remote.
On your car script, add the test if (networkView.isMine). If it is the case, you control it, and do the collision and physics stuff.
To broadcast the position, you may use state synchronize “Unreliable”.
If you want the NetworkView to observe your script instead of transform components, use OnSerializeNetworkView.
stream.isWriting is another way to determine whether you own the networkview or not. if you own it, you are “writing”, so you send the data. in you are not the owner, you are “reading” (and receiving data).
If it is the local player i allow inputs as a safe guard actually, it it is remote player i turn off all the scripts on the car.
function OnNetworkInstantiate (msg : NetworkMessageInfo) {
// This is our own player
if (networkView.isMine)
{
GetComponent(CarControl).PlayerCanDrive = true;
GetComponent("NetworkRigidbody").enabled = false;
}
// This is just some remote controlled player, don't execute direct
// user input on this
else
{
name += "Remote";
GetComponent(CarControl).enabled = false;
GetComponent(AeroDrag).enabled = false;
GetComponent(Hud).enabled = false;
GetComponent(SlipSmoke).enabled = false;
GetComponent(Garage).enabled = false;
GetComponent(EngineSound).enabled = false;
transform.Find ("WheelRL").GetComponent(Wheel).enabled = false;
transform.Find ("WheelRR").GetComponent(Wheel).enabled = false;
transform.Find ("WheelFL").GetComponent(Wheel).enabled = false;
transform.Find ("WheelFR").GetComponent(Wheel).enabled = false;
transform.Find ("V8Engine").GetComponent(GearBox).enabled = false;
transform.Find ("V8Engine").GetComponent(Engine).enabled = false;
GetComponent("NetworkRigidbody").enabled = true;
}
}
then this is the NetworkRigidbody code attached to the prefab:
using UnityEngine;
using System.Collections;
public class NetworkRigidbody : MonoBehaviour {
public double m_InterpolationBackTime = 0.1;
public double m_ExtrapolationLimit = 0.5;
internal struct State
{
internal double timestamp;
internal Vector3 pos;
internal Vector3 velocity;
internal Quaternion rot;
internal Vector3 angularVelocity;
}
// We store twenty states with "playback" information
State[] m_BufferedState = new State[20];
// Keep track of what slots are used
int m_TimestampCount;
void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
{
// Send data to server
if (stream.isWriting)
{
Vector3 pos = rigidbody.position;
Quaternion rot = rigidbody.rotation;
Vector3 velocity = rigidbody.velocity;
Vector3 angularVelocity = rigidbody.angularVelocity;
stream.Serialize(ref pos);
stream.Serialize(ref velocity);
stream.Serialize(ref rot);
stream.Serialize(ref angularVelocity);
}
// Read data from remote client
else
{
Vector3 pos = Vector3.zero;
Vector3 velocity = Vector3.zero;
Quaternion rot = Quaternion.identity;
Vector3 angularVelocity = Vector3.zero;
stream.Serialize(ref pos);
stream.Serialize(ref velocity);
stream.Serialize(ref rot);
stream.Serialize(ref angularVelocity);
// Shift the buffer sideways, deleting state 20
for (int i=m_BufferedState.Length-1;i>=1;i--)
{
m_BufferedState[i] = m_BufferedState[i-1];
}
// Record current state in slot 0
State state;
state.timestamp = info.timestamp;
state.pos = pos;
state.velocity = velocity;
state.rot = rot;
state.angularVelocity = angularVelocity;
m_BufferedState[0] = state;
// Update used slot count, however never exceed the buffer size
// Slots aren't actually freed so this just makes sure the buffer is
// filled up and that uninitalized slots aren't used.
m_TimestampCount = Mathf.Min(m_TimestampCount + 1, m_BufferedState.Length);
// Check if states are in order, if it is inconsistent you could reshuffel or
// drop the out-of-order state. Nothing is done here
for (int i=0;i<m_TimestampCount-1;i++)
{
if (m_BufferedState[i].timestamp < m_BufferedState[i+1].timestamp)
Debug.Log("State inconsistent");
}
}
}
// We have a window of interpolationBackTime where we basically play
// By having interpolationBackTime the average ping, you will usually use interpolation.
// And only if no more data arrives we will use extra polation
void Update () {
// This is the target playback time of the rigid body
double interpolationTime = Network.time - m_InterpolationBackTime;
// Use interpolation if the target playback time is present in the buffer
if (m_BufferedState[0].timestamp > interpolationTime)
{
// Go through buffer and find correct state to play back
for (int i=0;i<m_TimestampCount;i++)
{
if (m_BufferedState[i].timestamp <= interpolationTime || i == m_TimestampCount-1)
{
// The state one slot newer (<100ms) than the best playback state
State rhs = m_BufferedState[Mathf.Max(i-1, 0)];
// The best playback state (closest to 100 ms old (default time))
State lhs = m_BufferedState[i];
// Use the time between the two slots to determine if interpolation is necessary
double length = rhs.timestamp - lhs.timestamp;
float t = 0.0F;
// As the time difference gets closer to 100 ms t gets closer to 1 in
// which case rhs is only used
// Example:
// Time is 10.000, so sampleTime is 9.900
// lhs.time is 9.910 rhs.time is 9.980 length is 0.070
// t is 9.900 - 9.910 / 0.070 = 0.14. So it uses 14% of rhs, 86% of lhs
if (length > 0.0001)
t = (float)((interpolationTime - lhs.timestamp) / length);
// if t=0 => lhs is used directly
transform.localPosition = Vector3.Lerp(lhs.pos, rhs.pos, t);
transform.localRotation = Quaternion.Slerp(lhs.rot, rhs.rot, t);
return;
}
}
}
// Use extrapolation
else
{
State latest = m_BufferedState[0];
float extrapolationLength = (float)(interpolationTime - latest.timestamp);
// Don't extrapolation for more than 500 ms, you would need to do that carefully
if (extrapolationLength < m_ExtrapolationLimit)
{
float axisLength = extrapolationLength * latest.angularVelocity.magnitude * Mathf.Rad2Deg;
Quaternion angularRotation = Quaternion.AngleAxis(axisLength, latest.angularVelocity);
rigidbody.position = latest.pos + latest.velocity * extrapolationLength;
rigidbody.rotation = angularRotation * latest.rot;
rigidbody.velocity = latest.velocity;
rigidbody.angularVelocity = latest.angularVelocity;
}
}
}
}
Network view is in the parent transform observing itself.
I did try to drag a script into the observed variable but it woun’t let me and can’t seem to find my scripts on the drop down menu either.
Yes, it is that, but are you sure about GetComponent("NetworkRigidbody").enabled = false; when you are the owner ? But I suppose you have your reasons.
Regarding the second script, not only it is way too long but also I lack knowledge in C#. In addition, it seems pretty complicated so…I must give up
But I recognized the part when you should be sending data (OnSerializeNetworkView), it should be ok. The rest, huh…
About the lag, you mean the car do jerks moves (like, when a game runs with low framerate) ? That’s because network data is sent 15 times per seconds. But the framerate is way higher than that.
To counter that, instead of picking the value of stream.Serialize(ref pos); and giving it to the transform component, you can use a lerp function, in Update, so you will lerp 4 times, to make a smooth move.
Quoting the networking tutorial of M2H :
transform.position = posReceive;
//To reduce laggy movement a bit you could comment the line above and use position lerping below instead:
//transform.position = Vector3.Lerp(transform.position, posReceive, 0.9); //"lerp" to the posReceive by 90%
Edit : but by any chance, isn’t that what you were writing in your networkrigidbody ?
The “jerky” moving of the cars right now is because the game “hangs” from time to time. It is like when you lose connection in a game and it stops until you can catch up… Maybe i am using the wrong type of server?? It gotta be something obvius that is escaping me but i can’t realize what is it.
A wierd thing : I host in my computer. connecto ver LAN with the other PC. While there’s only one car in the scene game runs fine in both PCs. When both car are spawned in my PC the CPU load spikes from about 15 -20% to 60 % on my other PC CPU load spikes to 100% but game still kinda works. When i move the car on the host my test PC (the one that was at 100% CPU) dies… like in caput. nothing else happens. Wierd thing is that it happens when i move the other car. Btw, when cars are fully stoped they are kinematic rigidbodies.
Like a FPS where when there is a huge spike of lag, you stop moving, then you are teleported somewhere else (but small duration, and high frequency ?
Else, for your information, if you set state synchronize to unreliable as I said, this transmission mode do not care about transmissions losts (unlike Reliable Delta Compressed). But I doubt you have so many losses that the game become a mess. Don’t forget about the 15 data transmissions per second, and the lerp solution, it may help.