0
\$\begingroup\$

I am making a multiplayer game with prefab shooting, but unfortunately the prefab sometimes spawns in the wrong position when I shoot from a client. The bullet tends to spawn in a location where the player was a few miliseconds ago, making that the bullet sometimes spawns inside of the player which killing the player in the process.

For shooting, I currently have this code setup to instantiate the bullet

void Update() {
    if (Input.GetMouseButtonDown(0)) {
        float angle = GetComponentInChildren<Weapon>().angle;
        CmdShootBullet(angle);
        rigidbody.AddForce(Quaternion.AngleAxis(angle + 180, Vector3.forward) * Vector3.right * (bulletPrefab.GetComponent<Bullet>().force / 7.5f));
    }
}

[Command]
void CmdShootBullet (float angle) {
    GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);
    Bullet bulletScript = bullet.GetComponent<Bullet>();
    bulletScript.shotBy = gameObject;
    bullet.GetComponent<Rigidbody>().AddForce(Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.right * bulletScript.force);
    NetworkServer.Spawn(bullet);
}

And this is the setup for the location of the player and the gun. The top one is the player, the bottom is the gun.

enter image description here

My guess is that it has to do with lag, that the player position does not update soon enough, so how would I make it that the bullet spawns in the position of the player in the client rather than the position of the player in the host?

\$\endgroup\$
  • \$\begingroup\$ I don't think you want to do that. I think you should just fix the 'bullet kills player' problem. you should fire the bullet from the correct position (which is the one the server thinks your player is in) otherwise a lagging player could jump out of cover, and shoot without ever being seen by their opponent. \$\endgroup\$ – JeffUK Jan 16 at 13:54
  • \$\begingroup\$ have you tried syncing to the transform instead of the rigidbody? also increasing the network send rate will help. I would double it for player and almost max it for the faster moving objects such as a bullet. \$\endgroup\$ – Justin Markwell Jan 16 at 15:11
  • \$\begingroup\$ @JeffUK Alright, but how can I get the position the server thinks the player is in? \$\endgroup\$ – FlorisdG Jan 16 at 15:50
  • \$\begingroup\$ @JustinMarkwell Doesn't seem to work. If the player is falling down and shoots bellow him, the bullet spawns inside of him \$\endgroup\$ – FlorisdG Jan 16 at 15:50
  • \$\begingroup\$ @FlorisdG isn't that firepoint.position? \$\endgroup\$ – JeffUK Jan 16 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.