Search code examples
c#network-programmingunity-game-engineunity3d-unet

Player colliding with bullet when moving - Unity UNET


Setting : Creating my first multiplayer game and running into an odd issue. it's a tank game where players can shoot bullets and kill each other

Problem : When the client shoots while moving, the bullet seems to spawn with a little delay which causes the the player to collide with the bullet.

The issue seems to be that the player itself is local and the bullet is being spawned on the network ( which is causing the delay)

Note: The host player does not have this problem, therefore it's somehow related to networking.

How can I sync the bullet with the client player?

private void Fire(){
    // Set the fired flag so only Fire is only called once.
    m_Fired = true;
    CmdCreateBullets ();
    // Change the clip to the firing clip and play it.
    m_ShootingAudio.clip = m_FireClip;
    m_ShootingAudio.Play ();
    // Reset the launch force.  This is a precaution in case of missing button events.
    m_CurrentLaunchForce = m_MinLaunchForce;
}

[Command]
private void CmdCreateBullets()
{

    GameObject shellInstance = (GameObject)
        Instantiate (m_Shell, m_FireTransform.position, m_FireTransform.rotation) ;
    // Set the shell's velocity to the launch force in the fire position's forward direction.
    shellInstance.GetComponent<Rigidbody>().velocity = m_CurrentLaunchForce * m_FireTransform.forward; 

    NetworkServer.Spawn (shellInstance);

}

Solution

  • I solved it the following way. if someone can look over to confirm my answer, it would be nice.

    private void Fire(){
        // Set the fired flag so only Fire is only called once.
        m_Fired = true;
        CmdCreateBullets ();
        // Change the clip to the firing clip and play it.
        m_ShootingAudio.clip = m_FireClip;
        m_ShootingAudio.Play ();
        // Reset the launch force.  This is a precaution in case of missing button events.
        m_CurrentLaunchForce = m_MinLaunchForce;
    }
    
    [Command]
    private void CmdCreateBullets()
    {
        RpclocalBullet ();
    }
    
    [ClientRpc]
    private void RpclocalBullet(){
        GameObject shellInstance = (GameObject)
            Instantiate (m_Shell, m_FireTransform.position, m_FireTransform.rotation) ;
        // Set the shell's velocity to the launch force in the fire position's forward direction.
        shellInstance.GetComponent<Rigidbody>().velocity = 25f * m_FireTransform.forward; 
    }