66 lines
1.7 KiB
C#
66 lines
1.7 KiB
C#
using Unity.Netcode;
|
|
using UnityEngine;
|
|
|
|
public class PlayerShoot : NetworkBehaviour
|
|
{
|
|
[SerializeField] float damageAmount = 10f;
|
|
[SerializeField] float range = 100f;
|
|
[SerializeField] Transform cameraRoot;
|
|
|
|
[SerializeField] GameObject hitEffectPrefab;
|
|
|
|
private PlayerHealth playerHealth;
|
|
|
|
public override void OnNetworkSpawn()
|
|
{
|
|
if (IsOwner)
|
|
{
|
|
playerHealth = GetComponent<PlayerHealth>();
|
|
if (playerHealth == null)
|
|
{
|
|
Debug.LogError("PlayerHealth component not found on player");
|
|
}
|
|
}
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (!IsOwner) return;
|
|
|
|
if(playerHealth == null || playerHealth.isDead.Value) return;
|
|
|
|
if (Input.GetMouseButtonDown(0))
|
|
{
|
|
ShootServerRpc(cameraRoot.position, cameraRoot.forward);
|
|
}
|
|
}
|
|
|
|
[ServerRpc]
|
|
private void ShootServerRpc(Vector3 _origin, Vector3 _direction)
|
|
{
|
|
Collider[] ownerColliders = GetComponentsInChildren<Collider>();
|
|
|
|
if (Physics.Raycast(_origin, _direction, out RaycastHit _hit, range))
|
|
{
|
|
if (System.Array.Exists(ownerColliders, c => c == _hit.collider))
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (_hit.collider.TryGetComponent(out PlayerHealth _playerHealth))
|
|
{
|
|
_playerHealth.TakeDamage((int)damageAmount);
|
|
}
|
|
|
|
SpawnHitEffectClientRpc(_hit.point);
|
|
}
|
|
}
|
|
|
|
[ClientRpc]
|
|
private void SpawnHitEffectClientRpc(Vector3 _hitPosition)
|
|
{
|
|
Debug.Log($"Spawning hit effect at {_hitPosition}");
|
|
Instantiate(hitEffectPrefab, _hitPosition, Quaternion.identity);
|
|
}
|
|
}
|