Camera follow mouse around the map

Hello there.
So i am trying to make the camera follow the mouse.
But when i did this:

using UnityEngine;
using System.Collections;

public class CamMouse : MonoBehaviour {

void Update () {
    transform.position = Input.mousePosition;
}
}

That worked fine with moving to the sides.
But it zooms in and out when moving the mouse up and down.

So then i figured that this will work:

using UnityEngine;
using System.Collections;

public class CamMouse : MonoBehaviour {

void Update () {
    transform.position.x = Input.mousePosition.x;
transform.position.z = Input.mousePosition.y;
}
}

But that isnt working either.

So how do i fix this?

  • Frederik

Hi !

You have to create a new vector to assign the new position

public class CamMouse : MonoBehaviour
{
    public void Update()
    {
        transform.position = new Vector3(
              Input.mousePosition.x,
              Input.mousePosition.y,
              0);
    }
}

create a Vector3 temporary variable first, then use that to assign a value to transform.position.

using UnityEngine;
using System.Collections;

public class CamMouse : MonoBehaviour {

    void Update () {
        //transform.position.x = Input.mousePosition.x;
        //transform.position.z = Input.mousePosition.y; 
        // error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position'. 
        // Consider storing the value in a temporary variable

        Vector3 thePos = new Vector3( Input.mousePosition.x, transform.position.y, Input.mousePosition.y ); // temporary variable
        transform.position = thePos;
    } 
}