netcode-02/Assets/Scripts/PlayerControl.cs
2022-07-01 09:54:51 +08:00

81 lines
2.0 KiB
C#

using UnityEngine;
using Unity.Netcode;
using TMPro;
[RequireComponent(typeof(NetworkObject))]
public class FoxMovement : NetworkBehaviour
{
private CharacterController controller;
public float Speed = 10f;
public float RotateSpeed = 1f;
public float Gravity = -9.8f;
private Vector3 Velocity = Vector3.zero;
public Transform GroundCheck;
public float checkRadius = 0.2f;
public bool IsGround;
public LayerMask layerMask;
public NetworkVariable<Vector3> Position = new NetworkVariable<Vector3>();
public NetworkVariable<Vector3> MoveVector = new NetworkVariable<Vector3>();
public NetworkVariable<float> Angle = new NetworkVariable<float>();
public TextMeshPro IsOwnerText;
private CharacterController characterController;
private void Awake()
{
characterController = GetComponent<CharacterController>();
}
// Start is called before the first frame update
void Start()
{
controller = transform.GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
IsOwnerText.text = IsOwner ? "Owner" : "";
IsOwnerText.text += IsClient ? " Client" : "";
if (IsOwner && IsClient)
{
ClientInput();
}
ClientMoveAndRotate();
}
void ClientInput()
{
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
var move = transform.forward * Speed * vertical * Time.deltaTime;
IsGround = Physics.CheckSphere(GroundCheck.position, checkRadius, layerMask);
if (IsGround && Velocity.y < 0)
{
Velocity.y = 0;
}
else
{
Velocity.y += Gravity * Time.deltaTime;
}
updateClientPositionAndRotationServerRpc(move + Velocity * Time.deltaTime, horizontal * RotateSpeed);
}
void ClientMoveAndRotate()
{
characterController.Move(MoveVector.Value);
transform.Rotate(Vector3.up, Angle.Value);
}
[ServerRpc]
void updateClientPositionAndRotationServerRpc(Vector3 moveVector, float angle)
{
MoveVector.Value = moveVector;
Angle.Value = angle;
}
}