Camera Movement with Mouse – Unity3D (C#)


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.

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.

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#)


Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “Camera Movement with Mouse – Unity3D (C#)

  • Alex

    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) …