unity 拖动物体移动



常见的方法,脚本如下:

using UnityEngine;
using System.Collections;

public class TestMove : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
		StartCoroutine (OnMouseDown ());
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	IEnumerator OnMouseDown()
	{
		
		//将物体由世界坐标系转换为屏幕坐标系
		Vector3 screenSpace = Camera.main.WorldToScreenPoint (transform.position);//三维物体坐标转屏幕坐标
		//完成两个步骤 1.由于鼠标的坐标系是2维,需要转换成3维的世界坐标系 
		//    //             2.只有3维坐标情况下才能来计算鼠标位置与物理的距离,offset即是距离
		//将鼠标屏幕坐标转为三维坐标,再算出物体位置与鼠标之间的距离
		Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
		while (Input.GetMouseButton (0)) {
			//得到现在鼠标的2维坐标系位置
			Vector3 curScreenSpace = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
			//将当前鼠标的2维位置转换成3维位置,再加上鼠标的移动量
			Vector3 curPosition = Camera.main.ScreenToWorldPoint (curScreenSpace) + offset;
			//curPosition就是物体应该的移动向量赋给transform的position属性
			transform.position = curPosition;
			Debug.Log ("move the points");
			yield return new WaitForFixedUpdate (); //这个很重要,循环执行
		}
	}
}

unity 对拖拽物体有了定义后这段代码可以变得更加简单,道理是一样,代码如下:

     using UnityEngine;
     using System.Collections;
     
     [RequireComponent(typeof(MeshCollider))]
     
     public class DragObj : MonoBehaviour 
     {
     
     private Vector3 screenPoint;
     private Vector3 offset;
     

	void Start(){
	}

     void OnMouseDown()
     {
         screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
     
         offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
     
     }
     
     void OnMouseDrag()
     {
         Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
     
     Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
     transform.position = curPosition;
     
     }
     
     }
两个脚本任取一个挂载在需要移动的物体上都可以实现拖动鼠标移动物体的功能。

你可能感兴趣的:(unity)