0
votes

i´m work on a networked game and stuck on an problem with the instantiation or NetworkSpawn of an bullet. If the hostplayer/server "fires" the bullet is spaned, synced and flys all the way it should do. If a client "fires" the bullet will be spawned but stays on one point without any velocity.

Server/Host fires -> everythings fine.

Client fires -> bullet spawned but does not move.

Following i´ll show you a part of the script:

    public bool shootableAngle = false;
    public float bulletSpeed = 6.0f;
    public GameObject bulletPrefab;
    public float bulletRangeTime;

    private void Update()
    {
        if (!isLocalPlayer)
        {
            return;
        }

        if (Input.GetMouseButtonDown(0) && shootableAngle)
        {
            CmdFire();
        }
        
    }

[Command]
    void CmdFire()
    {
        //Instantiate bullet
        GameObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);

        //Look for crosshair child and set direction
        var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 direction = (transform.GetChild(0).gameObject.transform.position - transform.position).normalized;

        //Give some velocity
        bullet.GetComponent<Rigidbody2D>().velocity = direction * bulletSpeed;

        //Spawn over Network
        NetworkServer.Spawn(bullet);


        //Destroy after given time
        Destroy(bullet, bulletRangeTime);
    }

Thank you for your effort! :-)

1

1 Answers

0
votes

You need to call a function on client from the server. Use the:

[ClientRpc]
RpcFireOnClient(){
    //Instantiate bullet
        GameObject bullet = Instantiate(bulletPrefab, transform.position, 
        transform.rotation);

        //Look for crosshair child and set direction
        var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 direction = 
         (transform.GetChild(0).gameObject.transform.position - 
        transform.position).normalized;

        //Give some velocity
        bullet.GetComponent<Rigidbody2D>().velocity = direction * bulletSpeed;

        //Spawn over Network
        NetworkServer.Spawn(bullet);


        //Destroy after given time
        Destroy(bullet, bulletRangeTime);
}

And call it from the:

[Command]
    void CmdFire()
    {
       RpcFireOnClient();
    }

I hope it helps, i am learning it right now and do not know if it is totally true. But give it a try!

Cheers