/*
首先说一下,Input.mousePosition是鼠标所在像素平面内的坐标,需要根据自己的需求转变成世界坐标。
Description 描述
The current mouse position in pixel coordinates. (Read Only)
在屏幕坐标空间当前鼠标的位置(只读)。
The bottom-left of the screen or window is at (0, 0). The top-right of the screen or window is at (Screen.width, Screen.height).
屏幕或窗口的左下角是坐标系的(0,0)坐标。右上角的坐标是(屏幕宽度值,屏幕高度值)。
*/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| private bool isMouseDown; private Vector3 lastMousePosition = Vector3.zero; private void TwoDMove() { if (Input.GetMouseButtonDown(0)) { isMouseDown = true; } if (Input.GetMouseButtonUp(0)) { isMouseDown = false; lastMousePosition = Vector3.zero; } if (isMouseDown) { if (lastMousePosition != Vector3.zero) { Vector3 offset = Camera.main.ScreenToWorldPoint(Input.mousePosition) - lastMousePosition; transform.position += offset; } lastMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
} }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| private void RayMove() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (isMouseDown) { if (Physics.Raycast(ray, out hit)) { Vector3 offset = Input.mousePosition; hit.transform.position = new Vector3(hit.point.x, hit.point.y, hit.transform.position.z); Debug.DrawLine(ray.origin, hit.point); } }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
IEnumerator OnMouseDown() { Vector3 ScreenSpace = Camera.main.WorldToScreenPoint(transform.position); Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, ScreenSpace.z)); Debug.Log("down"); while (Input.GetMouseButton(0)) { Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, ScreenSpace.z); Vector3 CurPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset; transform.position = CurPosition; yield return new WaitForFixedUpdate(); } }
|