Search Unity

Camera dragging with mouse

Discussion in 'Scripting' started by DrOmega, Apr 30, 2017.

  1. DrOmega

    DrOmega

    Joined:
    Apr 27, 2017
    Posts:
    2
    I have 2D mesh in the XY plane. I have the following script which moves the camera across the plane, the camera starts at (0,0,-10).

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class DragMap : MonoBehaviour {
    5.     private float dist;
    6.     private Vector3 MouseStart;
    7.     private Vector3 derp;
    8.     void Start () {
    9.         dist = transform.position.z;  // Distance camera is above map
    10.     }
    11.     void Update () {
    12.         if (Input.GetMouseButtonDown (2)) {
    13.             MouseStart = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
    14.             MouseStart = Camera.main.ScreenToWorldPoint (MouseStart);
    15.             MouseStart.z = transform.position.z;
    16.         }
    17.         else if (Input.GetMouseButton (2)) {
    18.             var MouseMove = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
    19.             MouseMove = Camera.main.ScreenToWorldPoint (MouseMove);
    20.             MouseMove.z = transform.position.z;
    21.             transform.position = transform.position - (MouseMove - MouseStart);
    22.         }
    23.     }
    24. }
    But I cannot for the life of me figure out what to change so that if I drag my mouse to the right, the camera goes to the left and vice versa. Similarly if I drag my mouse up I want to move the camera down and vice versa. Help!

    Thank you for any replies.

    -DrOmega.
     
  2. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,089
    When you use '(MouseMove - MouseStart)' you create a delta vector that shows the difference between where you started and where the mouse is now. You can simply negate the contents of the x and y components to reverse how the camera moves. If you want to negate both you could change it to '(MouseStart - MouseMove)' instead.