Networking issues with Raycasting and Cameras

So I am working on a bird’s eye view shooter and I am adapting a camera script from a few different resources. So far the camera will not follow my player. I want to make it so that I do not have to attach the Camera to the player as a child.

In addition to that, when I create a build and run it as a client and when I shoot with one player the other player shoots. I have already added the whole if(!isLocalPlayer) thing to the shooting script, so I am not sure why both players shoot.

So I need some feedback on my player movement script and my shooting scripts please!

using UnityEngine;
using UnityEngine.Networking;

public class PlayerMovement : NetworkBehaviour
{

    [SerializeField] float cameraDistance = 16f;
    [SerializeField] float cameraHeight = 16f;

    Transform mainCamera;
    Vector3 cameraOffset;
    public float smoothing = 5f;




    public float speed = 6f;            // The speed that the player will move at.

    Vector3 movement;                   // The vector to store the direction of the player's movement.
    Animator anim;                      // Reference to the animator component.
    Rigidbody playerRigidbody;          // Reference to the player's rigidbody.
    int floorMask;                      // A layer mask so that a ray can be cast just at gameobjects on the floor layer.
    float camRayLength = 100f;          // The length of the ray from the camera into the scene.

    void Awake ()
    {
        // Create a layer mask for the floor layer.
        floorMask = LayerMask.GetMask ("Floor");

        // Set up references.
        anim = GetComponent <Animator> ();
        playerRigidbody = GetComponent <Rigidbody> ();

        cameraOffset = new Vector3 (0f, cameraHeight, -cameraDistance);

        mainCamera = Camera.main.transform;
        MoveCamera ();

    }

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

        // Store the input axes.
        float h = Input.GetAxisRaw ("Horizontal");
        float v = Input.GetAxisRaw ("Vertical");

        // Move the player around the scene.
        Move (h, v);

        // Turn the player to face the mouse cursor.
        Turning ();

        // Animate the player.
        Animating (h, v);

        MoveCamera ();

        Vector3 targetCamPos = transform.position + cameraOffset;

        transform.position = Vector3.Lerp (transform.position, targetCamPos, smoothing * Time.deltaTime);
    }




    void Move (float h, float v)
    {
        // Set the movement vector based on the axis input.
        movement.Set (h, 0f, v);

        // Normalise the movement vector and make it proportional to the speed per second.
        movement = movement.normalized * speed * Time.deltaTime;

        // Move the player to it's current position plus the movement.
        playerRigidbody.MovePosition (transform.position + movement);
    }


    void Turning ()
    {
        // Create a ray from the mouse cursor on screen in the direction of the camera.
        Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);

        // Create a RaycastHit variable to store information about what was hit by the ray.
        RaycastHit floorHit;

        // Perform the raycast and if it hits something on the floor layer...
        if(Physics.Raycast (camRay, out floorHit, camRayLength, floorMask))
        {
            // Create a vector from the player to the point on the floor the raycast from the mouse hit.
            Vector3 playerToMouse = floorHit.point - transform.position;

            // Ensure the vector is entirely along the floor plane.
            playerToMouse.y = 0f;

            // Create a quaternion (rotation) based on looking down the vector from the player to the mouse.
            Quaternion newRotation = Quaternion.LookRotation (playerToMouse);

            // Set the player's rotation to this new rotation.
            playerRigidbody.MoveRotation (newRotation);
        }
    }

    void Animating (float h, float v)
    {
        // Create a boolean that is true if either of the input axes is non-zero.
        bool walking = h != 0f || v != 0f;

        // Tell the animator whether or not the player is walking.
        anim.SetBool ("IsWalking", walking);
    }

    public override void OnStartLocalPlayer()
    {
        GetComponent<MeshRenderer>().material.color = Color.blue;
    }

    void MoveCamera()
    {
        mainCamera.position = transform.position;
        mainCamera.rotation = transform.rotation;
        mainCamera.Translate (cameraOffset);
        mainCamera.LookAt (transform);
    }
}
using UnityEngine;
using UnityEngine.Networking;

public class PlayerShooting : NetworkBehaviour
{
    public int damagePerShot = 20;
    public float timeBetweenBullets = 0.15f;
    public float range = 100f;


