- Home /
Move forward relative to a specific camera when two cameras are present
I am making a split screen co-op game so my scene has two camera in it, one for player one the other for player two. I want to move the objects relative to their respective cameras. The code I am using is below:
public float speed = 6.5f; // Update is called once per frame
void FixedUpdate()
{
if (Input.GetAxis("RightStickVertical") < 0f)
{
rigidbody.AddTorque(Camera.main.transform.right * speed);
}
else if (Input.GetAxis("RightStickVertical") > 0f)
{
rigidbody.AddTorque(Camera.main.transform.right * -speed);
}
else if (Input.GetAxis("RightStickHorizontal") > 0f)
{
rigidbody.AddTorque(Camera.main.transform.forward * -speed);
}
else if (Input.GetAxis("RightStickHorizontal") < 0f)
{
rigidbody.AddTorque(Camera.main.transform.forward * speed);
}
}
I have used the Camera.main.transform.right for this, however since I don't have a main camera, because I have two, I get a null reference as expected. Therefore my question is how do I set it for a specific camera in the scene?
The camera names are ballCamera and boxCamera.
I am using a xbox 360 controller.
Answer by robertbu · Nov 02, 2014 at 05:31 PM
The use of Main.camera depends on the tag on the camera, not the name. So you should be able to use select one of the cameras and set its tag to 'MainCamera'. Or you can use a variable you assign in start:
private Transform camTrans;
void Start() {
camTrans = GameObject.Find("ballCamera").transform;
}
...and then your code would do:
rigidbody.AddTorque(camTrans.forward);
Thank you so much this has fixed the problem and works perfectly.
Your answer
Follow this Question
Related Questions
Local Multiplayer, Player Sign In c# 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Multiplayer - Spawn in the last position 1 Answer
Tell the NetworkManager to spawn individual playerPrefab from Client 0 Answers