Unity學習之實現拖拽功能
阿新 • • 發佈:2019-02-09
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;
}
}
}