    float timer;
    Ray shootRay = new Ray();
    RaycastHit shootHit;
    int shootableMask;
    ParticleSystem gunParticles;
    LineRenderer gunLine;
    AudioSource gunAudio;
    Light gunLight;
    float effectsDisplayTime = 0.2f;


    void Awake ()
    {
        shootableMask = LayerMask.GetMask ("Shootable");
        gunParticles = GetComponent<ParticleSystem> ();
        gunLine = GetComponent <LineRenderer> ();
        gunAudio = GetComponent<AudioSource> ();
        gunLight = GetComponent<Light> ();
    }


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


        timer += Time.deltaTime;

        if(Input.GetButton ("Fire1") && timer >= timeBetweenBullets && Time.timeScale != 0)
        {
            CmdShoot ();
        }

        if(timer >= timeBetweenBullets * effectsDisplayTime)
        {
            DisableEffects ();
        }
    }


    public void DisableEffects ()
    {
        gunLine.enabled = false;
        gunLight.enabled = false;
    }

    [Command]
    void CmdShoot ()
    {
        timer = 0f;

        gunAudio.Play ();

        gunLight.enabled = true;

        gunParticles.Stop ();
        gunParticles.Play ();

        gunLine.enabled = true;
        gunLine.SetPosition (0, transform.position);

        shootRay.origin = transform.position;
        shootRay.direction = transform.forward;

        if(Physics.Raycast (shootRay, out shootHit, range, shootableMask))
        {
            EnemyHealth enemyHealth = shootHit.collider.GetComponent <EnemyHealth> ();
            if(enemyHealth != null)
            {
                enemyHealth.TakeDamage (damagePerShot, shootHit.point);
            }
            gunLine.SetPosition (1, shootHit.point);
        }
        else
        {
            gunLine.SetPosition (1, shootRay.origin + shootRay.direction * range);
        }
    }
}

If any other resources from my project are needed I can definitely include those.

I’m not sure how much useful information you are going to get with this post because it’s so open ended.

Perhaps it would be more useful if you take a video of what IS happening and post that, and if possible, show a picture of a game doing what you want your game to do.

I wasn’t able to upload a video file maybe because of the file type, but here is a picture of whats happening. My player should always be in the middle of the game screen because the camera should be following him but it isn’t.

I have tried multiple different camera follow scripts and none of them are working with my game. Does anyone have any ideas on what it could be?

Firstly, don’t try to move the camera in the player script. That’ll just give you headaches in the long term when you try to do something else with the camera that’s not player related. Instead, create a camera controller script, give it a target to follow, and handle the camera follow logic there.

Secondly, how exactly are you doing your tests? Where are “both players” coming from? It it actually a separate machine? Or two local builds running on the same computer?

I recommend you set all camera references on OnStartLocalPlayer().
If you want camera follows player, only need set the camera transform, child of player gameObject.
The best way to not get problem with cameras is adding when game starts:

public Transform cameraTransform; // Make child gameObject to player prefab, and drag it to this on Inspector.
public Camera cam;

public override void OnStartLocalPlayer()
    {
        cam = cameraTransform.gameObject.AddComponent<Camera>();
    }

And I dont understand how works your game and code for shooting, but all code inside of [Command] function can cause problems, because run only on server, in this case, maybe, when you call CmdShoot(), you are local Player, but you are calling that function on prefab server instance.

The best way to use raycasts and camera moves, is do it on normal functions, and then , sent info to Command function and Rpc function to says other clients.

And your are moving your rigidbody, moving your camera position and moving your position again in the same frame, and last move its based on cam position, if you move your camera to player, and then moves your player, they will be have different positions. Try move your camera on LateUpdate() functions.

I dont know if helps , if you share your proyect i can try to see the problem , im sure its easy solution, but I dont understand how works

Whats the best way to share my project?

You can use collaborate services. window/services/Collab. On member section, invite me to user, not manager, and I will be see your proyect but not apply changes, dont worry. Or you can zip you project folder and upload to MEGA and share link.

I send you my e-mail to private message for share your link or invite to collab.

If you invite me to the project collab, you have to upload files