【Unity】オブジェクト ドラッグで移動

オフセットの部分は、ベクトルで考えるとわかりやすい。

using UnityEngine;
using System.Collections;

public class PieceManager : MonoBehaviour {

	private bool isDrag = false;

	enum STEP{
		NONE = -1,
		IDLE = 0,
		DRAGGING,
	}
	// 初期状態
	private STEP step = STEP.IDLE;
	private STEP stepNext = STEP.NONE;

	private Vector3 screenPoint;
	private Vector3 offset;

	// シングルトーン
	public static PieceManager instance = null;
	void Awake(){
		if(instance == null){
			instance = this;
		}
	}
	void Start () {
	}
	void Update () {

		// 状態別で管理する。
		// 状態は2つである。
		switch(step){
		case STEP.IDLE:
			if(this.isDrag){
				this.stepNext = STEP.DRAGGING;
			}
			break;
		case STEP.DRAGGING:
			if(!this.isDrag){
				this.stepNext = STEP.IDLE;
			}
			break;
		}

		while(this.stepNext != STEP.NONE){
			this.step = this.stepNext;
			this.stepNext = STEP.NONE;
			switch (this.step){
			case STEP.DRAGGING:
				print("start drag "+ this.name);
				this.beginDragging();
				break;
			case STEP.IDLE:
				print("end drag "+ this.name);
				break;
			}
		}
		switch(this.step){
		case STEP.DRAGGING:
			this.doDragging();
			break;
		}
	}
	void beginDragging(){
		screenPoint = Camera.main.WorldToScreenPoint(transform.position);
		float x= Input.mousePosition.x;
		float y= Input.mousePosition.y;

		offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(x, y, screenPoint.z));

	}
	void doDragging(){
		float x = Input.mousePosition.x;
		float y = Input.mousePosition.y;

		Vector3 currentScreenPoint = new Vector3(x, y, screenPoint.z);
		Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenPoint) + offset;
		transform.position = currentPosition;
		
	}
	// 物体の上を押したときに呼ばれる。
	void OnMouseDown(){
		this.isDrag = true;
	}
	void OnMouseUp(){
		this.isDrag = false;
	}
}