DrOmega
DrOmega

Reputation: 31

Unity , script to drag camera

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

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragMap : MonoBehaviour {
private float dist;
private Vector3 MouseStart;
private Vector3 derp;

void Start () {
    dist = transform.position.z;  // Distance camera is above map
}

void Update () {
    if (Input.GetMouseButtonDown (2)) {
        MouseStart = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        MouseStart = Camera.main.ScreenToWorldPoint (MouseStart);
        MouseStart.z = transform.position.z;

    } 
    else if (Input.GetMouseButton (2)) {
        var MouseMove = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        MouseMove = Camera.main.ScreenToWorldPoint (MouseMove);
        MouseMove.z = transform.position.z;
        transform.position = transform.position - (MouseMove - MouseStart);
    }
}
}

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.

Upvotes: 0

Views: 7913

Answers (2)

GreatnessGamers
GreatnessGamers

Reputation: 21

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragMap : MonoBehaviour {
private float dist;
private Vector3 MouseStart;
private Vector3 derp;

void Start () {
    dist = transform.position.z;  // Distance camera is above map
}

void Update () {
    if (Input.GetMouseButtonDown (2)) {
        MouseStart = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        MouseStart = Camera.main.ScreenToWorldPoint (MouseStart);
        MouseStart.z = transform.position.z;

    } 
    else if (Input.GetMouseButton (2)) {
        var MouseMove = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        MouseMove = Camera.main.ScreenToWorldPoint (MouseMove);
        MouseMove.z = transform.position.z;
        transform.position = transform.position - (MouseMove - MouseStart);
    }
}
}

there is an easy fix here. if you want to flip both the x and the y, replace "- (MouseMove - MouseStart)" with "+ (MouseMove - MouseStart)"

Upvotes: 1

NullEntity
NullEntity

Reputation: 152

You need to negate the x of the MouseMove vector to only flip the x movement:

MouseMove = new Vector3(-MouseMove.x, MouseMove.y, MouseMove.z);

Upvotes: 1

Related Questions