add unity project for networking
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
using System;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace DefaultNamespace
|
||||
{
|
||||
public class NetworkPlayer : NetworkBehaviour
|
||||
{
|
||||
[SerializeField] private Camera camera;
|
||||
[SerializeField] private float speed = 10.0f;
|
||||
[SerializeField] private float rotationSpeed = 60.0f;
|
||||
[SerializeField] private Rigidbody bulletPrefab;
|
||||
[SerializeField] private float bulletForce = 50.0f;
|
||||
[SerializeField] private float initialHealth = 100.0f;
|
||||
|
||||
private NetworkVariable<float> _health = new NetworkVariable<float>(0);
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
camera.gameObject.SetActive(IsLocalPlayer);
|
||||
|
||||
if (IsLocalPlayer)
|
||||
{
|
||||
_health.OnValueChanged += OnHealthChanged;
|
||||
}
|
||||
|
||||
if (IsServer)
|
||||
{
|
||||
_health.Value = initialHealth;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
if (IsLocalPlayer)
|
||||
{
|
||||
_health.OnValueChanged -= OnHealthChanged;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnHealthChanged(float previousValue, float newValue)
|
||||
{
|
||||
// update health bar etc.
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!IsLocalPlayer) return;
|
||||
|
||||
if (Input.GetButtonDown("Fire1"))
|
||||
{
|
||||
ShootRpc();
|
||||
}
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
if (!IsLocalPlayer) return;
|
||||
|
||||
transform.Translate(
|
||||
(Vector3.right * Input.GetAxis("Horizontal") + Vector3.forward * Input.GetAxis("Vertical")) *
|
||||
(speed * Time.deltaTime));
|
||||
|
||||
transform.Rotate(Vector3.up, Input.GetAxis("Mouse X") * rotationSpeed * Time.deltaTime);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
private void ShootRpc()
|
||||
{
|
||||
Rigidbody bullet = Instantiate(bulletPrefab, transform.position + transform.forward, transform.rotation);
|
||||
bullet.GetComponent<NetworkObject>().Spawn();
|
||||
bullet.AddForce(transform.forward * bulletForce, ForceMode.Impulse);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user