Camera Controls: Mouse Only

Hello All - Ive modified the code to handle camera controls via mouse inputs only. Main changes are:

  • Press and hold right mouse button to rotate

  • Press and hold scroll wheel to move about

          private void HandleMovement() {
              // Check if right mouse button is down
              if (!Input.GetKey(KeyCode.Mouse2)) {
                  return;
              }
    
              float mouseHorizontalOffset = Input.GetAxis("Mouse X");
              float mouseVerticalOffset = Input.GetAxis("Mouse Y");
    
              // If no movement, early return
              if (mouseHorizontalOffset == 0 && mouseVerticalOffset == 0) {
                  return;
              }
    
              Vector3 inputMoveDirection = Vector3.zero;
    
              if (mouseHorizontalOffset != 0) {
                  inputMoveDirection += mouseHorizontalOffset > 0
                      ? Vector3.right
                      : Vector3.left;
              }
    
              if (mouseVerticalOffset != 0) {
                  inputMoveDirection += mouseVerticalOffset > 0
                      ? Vector3.forward
                      : Vector3.back;
              }
    
              Vector3 moveVector = transform.forward * inputMoveDirection.z + transform.right * inputMoveDirection.x;
              transform.position += moveVector * Time.deltaTime * MOVE_SPEED;
          }
    
          private void HandleRotation() {
              // Check if wheel mouse button is down
              if (!Input.GetKey(KeyCode.Mouse1)) {
                  return;
              }
    
              float mouseHorizontalOffset = Input.GetAxis("Mouse X");
    
              // If no movement, early return
              if (mouseHorizontalOffset == 0) {
                  return;
              }
    
    
            Vector3 rotationVectorAdjustment = mouseHorizontalOffset > 0
                 ? Vector3.up
                 : Vector3.down;
    
            transform.eulerAngles += rotationVectorAdjustment * Time.deltaTime * ROTATION_SPEED;
          }
    
          private void HandleZoom() {
              float mouseScrollDeltaY = Input.mouseScrollDelta.y;
    
              if (mouseScrollDeltaY == 0) {
                  return;
              }
    
              _followOffset += mouseScrollDeltaY > 0
                  ? Vector3.up
                  : Vector3.down;
    
              _followOffset.y = Mathf.Clamp(_followOffset.y, MIN_FOLLOW_Y_OFFSEET, MAX_FOLLOW_Y_OFFSEET);
    
              _cinemachineTransposer.m_FollowOffset = Vector3
                  .Lerp(_cinemachineTransposer.m_FollowOffset, _followOffset, Time.deltaTime * ZOOM_SPEED);
          }
5 Likes

Well done!

1 Like

just invert the > 0 checks (to < 0) if you wanna change direction of movement / rotation

1 Like

Privacy & Terms