public class Move : MonoBehaviour {
? ? ?public GameObject cube;? //要拖拽的物體
? ? Vector3 mouseV3;? ? //鼠標
? ? Vector3 screeenV;? //存儲cube的屏幕坐標
? ? Vector3 world;? ? //記錄鼠標坐標轉成的世界坐標
void Update() {
if (Input.GetMouseButtonDown(0)) {
? ? ? ? ? ? ? //當鼠標第一次單擊時記錄下cube在場景中的坐標,并把世界坐標轉成屏幕坐標
? ? ? ? ? ? screeenV= Camera.main.WorldToScreenPoint(cube.transform.position);
}
if (Input.GetMouseButton(0)){
? ? ? ? ? ? ? ? ? ? mouseV3 = Input.mousePosition;? //當鼠標移動時記錄下鼠標的坐標
? ? ? ? ? ? ? ? ? ?mouseV3.z = screeenV.z;? //因為鼠標的z坐標為0,所以需要一個z坐標
? ? ? ? ? ? ? ? ? //把鼠標的屏幕坐標轉換成世界坐標
? ? ? ? ? ? ? ? ? world = Camera.main.ScreenToWorldPoint(mouseV3);
? ? ? ? ? ? ? ? ?//當鼠標移動時,cube也發(fā)生移動,為了讓cube的y軸不發(fā)生移動,設y軸為原來的y軸
? ? ? ? ? ? ? ? ? cube.transform.position = new Vector3(world.x, cube.transform.position.y, world.z);
? ? ? ? ? ? ? ? ?print(cube.transform.position);
? ? ? ? ?}
? ?}
}