So I’m making an adorable little 2-player space game for a college project. Players fly about, shoot each other, bullets hit and decrement health, all of that is working except for one problem.
When a remote-client-player moves and fires a bullet, the bullet spawns inside the player and a collision occurs. This does not happen to the local-client-player, and it does not happen to any motionless player. I’m assuming this happens because the bullet is spawning at the player’s server-position and not its client-position, where the latency causes the bullet to spawn within the player.
I would like to know how to spawn a bullet at the remote-client-player’s client-position, or of any other strategy that would fix my problem.
This is my current script attached to a player for firing:
PlayerNetFire Script
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class PlayerNetFire : NetworkBehaviour
{
public GameObject projectile;
public GameObject firingPoint; //Firing point
public float firingRate; //Firing rate
private float firingRateRecord; //Firing rate returns to this after firing.
// Use this for initialization
void Start ()
{
firingRateRecord = firingRate;
}
// Update is called once per frame
void Update ()
{
//Firing
if (Input.GetKey("space") && firingRate <= 0 && isLocalPlayer)
{
CntSpawnBullet();
firingRate = firingRateRecord;
}
if (firingRate > 0)
{
firingRate -= Time.deltaTime;
}
else
{
firingRate = 0;
}
}
//Passes the client firing point position and rotation to to CmdSpawnBullet
[Client]
void CntSpawnBullet()
{
CmdSpawnBullet(firingPoint.transform.position, transform.rotation);
}
//Generates a bullet with the client's firing point position and rotation.
[Command]
void CmdSpawnBullet(Vector3 position, Quaternion rotation)
{
GameObject bullet = (GameObject)Instantiate(
projectile,
position,
rotation);
NetworkServer.Spawn(bullet);
}
}