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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| public class dragging : MonoBehaviour
{
static public GameObject movingObject;
Vector3 positionZero;
Plane plane;
private void Start()
{
}
void Update()
{
{
if (Input.GetMouseButtonDown(0))
{
Ray mouseRay = GetMouseRay();
RaycastHit hit;
if (Physics.Raycast(mouseRay.origin, mouseRay.direction, out hit))
{
movingObject = hit.transform.gameObject;
plane = new Plane(Vector3.up, movingObject.transform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float rayDistance;
plane.Raycast(ray, out rayDistance);
positionZero = movingObject.transform.position - ray.GetPoint(rayDistance);
}
}
else if (Input.GetMouseButton(0) && movingObject)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float rayDistance;
if (plane.Raycast(ray, out rayDistance))
{
movingObject.transform.position = ray.GetPoint(rayDistance) + positionZero;
}
}
else if (Input.GetMouseButtonUp(0) && movingObject)
{
movingObject = null;
}
}
Ray GetMouseRay()
{
Vector3 mousePositionFar = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.farClipPlane);
Vector3 mousePositionNear = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane);
Vector3 mousePositionF = Camera.main.ScreenToWorldPoint(mousePositionFar);
Vector3 mousePositionN = Camera.main.ScreenToWorldPoint(mousePositionNear);
Ray mouseRay = new Ray(mousePositionN, mousePositionF - mousePositionN);
return mouseRay;
}
// if (capsuleToMagnet.magnetMode == true)
{
var position = new Vector3(
Mathf.RoundToInt(movingObject.transform.position.x),
Mathf.RoundToInt(movingObject.transform.position.y),
Mathf.RoundToInt(movingObject.transform.position.z));
movingObject.transform.position = position;
}
}
} |
Partager