- Home /
Moving the Camera Up and Down by pressing Key
Hey Guys I have the following problem, The Script I have
var lookSpeed = 15.0; var moveSpeed = 15.0; var rotationX = 0.0; var rotationY = 0.0; function Update () { rotationX += Input.GetAxis("Mouse X")*lookSpeed; rotationY += Input.GetAxis("Mouse Y")*lookSpeed; rotationY = Mathf.Clamp (rotationY, -90, 90);
transform.localRotation = Quaternion.AngleAxis(rotationX, Vector3.up);
transform.localRotation *= Quaternion.AngleAxis(rotationY, Vector3.left);
transform.position += transform.forward*moveSpeed*Input.GetAxis("Vertical");
transform.position += transform.right*moveSpeed*Input.GetAxis("Horizontal");
transform.position += transform.up*moveSpeed*Input.GetAxis("Vertical");
transform.position += transform.down*moveSpeed*Input.GetAxis("Horizontal");
only moves the camera in any direction but I need the Camera to move positive along the Y Axis when pressing Q for example and Negative when pressing E. Thx for the Answers =)
Answer by aldonaletto · May 15, 2012 at 12:50 AM
You could replace the movement code (the last 4 lines) with this code:
... transform.position += transform.forward*moveSpeed*Input.GetAxis("Vertical")*Time.deltaTime; transform.position += transform.right*moveSpeed*Input.GetAxis("Horizontal")*Time.deltaTime; var vDir: float = 0; if (Input.GetKey("q")) vDir = 1; if (Input.GetKey("e")) vDir = -1; transform.position += transform.up*moveSpeed*vDir*Time.deltaTime;Notice the multiplication by Time.deltaTime: this makes the movement framerate independent, a very important thing given the wide performance variation among different machines (the velocity moveSpeed means units per second in this case). This isn't necessary in the rotation section, because Mouse X and Mouse Y already give values that compensate the framerate.
Answer by hathol · May 15, 2012 at 12:44 AM
Try this:
if (Input.GetKey(KeyCode.Q))
transform.position += Vector3.up * moveSpeed * Time.deltaTime;
else if (Input.GetKey(KeyCode.E))
transform.position += -Vector3.up * moveSpeed * Time.deltaTime;
Vector3.up (and respectively .forward and .right) gives you a unit vector (direction) in world space coordinates, unlike transform.up which gives you the direction in local space.
Tip: Always multiply your movements with the current delta time to make it framerate independent
Your answer
Follow this Question
Related Questions
How to detect VR camera movement? 0 Answers
How to keep the same position of the object instead of camera 0 Answers
Child GameObject is aligned to world axis and not the parents axis (UPDATE) 1 Answer
Trouble converting transform.position to C# 1 Answer
Any help with prevent camera from passing a specific coordinate? 1 Answer