SanAndreasUnity/Assets/Scripts/Networking/NetworkRigidBody.cs

78 lines
2 KiB
C#
Raw Normal View History

2020-07-01 21:32:40 +00:00
using Mirror;
using UnityEngine;
namespace SanAndreasUnity.Net
{
public class NetworkRigidBody : NetworkBehaviour
{
public Rigidbody Rigidbody { get; set; }
2020-07-01 22:59:17 +00:00
[SyncVar] Vector3 m_net_position = Vector3.zero;
[SyncVar] Vector3 m_net_rotation = Vector3.zero;
[SyncVar] Vector3 m_net_velocity = Vector3.zero;
[SyncVar] Vector3 m_net_angularVelocity = Vector3.zero;
2020-07-01 21:32:40 +00:00
void Awake()
{
this.Rigidbody = this.GetComponent<Rigidbody>();
2020-07-01 22:59:17 +00:00
if (NetStatus.IsServer)
{
this.UpdateServer();
this.InvokeRepeating(nameof(this.UpdateServer), 0.001f, this.syncInterval);
}
else
{
this.InvokeRepeating(nameof(this.UpdateClient), 0.001f, this.syncInterval);
}
2020-07-01 21:32:40 +00:00
}
2020-07-01 22:59:17 +00:00
public void UpdateServer()
{
if (null == this.Rigidbody)
return;
Vector3 pos = this.Rigidbody.position;
Vector3 rot = this.Rigidbody.rotation.eulerAngles;
Vector3 vel = this.Rigidbody.velocity;
Vector3 angVel = this.Rigidbody.angularVelocity;
if (pos != m_net_position)
{
m_net_position = pos;
}
if (rot != m_net_rotation)
{
m_net_rotation = rot;
}
if (vel != m_net_velocity)
{
m_net_velocity = vel;
}
if (angVel != m_net_angularVelocity)
{
m_net_angularVelocity = angVel;
}
}
public void UpdateClient()
2020-07-01 21:32:40 +00:00
{
if (null == this.Rigidbody)
return;
2020-07-01 22:59:17 +00:00
this.Rigidbody.MovePosition(m_net_position);
this.Rigidbody.MoveRotation(Quaternion.Euler(m_net_rotation));
this.Rigidbody.velocity = m_net_velocity;
this.Rigidbody.angularVelocity = m_net_angularVelocity;
}
2020-07-01 21:32:40 +00:00
}
}