- Home /
Multiplayer Game Player Camera not Working
I am trying to create a multiplayer game with two players where each requires their own camera. The can't simply be parented to the player because I don't want Player rotation to affect the camera.
Right now it works when there is one host and no clients. When there is both a host and client, the cameras follow the client player in both games.
I have looked about and have found results such as http://answers.unity3d.com/questions/1157437/making-my-camera-follow-player-in-multiplayer.html where I used jah0's reply as a starting point but I seem to have gotten stuck
I also looked at https://forum.unity3d.com/threads/network-camera-multiplayer.73162/ and some info on the API https://docs.unity3d.com/ScriptReference/Network.OnNetworkInstantiate.html
Here is the code I am currently using
using UnityEngine;
public class CameraFollow : MonoBehaviour {
public Transform playerTransform; //always gets the same player, use an array instead
public int depth = 8;
public int height = 10; //y component
// Update is called once per frame
void Update() {
if (playerTransform != null) {
transform.position = new Vector3(playerTransform.position.x - depth, height, 0);
}
}
public void SetTarget(Transform target) {
playerTransform = target;
}
}
Here is what I'm doing with the player (excerpt)
public override void OnStartLocalPlayer() {
Camera.main.GetComponent<CameraFollow>().SetTarget(gameObject.transform);
}
I appreciate any and all help.
Answer by weimaraner · Aug 09, 2017 at 04:06 PM
I found out that it helps to deactivate and reactivate the new spawned camera in OnStartLocalPlayer().
public override void OnStartLocalPlayer() {
Invoke ("ReactivateCam", 0.5f);
}
void ReactivateCam(){
this.gameObject.GetComponentInChildren<Camera> ().enabled = false;
this.gameObject.GetComponentInChildren<Camera> ().enabled = true;
}
I don't know why, but at my project it only worked when I had a bit of delay (Invoke...).
Hope this helped...
Answer by apachesquirrel · Aug 09, 2017 at 04:20 PM
I think you need to look into IsLocalPlayer in order to check that scripts which control your character, and associated camera is only running on the client instance.
https://www.youtube.com/watch?v=ywbdVTRe-aA
This is an old video, but it will show you how to convert a single player into multiplayer game, including cam tracking.