- Home /
Moving the camera?
I have been attempting to allow the player to move their Camera through wasd. Since I am new to Unity I am kind of in a pickle here so to speak. Here is the code:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
void Start () {
}
void Update () {
// To move the Camera get the players key.
if (string.ReferenceEquals(Input.anyKeyDown, "w")){
UnityEngine.GameObject.Main_Camera.Translate(Vector3.up);
}
if (string.ReferenceEquals(Input.anyKeyDown, "s")) {
UnityEngine.GameObject.Main_Camera.Translate(Vector3.down);
}
if (string.ReferenceEquals(Input.anyKeyDown, "a")) {
UnityEngine.GameObject.Main_Camera.Translate(Vector3.right);
}
if (string.ReferenceEquals(Input.anyKeyDown, "d")) {
UnityEngine.GameObject.Main_Camera.Translate(Vector3.left);
}
}
}
The output is that Main Camera is not a defined object.
Answer by tanoshimi · Dec 09, 2013 at 03:43 PM
Try this instead - if you want to make the speed of movements framerate-independent (which, generally, you always do), you should always adjust any movements by the amount of time which has passed since the last frame, which is what the * Time.deltaTime term is for :
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.W)){
Camera.main.transform.Translate(Vector3.up * Time.deltaTime);
}
if(Input.GetKey(KeyCode.S)){
Camera.main.transform.Translate(Vector3.down * Time.deltaTime);
}
if(Input.GetKey(KeyCode.A)){
Camera.main.transform.Translate(Vector3.right * Time.deltaTime);
}
if(Input.GetKey(KeyCode.D)){
Camera.main.transform.Translate(Vector3.left * Time.deltaTime);
}
}
}
Answer by robertbu · Dec 09, 2013 at 03:37 PM
Assuming you haven't changed the main camera's tag, you can reference the camera by Camera.main. So to translate you can do:
Camera.main.transform.Translate(Vector3.up);
Also for capturing your board events consider:
if (Input.GetKeyDown(KeyCode.A))
@tanoshimi - his code is looking for a key down and to translate 1 unit when pressed. You wouldn't want to use Time.deltaTime if this is the intended behavior. He may very well want a continuous/smooth move like you've coded, in which case Time.deltaTime is important.
@robertbu - Good point. I was assu$$anonymous$$g the intention of the code was to create continuous movement and therefore changed Get$$anonymous$$eyDown-> Get$$anonymous$$ey and added deltaTime, second-guessing that the next question would be "how come it doesn't carry on moving when I hold the key down".... ;)