How to move the Camera(3D)

Hey,
I tried to make a 1st Person game and I have some Problems with the camera movement.
When I press w, the camera should move in x-direction by 1.
How could I do this?

My script so far:

        bool horizontalDir = Input.GetButton("Horizontal1"); //Button W
        bool verticalDir = Input.GetButton("Vertical1"); //Button D
        bool horizontalDirn = Input.GetButton("Horizontal2"); //Button S (n = negative)
        bool verticalDirn = Input.GetButton("Vertical2"); //Button A (n = negative)
        bool jump = Input.GetButton("Jump"); //Space
        float camPosX = cam.transform.position.x; //variable with the X-value
        float camPosZ = cam.transform.position.z; //variable with the Z-value
        float camPosY = cam.transform.position.y; //variable with the Y-value
        cam = GetComponent<Camera>();
        if (horizontalDir == true)
        {
            camPosX = Camera.main.gameObject.transform.position.x + moveSpeed; 
        }
        if (verticalDir == true)
        {
            camPosZ = Camera.main.gameObject.transform.position.z + moveSpeed;
        }
        if (horizontalDirn == true)
        {
            camPosX = Camera.main.gameObject.transform.position.x - moveSpeed;
        }
        if (verticalDirn == true)
        {
            camPosZ = Camera.main.gameObject.transform.position.z - moveSpeed;
        }
        if (jump == true)
        {
            camPosY = Camera.main.gameObject.transform.position.y + jumpHeight;
            camPosY = Camera.main.gameObject.transform.position.y - jumpHeight;
        }
        cam.gameObject.transform.position.x = camPosX; //does not work
        cam.gameObject.transform.position.y = camPosY; //does not work
        cam.gameObject.transform.position.z = camPosZ; //does not work

Hi masse0311,
There are a few points to make:

  • Typically, you will want to multiply movement speeds by the framerate (Time.deltaTime).
  • Lines 33 to 35 will not work that way because structs are value types, not references (also see point 4). This means a copy of the camera’s position is being updated- which is not what you are wanting to do here.
  • You could consider using the Unity Character Controller. See here for a tutorial that uses it.
  • If point 2 does not make sense to you, do consider going through some starter tutorials. Scroll to the top of the page and cliick on “Learn”. Lots of good stuff there. :slight_smile:

Thanks for the fast answer. I know that there is already a prefab for the character controller with ist scripts. But where can I find this pre-made prefabs because in the Unity-files there is´t any package?

In the Editor menus try : Assets => Import package => Characters.

That will bring the general asset into your project. Here is a Unity tutorial for the asset.