Hello. I am currently learning about netcode and i am creating a simple fps multiplayer game with netcode.
The problem that i am facing right now is that, i use a ServerRpc call for the shoot function.
When i shoot from the host, it works perfectly, however from the clients, the shoot function is called multiple times. For example, for each mouse click, the function is called 4-5 times.
void Update()
{
if (!IsOwner) return;
UserInput();
}
private void UserInput()
{
//Input
if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
else shooting = Input.GetKeyDown(KeyCode.Mouse0);
//Shoot
if (readyToShoot && shooting && !bulletsLeft > 0){
ShootServerRpc();
}
}
[ServerRpc]
private void ShootServerRpc()
{
Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
Vector3 targetPoint;
targetPoint = ray.GetPoint(75);
//Calculate direction
Vector3 directionWithoutSpread = targetPoint - attackPoint.position;
//Spread
float x = Random.Range(-spread, spread);
float y = Random.Range(-spread, spread);
float z = Random.Range(-spread, spread);
//Calc Direction with Spread
Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, z);
//Instantiate bullet/projectile
GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
currentBullet.transform.forward = directionWithSpread.normalized;
//AddForce
currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
bulletsLeft--;
bulletsShot--;
if (allowInvoke)
{
Invoke("ShotReset", timeBetweenShooting);
allowInvoke = false;
}
currentBullet.GetComponent<NetworkObject>().Spawn();
}