quantum-space-buddies/QSB/NetworkPlayer.cs

83 lines
2.9 KiB
C#
Raw Normal View History

using System;
using System.Linq;
using UnityEngine;
2020-02-10 23:03:28 +01:00
using UnityEngine.Networking;
namespace QSB {
public class NetworkPlayer: NetworkBehaviour {
Transform _body;
2020-02-11 13:57:43 +01:00
float _smoothSpeed = 10f;
public static NetworkPlayer localInstance { get; private set; }
[SyncVar(hook = "OnChangeSector")]
public Sector.Name _sector;
Transform _sectorTransform;
2020-02-10 23:03:28 +01:00
void Start () {
2020-02-11 20:05:02 +01:00
QSB.LogToScreen("Started network player");
2020-02-10 23:03:28 +01:00
_sectorTransform = Locator.GetAstroObject(AstroObject.Name.TimberHearth).transform;
2020-02-10 23:03:28 +01:00
var player = Locator.GetPlayerBody().transform.Find("Traveller_HEA_Player_v2");
if (isLocalPlayer) {
localInstance = this;
2020-02-10 23:03:28 +01:00
_body = player;
} else {
_body = Instantiate(player);
2020-02-11 14:38:08 +01:00
_body.GetComponent<PlayerAnimController>().enabled = false;
2020-02-11 14:14:17 +01:00
_body.Find("player_mesh_noSuit:Traveller_HEA_Player/player_mesh_noSuit:Player_Head").gameObject.layer = 0;
2020-02-10 23:03:28 +01:00
_body.parent = transform;
_body.localPosition = Vector3.zero;
_body.localRotation = Quaternion.identity;
}
}
public void EnterSector (Sector sector) {
if (!isLocalPlayer) {
2020-02-11 20:05:02 +01:00
QSB.LogToScreen("EnterSector being called for non-local player! Bad!");
}
var name = sector.GetName();
if (name != Sector.Name.Unnamed) {
2020-02-11 20:05:02 +01:00
QSB.LogToScreen("Client entered sector", name.ToString());
CmdSetSector(name);
}
}
[Command]
void CmdSetSector (Sector.Name name) {
if (!isServer) {
2020-02-11 20:05:02 +01:00
QSB.LogToScreen("This is not the server, so skipping CmdSetSector");
return;
}
2020-02-11 20:05:02 +01:00
QSB.LogToScreen("This is iserver, so setting client sector to", name.ToString());
_sector = name;
}
void OnChangeSector (Sector.Name name) {
2020-02-11 20:05:02 +01:00
QSB.LogToScreen("Client received onChange from server, to sector", name.ToString());
_sector = name;
var sectors = GameObject.FindObjectsOfType<Sector>();
foreach (var sector in sectors) {
if (name == sector.GetName()) {
_sectorTransform = sector.transform;
return;
}
}
}
2020-02-10 23:03:28 +01:00
void Update () {
if (!_body) {
return;
}
if (isLocalPlayer) {
transform.position = _body.position - _sectorTransform.position;
transform.rotation = _body.rotation * Quaternion.Inverse(_sectorTransform.rotation);
2020-02-10 23:03:28 +01:00
} else {
_body.position = Vector3.Lerp(_body.position, _sectorTransform.position + transform.position, _smoothSpeed * Time.deltaTime);
_body.rotation = transform.rotation * _sectorTransform.rotation;
2020-02-10 23:03:28 +01:00
}
}
}
}