How to keep cameras Vector3.y Position While Translating it.

I’m trying to create an RTS style camera movement. So I have This script attached to my mainCamera.

using UnityEngine;

using System.Collections;

public class UserInput : MonoBehaviour
{
public float moveSpeed = 50f;

void Update ()
{
										
    if(Input.GetKey(KeyCode.W))
        transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
    
    if(Input.GetKey(KeyCode.S))
        transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);
    
    if(Input.GetKey(KeyCode.A))
        transform.Translate(Vector3.left * moveSpeed * Time.deltaTime);
    
    if(Input.GetKey(KeyCode.D))
        transform.Translate(Vector3.right * moveSpeed * Time.deltaTime);
			
}

}

The Cameras rotation is angled to face slightly down. So when I press my keys, of course, the camera begins heading in the direction it’s facing. How to I have it head in the direction it’s facing but maintain the height of y?

Well if you used .Translate(cccc, Space.World) it would move in world space not based on its angle - which “feels” like what you want. If you can rotate the camera and hence have the buttons need to move relative to the current rotation then you need to store the y coordinate and reset it after.

       var y = transform.position.y;

       //Your input stuff

       var pos = transform.position;
       pos.y = y;
       transform.position = pos; //Note in C# you can't just assign to transform.position.y because Vector3 is a struct and not a class

[META] Fix answer count due to system fault