Question by
luk3b · Feb 25, 2018 at 02:24 AM ·
2dnetworkingmultiplayer2d gamenetwork
Why is my script firing 2 bullets on the client side?
So I have a script that fires towards the direction of the cursor, and for some reason on the client side it sees it as firing 2 projectiles, but if you are the host it only shows the single bullet. Also on the client side, it sees the host as shooting 2 projectiles. Sorry if this explanation was confusing, basically the Client sees 2 projectiles for every 1 projectile shot.
My Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class FireProjectileLeftClick : NetworkBehaviour {
public GameObject projectile;
public Transform firePoint;
float projectileSpeed;
bool readyToFire;
// Use this for initialization
void Start() {
projectileSpeed = projectile.GetComponent<Projectile>().projectileSpeed;
readyToFire = true;
}
IEnumerator fired()
{
yield return new WaitForSeconds(0.5f);
readyToFire = true;
}
// Update is called once per frame
void Update() {
if (!isLocalPlayer)
{
return;
}
if (Input.GetButtonDown("Fire1") && readyToFire == true) {
Fire();
readyToFire = false;
StartCoroutine(fired());
}
}
[ClientRpc]
void RpcFire(Vector2 direction, Vector3 worldMousePos)
{
//fire a projectile
GameObject projectileInstance = (GameObject)Instantiate(projectile, firePoint.position + (Vector3)(direction * 1.5f), firePoint.rotation);
projectileInstance.GetComponent<Rigidbody2D>().velocity = direction * projectileSpeed;
//spawn projectile on the server
NetworkServer.Spawn(projectileInstance);
//destroy the object after three seconds
Destroy(projectileInstance, 3f);
Debug.Log("shoot once!");
}
[Command]
void CmdfireProjectile(Vector2 direction, Vector3 worldMousePos)
{
//call rpc client fire function
RpcFire(direction, worldMousePos);
}
void Fire()
{
//tell firepoint where the mouse position is and rotate it
Vector3 worldMousePos = Input.mousePosition;
worldMousePos = Camera.main.ScreenToWorldPoint(worldMousePos);
Vector2 direction = new Vector2(
worldMousePos.x - transform.position.x,
worldMousePos.y - transform.position.y);
firePoint.transform.up = direction;
direction.Normalize();
CmdfireProjectile(direction, worldMousePos);
}
}
Comment
Your answer
Follow this Question
Related Questions
Assign Network Manager an Online Scene with Script 0 Answers
localScale in network 0 Answers
[SOLVED] PhotonNetwork.Instantiate cannot spawn players 0 Answers