Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Bug Camera Panning Bug

Discussion in 'Unity Hub' started by Myst1cS04p, Feb 4, 2024.

  1. Myst1cS04p

    Myst1cS04p

    Joined:
    Oct 10, 2022
    Posts:
    17
    So I wrote a script to pan around the camera when I right click, but there is an issue that i cant seem to figure out; the camera keeps on changing positions between 2 different points for seemingly no reason
    Here's the script
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.InputSystem;
    3. using UnityEngine.Events;
    4.  
    5. public class CameraMovement : MonoBehaviour
    6. {
    7.     [SerializeField] private Vector3 dragOrigin;
    8.     [SerializeField] private bool isDragging;
    9.     [SerializeField] private InputActionReference mouseClick;
    10.     public UnityAction onMoveCamera;
    11.  
    12.     private void OnEnable()
    13.     {
    14.         mouseClick.action.started += Drag;  
    15.         mouseClick.action.canceled += Drag;  
    16.     }
    17.     private void OnDisable()
    18.     {
    19.         mouseClick.action.started -= Drag;
    20.         mouseClick.action.canceled -= Drag;
    21.     }
    22.  
    23.     private void Drag(InputAction.CallbackContext context)
    24.     {
    25.         if (context.started)
    26.         {
    27.             isDragging = true;
    28.             dragOrigin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    29.             onMoveCamera?.Invoke();
    30.         }
    31.         else if (context.canceled)
    32.         {
    33.             isDragging = false;
    34.         }
    35.     }
    36.  
    37.     private void Update()
    38.     {
    39.         if(isDragging)
    40.         {
    41.             Vector3 move = dragOrigin - Camera.main.ScreenToWorldPoint(Input.mousePosition);
    42.             move.z = -10;
    43.             Camera.main.transform.position = move;
    44.         }
    45.     }
    46. }
    47.  
    Here's some footage of the behaviour