Camera Movement with Mouse – Unity3D (C#)
This type of camera controller is mostly used in RTS projects. You can move camera with mouse movement. There are two types of camera movement with mouse: Touch the edges of screen or drag the mouse.
In “Drag the Mouse” movement type, player holds right mouse button and drags the mouse to move camera view.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
float speed = 10.0f; void Update () { if (Input.GetMouseButton (1)) { if (Input.GetAxis ("Mouse X") > 0) { transform.position += new Vector3 (Input.GetAxisRaw ("Mouse X") * Time.deltaTime * speed, 0.0f, Input.GetAxisRaw ("Mouse Y") * Time.deltaTime * speed); } else if (Input.GetAxis ("Mouse X") < 0) { transform.position += new Vector3 (Input.GetAxisRaw ("Mouse X") * Time.deltaTime * speed, 0.0f, Input.GetAxisRaw ("Mouse Y") * Time.deltaTime * speed); } } } |
In the second camera movement type, player drags the cursor to edges of the screen. There are four edges so, we should check four possibilities.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
float speed = 10.0f; int boundary = 1; int width; int height; void Start () { width = Screen.width; height = Screen.height; } void Update () { if (Input.mousePosition.x > width - boundary) { transform.position -= new Vector3 (Input.GetAxisRaw ("Mouse X") * Time.deltaTime * speed, 0.0f, 0.0f); } if (Input.mousePosition.x < 0 + boundary) { transform.position -= new Vector3 (Input.GetAxisRaw ("Mouse X") * Time.deltaTime * speed, 0.0f, 0.0f); } if (Input.mousePosition.y > height - boundary) { transform.position -= new Vector3 (0.0f, 0.0f, Input.GetAxisRaw ("Mouse Y") * Time.deltaTime * speed); } if (Input.mousePosition.y < 0 + boundary) { transform.position -= new Vector3 (0.0f, 0.0f, Input.GetAxisRaw ("Mouse Y") * Time.deltaTime * speed); } } |
Both solutions are pretty good, you can use whichever you want.
©Coffee Break Codes – Camera Movement with Mouse – Unity3D (C#)
Thanks for the code! I would add a = in one of the IF so that we are still translating the camera when the user drags vertically (Mouse X displacement can be 0). Otherwise drag behavior is choppy.
… (Input.GetAxis (“Mouse X”) <= 0) …