unity基础开发--鼠标移动物体并判断是否移动

using UnityEngine;
using System.Collections;

public class Comm_MoveGameObject : MonoBehaviour {

    private GameObject mainCamera;
    public static bool moveDown=false;
    public static bool IsMoveGameObject=false;
    private Vector3 currentPos;//初始位置
	// Use this for initialization
	void Start () {

        mainCamera = GameObject.Find("Main Camera");
        currentPos= this.gameObject.transform.position;
	}
    IEnumerator OnMouseDown()
    {

            moveDown = true;
            Vector3 screenSpace = Camera.main.WorldToScreenPoint(transform.position);//三维物体坐标转屏幕坐标
            //将鼠标屏幕坐标转为三维坐标,再算出物体位置与鼠标之间的距离
            Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
            //        print("down");
            while (Input.GetMouseButton(0))
            {
                //屏蔽镜头旋转
                mainCamera.GetComponent().enabled = false;
                //print("button0");
                Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
                Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;

                transform.position = new Vector3(curPosition.x, curPosition.y, curPosition.z);
                yield return new WaitForFixedUpdate();//这个很重要,循环执行
                对物体y进行限制
                //if (transform.position.y <= limit_Y)
                //{
                //    transform.position = new Vector3(curPosition.x,limit_Y,transform.position.z);
                //}
            }
           
        }
    void OnMouseUp() 
    {
        moveDown = false;
        mainCamera.GetComponent().enabled = true;
        //IsGameMove();
    }
	// Update is called once per frame
	void Update () {

        IsGameMove();
	}
    /// 
    /// 判断物体是否移动
    /// 
    void IsGameMove() 
    {
        if (currentPos != this.gameObject.transform.position)
        {
            //currentPos.transform.position
            print("移动了");
            IsMoveGameObject = true;
        }
        else
        {
            print("没有移动");
            IsMoveGameObject =false;
        }
    }
}
脚本放在需要移动的物体上,ok

你可能感兴趣的:(unity基础开发--鼠标移动物体并判断是否移动)