Hi,
Iam new to the networking and unet. What Iam trying to achieve is this. Spawn the cube with rigidbody2d and allow players to push/shoot it by .AddForce(). Problem is that just the host can shoot but not the clients. Dont know if to use Command, ClientRpc or something else.
So my spawn script works great. cubeSpawner have network identity with Server Only checked.
public class cubeSpawner : NetworkBehaviour
{
public GameObject cube;
public Transform cubeSpawn;
void Start ()
{
CmdSpawnTheCube (cubeSpawn.position, cubeSpawn.rotation);
}
[Command]
void CmdSpawnTheCube (Vector3 pos, Quaternion rot)
{
GameObject _cube = (GameObject)Instantiate (cube, pos, rot);
NetworkServer.Spawn (_cube);
}
}
cube have attached network identity, network transform and rigidbody2d.
player can charge energy and shoot the cube when is near, my code
public class playerController : NetworkBehaviour
{
public bool haveCube;
public Transform cube;
public float regenerationForce;
float relativeForce = 0f;
bool isCharging;
void Update ()
{
if (!isLocalPlayer) {
return;
}
if (Input.GetButtonDown ("Fire1") && cube) {
isCharging = true;
}
if (Input.GetButtonUp ("Fire1")) {
isCharging = false;
}
if (isCharging) {
relativeForce += Time.deltaTime * regenerationForce;
relativeForce = Mathf.Clamp01 (relativeForce);
} else if (relativeForce > 0.1f) {
CmdFire ();
}
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "cube") {
haveCube = true;
cube = other.transform;
}
}
void OnTriggerExit2D (Collider2D other)
{
if (other.gameObject.tag == "cube") {
haveCube = false;
cube = null;
}
}
}
[Command]
void CmdFire ()
{
Vector3 sp = Camera.main.WorldToScreenPoint (transform.position);
Vector3 dir = (Input.mousePosition - sp).normalized;
if (cube != null) {
cube.GetComponent<Rigidbody2D> ().AddForce (dir * (relativeForce * 700));
}
relativeForce = 0f;
}
}
This works on host but not on clients. Should I use ClientRpc or is there another error?
Thanks so much for the answer.