I have this little script for dragging object in my level editor:
using UnityEngine;
using System.Collections;
public class DragTile : MonoBehaviour {
//declaring some variables
private bool mousedwn;
private Vector3 oldMousePosition;
private float traveleddistX,traveleddistY = 0;
void OnMouseDown() {
if (!GameData.freemove){
mousedwn = true;
}
}
void OnMouseUp() {
mousedwn = false;
}
void Start(){
oldMousePosition = Input.mousePosition;
}
// Update is called once per frame
void Update () {
if (!GameData.freemove){
if ((mousedwn) && (Input.GetMouseButton(0))){
if (Input.GetButton("Control")){
if ((this.oldMousePosition.x<Input.mousePosition.x) && (traveleddistX>=5)){
this.transform.Translate(0.25f,0,0);
traveleddistX = 0;
}
if ((this.oldMousePosition.x>Input.mousePosition.x) && (traveleddistX>=5)){
this.transform.Translate(-0.25f,0,0);
traveleddistX = 0;
}
if ((this.oldMousePosition.y<Input.mousePosition.y) && (traveleddistY>=5)){
this.transform.Translate(0,0,0.25f);
traveleddistY = 0;
}
if ((this.oldMousePosition.y>Input.mousePosition.y) && (traveleddistY>=5)){
this.transform.Translate(0,0,-0.25f);
traveleddistY = 0;
}
} else {
//this.transform.Translate(Input.GetAxis("Mouse X"),0,Input.GetAxis("Mouse Y"),Space.World);
if ((this.oldMousePosition.x<Input.mousePosition.x) && (traveleddistX>=5)){
this.transform.Translate(0.125f,0,0);
traveleddistX = 0;
}
if ((this.oldMousePosition.x>Input.mousePosition.x) && (traveleddistX>=5)){
this.transform.Translate(-0.125f,0,0);
traveleddistX = 0;
}
if ((this.oldMousePosition.y<Input.mousePosition.y) && (traveleddistY>=5)){
this.transform.Translate(0,0,0.125f);
traveleddistY = 0;
}
if ((this.oldMousePosition.y>Input.mousePosition.y) && (traveleddistY>=5)){
this.transform.Translate(0,0,-0.125f);
traveleddistY = 0;
}
}
}
traveleddistX += Mathf.Abs(this.oldMousePosition.x-Input.mousePosition.x);
traveleddistY += Mathf.Abs(this.oldMousePosition.y-Input.mousePosition.y);
oldMousePosition = Input.mousePosition;
}
}
}
Problem is, that it doesn’t take camera’s orientation into consideration. This hurts, because when rotating camera by 180 degrees “tiles” are moving upwards when moving mouse downwards and when rotating camera by 90 deg., moving mouse upwards results in visible movement of left/right.
How to prevent that?
//edit: My editor features freemove camera (think of Minecraft’s Creative mode or fly mod) and I want only move things in x/z plane.