public class NewBehaviourScript : MonoBehaviour {
public Vector3 screenPosition;
public Vector3 position;
public Vector3 tempPosition;
//以下实现拖拽箱子的变换原理:
void OnMouseDown(){//当鼠标按下时候
screenPosition = Camera .main.WorldToScreenPoint (transform.position );//主相机的屏幕坐标
print (screenPosition);
position = transform .position - Camera .main .ScreenToWorldPoint (new Vector3 (Input .mousePosition.x,Input .mousePosition .y,screenPosition .z));
StartCoroutine (ChangePosition());
}
IEnumerator ChangePosition(){
while (Input.GetMouseButton (0)) {
tempPosition =Camera .main .ScreenToWorldPoint (new Vector3 (Input .mousePosition.x,Input .mousePosition .y,screenPosition .z));
StartCoroutine (ChangePosition());
transform.position =tempPosition +position ;//改变木箱的位置----将当前坐标加上鼠标变幻的值 transform.position(之前的坐标)=transform.position(鼠标移动后的坐标)
yield return null;
}
}
}
public Vector3 screenPosition;
public Vector3 position;
public Vector3 tempPosition;
//以下实现拖拽箱子的变换原理:
//第一步获取屏幕在世界坐标系的z坐标
//第二步将鼠标的屏幕坐标转变为世界坐标,由于屏幕没有z坐标,故将第一步的获得的z 放入此处
//第三步 箱子本来的坐标-鼠标坐标(旧),这里是在onmousedown函数实现 只在按下鼠标的时候实现,意思是按下鼠标后只执行一次
//第四步 将结果 再 加上鼠标坐标(新) 得到的是拖拽后的值
void OnMouseDown(){//当鼠标按下时候
screenPosition = Camera .main.WorldToScreenPoint (transform.position );//主相机的屏幕坐标
print (screenPosition);
position = transform .position - Camera .main .ScreenToWorldPoint (new Vector3 (Input .mousePosition.x,Input .mousePosition .y,screenPosition .z));
StartCoroutine (ChangePosition());
}
IEnumerator ChangePosition(){
while (Input.GetMouseButton (0)) {
tempPosition =Camera .main .ScreenToWorldPoint (new Vector3 (Input .mousePosition.x,Input .mousePosition .y,screenPosition .z));
StartCoroutine (ChangePosition());
transform.position =tempPosition +position ;//改变木箱的位置----将当前坐标加上鼠标变幻的值 transform.position(之前的坐标)=transform.position(鼠标移动后的坐标)
yield return null;
}
}
}