I’m trying to where I can pick up and throw items using mirror. Currently I am doing this by deleting the object on the ground and spawning a different non networked prefab into the players hand. To throw the item, The hand item is deleted and a new object is spawned and launched by the server. It works fine on the host, but it breaks on the client. One of the issues is that there is noticeable lag between the object being spawned and it being launched. The other issue is that the object doesn’t seem to always spawn in the right place or launch correctly. The item being thrown is on a separate layer from my player collider, and I tried disabling all of the hitbox colliders on the player, but I still can’t get it to work.
Here’s my code:
[Command]
private void CmdThrow(int i, float itemMass)
{
float throwForce = 7.28f * Mathf.Pow(10f, -0.0623f * itemMass);
if (throwForce > 7) { throwForce = 7f; }
if (throwForce < 3) { throwForce = 3f; }
if (itemMass > 99) { throwForce = 7f; }
GameObject playerWithItem = NetworkIdentity.spawned[netId].gameObject;
Transform newItemContainer = playerWithItem.transform.GetChild(0).GetChild(0).GetChild(2).GetChild(0).GetChild(0).GetChild(2).GetChild(0).GetChild(0).GetChild(1);
Transform _cam = playerWithItem.transform.GetChild(0).GetChild(0).GetChild(2).GetComponentInChildren<Camera>().transform;
Transform arm = playerWithItem.transform.GetChild(0).GetChild(0).GetChild(2).GetChild(0).GetChild(0).GetChild(2).GetChild(0).GetChild(0);
//arm.gameObject.GetComponent<Collider>().enabled = false;
Debug.Log(grounditems[i].name);
//GameObject itemThrown = Instantiate(grounditems[i], playerWithItem.transform.position + _cam.forward, Quaternion.Euler(0,0,0));
GameObject itemThrown = Instantiate(grounditems[i], newItemContainer.position, Quaternion.Euler(0,0,0));
Rigidbody itemRB = itemThrown.GetComponent<Rigidbody>();
NetworkServer.Spawn(itemThrown);
foreach (Collider col in itemThrown.GetComponents<Collider>())
{
foreach (Collider hitBox in playerWithItem.GetComponentsInChildren<Collider>())
{
Physics.IgnoreCollision(hitBox, col, true);
}
}
itemRB.velocity = playerWithItem.GetComponent<Rigidbody>().velocity;
itemThrown.GetComponent<Rigidbody>().AddForce(_cam.forward * throwForce + new Vector3(0f, throwForce / 2, 0f), ForceMode.VelocityChange);
float random = Random.Range(10, 30);
itemThrown.GetComponent<Rigidbody>().AddTorque(new Vector3(random, random, random));
//StartCoroutine(Reconsider(itemThrown));
}