add unity project for networking
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace DefaultNamespace
|
||||
{
|
||||
public class NetworkPlayer : NetworkBehaviour
|
||||
{
|
||||
[Header("Player Values")]
|
||||
[SerializeField] private float speed = 10f;
|
||||
[SerializeField] private float initialHealth = 100.0f;
|
||||
[SerializeField] private NetworkObject bulletPrefab;
|
||||
|
||||
[Header("Input")]
|
||||
[SerializeField] private InputActionProperty moveInput;
|
||||
[SerializeField] private InputActionProperty fireInput;
|
||||
|
||||
[Header("Elements")]
|
||||
[SerializeField] private Camera playerCamera;
|
||||
[SerializeField] private Canvas playerCanvas;
|
||||
[SerializeField] private Image playerHealthBar;
|
||||
|
||||
private NetworkVariable<float> _health = new NetworkVariable<float>();
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
// playerCamera.gameObject.SetActive(IsLocalPlayer);
|
||||
// playerCanvas.gameObject.SetActive(IsLocalPlayer);
|
||||
|
||||
|
||||
if (IsLocalPlayer)
|
||||
{
|
||||
_health.OnValueChanged += OnHealthChanged;
|
||||
|
||||
moveInput.action.Enable();
|
||||
|
||||
fireInput.action.performed += OnFired;
|
||||
fireInput.action.Enable();
|
||||
}
|
||||
|
||||
if (IsServer)
|
||||
{
|
||||
_health.Value = initialHealth;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
|
||||
if (IsLocalPlayer)
|
||||
{
|
||||
_health.OnValueChanged -= OnHealthChanged;
|
||||
|
||||
moveInput.action.Disable();
|
||||
|
||||
fireInput.action.performed -= OnFired;
|
||||
fireInput.action.Disable();
|
||||
}
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
if (!IsLocalPlayer) return;
|
||||
|
||||
Vector2 input = moveInput.action.ReadValue<Vector2>() * (speed * Time.deltaTime);
|
||||
transform.Translate(input.x, 0.0f, input.y);
|
||||
}
|
||||
|
||||
private void OnHealthChanged(float previousValue, float newValue)
|
||||
{
|
||||
// playerHealthBar.fillAmount = newValue / initialHealth;
|
||||
}
|
||||
|
||||
private void OnFired(InputAction.CallbackContext obj)
|
||||
{
|
||||
SpawnBulletRpc();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
private void SpawnBulletRpc()
|
||||
{
|
||||
NetworkObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
|
||||
bullet.Spawn(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user