Server authoritive controls

This commit is contained in:
Sewmina
2022-07-13 07:35:42 +05:30
parent 7368968176
commit 214e01fa0f
64 changed files with 6728 additions and 4125 deletions

View File

@@ -0,0 +1,45 @@
using UnityEngine;
public class DontMove : MonoBehaviour
{
new Rigidbody rigidbody;
public Vector3 position, velocity, angularVelocity;
public bool isColliding;
void Awake()
{
rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (!isColliding)
{
position = rigidbody.position;
velocity = rigidbody.velocity;
angularVelocity = rigidbody.angularVelocity;
}
}
void LateUpdate()
{
if (isColliding)
{
rigidbody.position = position;
rigidbody.velocity = velocity;
rigidbody.angularVelocity = angularVelocity;
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.collider.tag == "Player")
isColliding = true;
}
void OnCollisionExit(Collision collision)
{
if (collision.collider.tag == "Player")
isColliding = false;
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 35c18a3e8f9a08702a75aca84aaf8fd2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -28,7 +28,7 @@ public class Door : MonoBehaviour
Debug.Log(col.gameObject.name + " Entered");
NetPlayer playerObject = col.GetComponent<NetPlayer>();
if(!locked&& playerObject!=null){
if(playerObject.isLocalPlayer){
if(playerObject.isServer){
col.GetComponent<PlayerController>().inDoor = true;
}
}
@@ -38,7 +38,7 @@ public class Door : MonoBehaviour
Debug.Log(col.gameObject.name + " Exited");
NetPlayer playerObject = col.GetComponent<NetPlayer>();
if(!locked&& playerObject!=null){
if(playerObject.isLocalPlayer){
if(playerObject.isServer){
col.GetComponent<PlayerController>().inDoor = false;
}
}

View File

@@ -12,39 +12,68 @@ public class NetPlayer : NetworkBehaviour
public bool insideDoor;
public LayerMask friendLayer;
public List<NetPlayer> touchingNeighbours = new List<NetPlayer>();
[SyncVar]
public Color pColor;
[SyncVar]
public string playerName;
public Color[] playerColors;
void Start()
{
DontDestroyOnLoad(gameObject);
if(!isLocalPlayer){
gameObject.layer = LayerMask.NameToLayer("Gnd");
if (!isLocalPlayer)
{
// gameObject.layer = LayerMask.NameToLayer("Gnd");
//GetComponent<BoxCollider2D>().size = new Vector2(GetComponent<BoxCollider2D>().size.x/2f,GetComponent<BoxCollider2D>().size.y);
foreach(Behaviour localComponent in LocalComponents){
localComponent.enabled=false;
foreach (Behaviour localComponent in LocalComponents)
{
localComponent.enabled = false;
}
}
if(isLocalPlayer){
if (isLocalPlayer)
{
SceneData.localPlayer = gameObject;
if(SceneData.netSceneData==null){Debug.Log("Scene Data is not init yet");}else{
transform.position = SceneData.netSceneData.spawnPoint.position;
}
// if(SceneData.netSceneData==null){Debug.Log("Scene Data is not init yet");}else{
// transform.position = SceneData.netSceneData.spawnPoint.position;
// }
ReturnToSpawn();
}
if(isServer){
pColor = playerColors[NetworkServer.connections.Count-1];
}
GetComponent<SpriteRenderer>().color = pColor;
}
public void ReturnToSpawn(){
if(isLocalPlayer){
public void ReturnToSpawn()
{
if (isServer)
{
StartCoroutine(returnToSpawn());
}
else
{
CmdReturnToSpawn();
}
}
IEnumerator returnToSpawn(){
while(SceneData.netSceneData==null){
yield return new WaitForSeconds(0.1f);
}
while(SceneData.netSceneData.spawnPoint==null){
yield return new WaitForSeconds(0.1f);
}
transform.position = SceneData.netSceneData.spawnPoint.position;
[Command]
void CmdReturnToSpawn()
{
StartCoroutine(returnToSpawn());
}
IEnumerator returnToSpawn()
{
while (SceneData.netSceneData == null)
{
yield return new WaitForSeconds(0.1f);
}
while (SceneData.netSceneData.spawnPoint == null)
{
yield return new WaitForSeconds(0.1f);
}
transform.position = SceneData.netSceneData.spawnPoint.position;
}
[SyncVar]
public Transform parentFrnd;
@@ -52,51 +81,68 @@ public class NetPlayer : NetworkBehaviour
Transform _parentFrnd;
[Command]
void CmdChangeParent(Transform newParent){
transform.parent = newParent;
RpcChangeParent(newParent);
}
[ClientRpc]
void RpcChangeParent(Transform newParent){
transform.parent = newParent;
}
float t=0;
// [Command]
// void CmdChangeParent(Transform newParent)
// {
// transform.parent = newParent;
// RpcChangeParent(newParent);
// parentFrnd = newParent;
// }
// [ClientRpc]
// void RpcChangeParent(Transform newParent)
// {
// transform.parent = newParent;
// parentFrnd = newParent;
// }
float t = 0;
void FixedUpdate()
{
if(transform.parent!=null){
if(t <1){
t+=Time.deltaTime;
}else{
GetComponent<NetworkTransform>().useLocalSpace=true;
if (isServer)
{
parentFrnd = getOnFriend();
if (collisionImpact != Vector3.zero)
{
GetComponent<Rigidbody2D>().AddForce(-collisionImpact, ForceMode2D.Impulse);
collisionImpact = Vector3.zero;
}
}else{
GetComponent<NetworkTransform>().useLocalSpace=false;
t=0;
}
if(!isLocalPlayer){return;}
parentFrnd = getOnFriend();
transform.parent = parentFrnd;
if(_parentFrnd != parentFrnd){
if(isServer){
transform.parent = parentFrnd;
RpcChangeParent(parentFrnd);
}else{
CmdChangeParent(parentFrnd);
if (oldFlipVal != characterSprite.flipX)
{
if (isServer)
{
RpcFlipX(characterSprite.flipX);
}
else
{
CmdFlipX(characterSprite.flipX);
}
oldFlipVal = characterSprite.flipX;
}
_parentFrnd=parentFrnd;
}
if(oldFlipVal != characterSprite.flipX){
if(isServer){
RpcFlipX(characterSprite.flipX);
}else{
CmdFlipX(characterSprite.flipX);
transform.parent = parentFrnd;
if (transform.parent != null)
{
if (t < 1)
{
t += Time.deltaTime;
}
else
{
GetComponent<NetworkTransform>().useLocalSpace = true;
}
oldFlipVal=characterSprite.flipX;
}
else
{
GetComponent<NetworkTransform>().useLocalSpace = false;
t = 0;
}
if (!isLocalPlayer) { return; }
// bool someoneOnTop = false;
// foreach(NetPlayer neighbour in touchingNeighbours){
// if(neighbour.parentFrnd == this){
@@ -108,69 +154,96 @@ public class NetPlayer : NetworkBehaviour
if(!isServer){return;}
if (!isServer) { return; }
}
[Command]
void CmdFlipX(bool value){
void CmdFlipX(bool value)
{
FlipX(value);
RpcFlipX(value);
}
[ClientRpc]
void RpcFlipX(bool value){
if(!isLocalPlayer)FlipX(value);
void RpcFlipX(bool value)
{
FlipX(value);
}
void FlipX(bool value){
void FlipX(bool value)
{
characterSprite.flipX = value;
}
public void CallChangeInsideDoor(bool value){
if(isServer){
insideDoor=value;
}else{
public void CallChangeInsideDoor(bool value)
{
if (isServer)
{
insideDoor = value;
}
else
{
CmdChangeInsideDoor(value);
}
}
[Command]
void CmdChangeInsideDoor(bool value){
insideDoor=value;
void CmdChangeInsideDoor(bool value)
{
insideDoor = value;
}
public Transform getOnFriend()
{
Transform friend =null;
Transform friend = null;
//return (Physics2D.Linecast(transform.position, groundChecker.position, groundLayerMask));
Collider2D col = GetComponentInChildren<Collider2D>();
RaycastHit2D hit = Physics2D.BoxCast(col.bounds.center, new Vector2(col.bounds.size.x - (col.bounds.size.x / 5f), col.bounds.size.y), 0, Vector2.down, 0.1f, friendLayer);
friend = (hit) ? ((hit.collider.transform.GetComponent<NetPlayer>()!=null) ? hit.collider.transform : null) : null;
friend = (hit) ? ((hit.collider.transform.GetComponent<NetPlayer>() != null && hit.collider.transform.GetComponent<NetPlayer>() != this) ? hit.collider.transform : null) : null;
return friend;
}
void OnCollisionEnter2D(Collision2D col){
Vector3 collisionImpact;
void OnCollisionEnter2D(Collision2D col)
{
NetPlayer obj = col.collider.transform.GetComponent<NetPlayer>();
if(obj!=null){
if(!touchingNeighbours.Contains(obj)){
if (obj != null)
{
collisionImpact = col.contacts[0].normal * col.contacts[0].relativeVelocity * col.otherRigidbody.mass;
Debug.Log("Collision impact : " + collisionImpact);
if (!touchingNeighbours.Contains(obj))
{
touchingNeighbours.Add(obj);
}
}
}
void OnCollisionExit2D(Collision2D col){
void OnCollisionExit2D(Collision2D col)
{
NetPlayer obj = col.collider.transform.GetComponent<NetPlayer>();
if(obj!=null){
if(touchingNeighbours.Contains(obj)){
if (obj != null)
{
if (touchingNeighbours.Contains(obj))
{
touchingNeighbours.Remove(obj);
}
}
}
void UpdatePushBoxes(){
foreach(PushBox box in FindObjectsOfType<PushBox>()){
void UpdatePushBoxes()
{
foreach (PushBox box in FindObjectsOfType<PushBox>())
{
box.UpdateNeighbourCount();
}
}
public void OnSceneChanged(){
if(!isServer){return;}
foreach(GameObject obj in SceneData.netSceneData.networkObjects){
GameObject go = Instantiate(obj);
NetworkServer.Spawn(go, NetworkServer.localConnection);
}
}
}

View File

@@ -7,6 +7,8 @@ public class NetSceneData : MonoBehaviour
public Transform spawnPoint;
public Transform doorExit;
public Door door;
public GameObject[] networkObjects;
void Awake()
{
SceneData.netSceneData = this;

View File

@@ -27,18 +27,60 @@ public class PlayerController : NetworkBehaviour
public bool insideDoor = false;
bool enteringDoor = false;
public Vector3 neighboursDetectorSize;
void Start()
{
jumpT = jumpDuration;
if(!isServer){
rigidbody.simulated=false;
}
}
[SyncVar]
bool _grounded = false;
float moveInput = 0;
bool jumpReleased = true;
[HideInInspector]
public bool inWater;
[SyncVar]
public bool InteractionKeyPressed;
[SyncVar]
public bool JumpKeyPressed;
[SyncVar]
public float HorizontalAxis;
public float moveInput = 0;
[Command]
void CmdUpdateInput(float _horizontal, bool jump, bool interact){
HorizontalAxis = _horizontal;
JumpKeyPressed=jump;
InteractionKeyPressed=interact;
}
void ListenInput(){
HorizontalAxis=0;
if (Input.GetKey(InputManager.data().leftInput)) { HorizontalAxis = -1; } else if (Input.GetKey(InputManager.data().rightInput)) { HorizontalAxis = 1; }
JumpKeyPressed = Input.GetKey(InputManager.data().jumpInput);
InteractionKeyPressed = Input.GetKey(InputManager.data().interactingKey);
}
void FixedUpdate()
{
if(!isServer){
if(isLocalPlayer){
//Command Inputs to server
ListenInput();
CmdUpdateInput(HorizontalAxis, JumpKeyPressed, InteractionKeyPressed);
}
return;
}
if(isLocalPlayer){
ListenInput();
}
isGrounded = getGrounded();
if (_grounded != isGrounded)
@@ -57,7 +99,7 @@ public class PlayerController : NetworkBehaviour
if (isSwimming)
{
rigidbody.velocity = new Vector2(rigidbody.velocity.x, Mathf.Lerp(rigidbody.velocity.y, buoyantForce, buoyantSpd));
if ((Input.GetKey(InputManager.data().jumpInput)))
if ((JumpKeyPressed))
{
rigidbody.velocity = new Vector2(rigidbody.velocity.x, jumpForce / 12f);
}
@@ -73,18 +115,16 @@ public class PlayerController : NetworkBehaviour
//Update In-Air value on animation
animator.SetBool("inAir", !isGrounded);
animator.SetBool("isOnWater", inWater);
float HorizontalAxis = 0;
if (Input.GetKey(InputManager.data().leftInput)) { HorizontalAxis = -1; } else if (Input.GetKey(InputManager.data().rightInput)) { HorizontalAxis = 1; }
// if (GameManager.isPaused) { HorizontalAxis = 0; }
//Move according to input
//Exit the door
if (enteringDoor && !Input.GetKey(InputManager.data().interactingKey))
if (enteringDoor && !InteractionKeyPressed)
{
enteringDoor = false;
}
if (insideDoor && !enteringDoor && Input.GetKey(InputManager.data().interactingKey))
if (insideDoor && !enteringDoor && InteractionKeyPressed)
{
Debug.Log("Exiting door");
transform.position = SceneData.netSceneData.door.transform.position;
@@ -101,18 +141,20 @@ public class PlayerController : NetworkBehaviour
else
{
//Change moveInput while in-air | IF there is an input
if (Input.GetKey(InputManager.data().leftInput) || Input.GetKey(InputManager.data().rightInput))
// if (Input.GetKey(InputManager.data().leftInput) || Input.GetKey(InputManager.data().rightInput))
if (HorizontalAxis!=0)
{
moveInput = Mathf.Lerp(moveInput, HorizontalAxis, 0.2f);
}
}
//Enter the door
if (inDoor && Input.GetKey(InputManager.data().interactingKey) && !enteringDoor)
if (inDoor && InteractionKeyPressed && !enteringDoor)
{
if (SceneData.netSceneData.doorExit != null)
{
Debug.Log("Entering door");
transform.DetachChildren();
transform.position = SceneData.netSceneData.doorExit.position;
insideDoor = true;
enteringDoor = true;
@@ -148,10 +190,15 @@ public class PlayerController : NetworkBehaviour
// }
// }
rigidbody.transform.Translate(new Vector2(moveSpeed * moveInput, 0));
if(moveInput == 0){
rigidbody.constraints = RigidbodyConstraints2D.FreezePositionX|RigidbodyConstraints2D.FreezeRotation;
}else{
rigidbody.constraints = RigidbodyConstraints2D.FreezeRotation;
}
bool _canJump = canJump();
if ((Input.GetKey(InputManager.data().jumpInput)) && _canJump)
if ((JumpKeyPressed) && _canJump)
{
jumpT = 0;
jumpReleased = false;
@@ -161,7 +208,7 @@ public class PlayerController : NetworkBehaviour
//Blocks continous jump button
if (!Input.GetKey(InputManager.data().jumpInput)) { jumpReleased = true; }
if (!JumpKeyPressed) { jumpReleased = true; }
//Apply Jump to player
if (jumpT < jumpDuration)
@@ -169,7 +216,7 @@ public class PlayerController : NetworkBehaviour
jumpT += Time.deltaTime;
float progress = (jumpDuration - jumpT) / jumpDuration;
//|| jumpT < jumpDuration/2f
if ((Input.GetKey(InputManager.data().jumpInput)) || b) { rigidbody.AddForce(new Vector2(0, jumpForce * progress)); }
if ((JumpKeyPressed) || b) { rigidbody.AddForce(new Vector2(0, jumpForce * progress)); }
}
else { b = false; }
@@ -227,6 +274,7 @@ public class PlayerController : NetworkBehaviour
void OnDrawGizmos()
{
Collider2D col = GetComponentInChildren<Collider2D>();
Gizmos.DrawWireCube(transform.position, neighboursDetectorSize);
Gizmos.color = Color.red;
Gizmos.DrawWireCube(col.bounds.center - new Vector3(0, groundCheckerDist), new Vector2(col.bounds.size.x - (col.bounds.size.x / 5f), col.bounds.size.y * groundCheckerHeighMultipler));
}

View File

@@ -6,6 +6,9 @@ using Mirror;
public class PushBox : NetworkBehaviour
{
public int playersRequired;
[SyncVar(hook =nameof(OnTouchersChanged))]
public int playersTouching;
public Vector3 detectorSize;
public Text numberTxt;
public List<NetPlayer> DTP;
@@ -18,35 +21,21 @@ public class PushBox : NetworkBehaviour
UpdateText();
}
void OnCollisionEnter2D(Collision2D col)
{
NetPlayer player = col.collider.GetComponent<NetPlayer>();
if (player != null)
{
if (!DTP.Contains(player))
{
DTP.Add(player);
UpdateNeighbourCount();
}
}
void Update(){
}
void OnCollisionExit2D(Collision2D col)
{
NetPlayer player = col.collider.GetComponent<NetPlayer>();
if (player != null)
{
if (DTP.Contains(player))
{
DTP.Remove(player);
UpdateNeighbourCount();
}
}
private void OnDrawGizmos() {
Gizmos.DrawWireCube(transform.position, detectorSize);
}
[Server]
public void UpdateNeighbourCount(){
public void UpdateNeighbourCount()
}
[Server]
public void UpdateNeighbourCount2()
{
targets = new List<NetPlayer>();
Neighbours = new List<NetPlayer>();
@@ -58,7 +47,7 @@ public class PushBox : NetworkBehaviour
while(targets.Count > 0 && failCount < 50){
failCount++;
Neighbours.Add(targets[0]);
if(!Neighbours.Contains(targets[0])){Neighbours.Add(targets[0]);}
scannedList.Add(targets[0]);
foreach(NetPlayer neighbour in targets[0].touchingNeighbours){
if(!scannedList.Contains(neighbour)){
@@ -73,7 +62,9 @@ public class PushBox : NetworkBehaviour
Debug.LogError("Fail switch triggered");
}
GetComponent<Rigidbody2D>().simulated=((playersRequired - Neighbours.Count) > 0);
playersTouching = Neighbours.Count;
GetComponent<Rigidbody2D>().constraints=((playersRequired - playersTouching) > 0) ? RigidbodyConstraints2D.FreezeAll : RigidbodyConstraints2D.FreezeRotation;
UpdateText();
}
@@ -82,4 +73,14 @@ public class PushBox : NetworkBehaviour
{
numberTxt.text = (playersRequired - Neighbours.Count).ToString();
}
void UpdateText(int touchers)
{
numberTxt.text = (playersRequired - touchers).ToString();
}
void OnTouchersChanged(int oldValue, int newValue){
UpdateText(newValue);
}
}

View File

@@ -90,7 +90,7 @@ public class loadingScreen : MonoBehaviour
// Debug.Log()
SceneData.netSceneData = FindObjectOfType<NetSceneData>();
SceneData.localPlayer.GetComponent<NetPlayer>().ReturnToSpawn();
SceneData.localPlayer.GetComponent<NetPlayer>().OnSceneChanged();
}
}
public bool alreadyConnected= false;