不BB了,直接上代码
using UnityEngine; using System.Collections; public class Hero : MonoBehaviour { private bool isMouseDown = false; private Vector3 lastMousePosition = Vector3.zero; public Transform hero; void Start(){ } // Update is called once per frame void Update () { if(Input.GetMouseButtonDown(0)){ isMouseDown=true; } if(Input.GetMouseButtonUp(0)){ isMouseDown=false; lastMousePosition = Vector3.zero; } if(isMouseDown){ if(lastMousePosition!=Vector3.zero){ //Camera.main.ScreenToWorldPoint(Input.mousePosition) //print (Camera.main.ScreenToWorldPoint(Input.mousePosition)); Vector3 offset = Camera.main.ScreenToWorldPoint(Input.mousePosition) -lastMousePosition; transform.position = transform.position+offset; checkPosition(); } lastMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); } } private void checkPosition(){ //check y -3.3f +3.3f //check x -1.9f +1.9f Vector3 pos = transform.position; float x = pos.x; float y = pos.y; if(y<-3.3f){ y=-3.3f; } if(y>3.3f){ y=3.3f; } if(x<-1.9f){ x=-1.9f; } if(x>1.9f){ x=1.9f; } transform.position= new Vector3(x,y,0); } }
再将脚本挂在要移动的物体上,拖一下game object到Transform hero既可。
最后效果如下:
这个虽然好,但是没有考虑到摄像机透视效果的问题,摄像机切换成透视模式,这个方法就完全不能用了啊