以下代码可用于单击并拖动对象:
private void MousePressed(InputAction.CallbackContext context)
{
Vector2 mousePosition = Input.mousePosition;
Vector3 worldPosition = mainCamera.ScreenToWorldPoint(new Vector3(mousePosition.x, mousePosition.y, -mainCamera.transform.position.z));
worldPosition.z = 0;
Collider2D hitCollider = Physics2D.OverlapPoint(worldPosition);
if (hitCollider != null)
{
StartCoroutine(DragUpdate(hitCollider.gameObject));
}
}
private IEnumerator DragUpdate(GameObject clickedObject)
{
float initialDistance = Vector3.Distance(clickedObject.transform.position, mainCamera.transform.position);
clickedObject.TryGetComponent<Rigidbody2D>(out var rb);
while (mouseClick.ReadValue<float>() != 0) {
Ray ray = mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue());
if (rb != null) {
Vector3 direction = ray.GetPoint(initialDistance) - clickedObject.transform.position;
rb.velocity = direction * mouseDragPhysicsSpeed;
yield return waitForFixedUpdate;
} else {
clickedObject.transform.position = Vector2.SmoothDamp(clickedObject.transform.position, ray.GetPoint(initialDistance), ref velocity, mouseDragSpeed);
yield return null;
}
}
}
问题是对象首先移动,使其中心位于光标上。如何保持初始偏移量,以便光标相对于对象保持在与第一次开始拖动时相同的位置?
我愿意接受任何其他改进此代码的建议 - 我是 Unity/C# 的新手。谢谢!
要在拖动过程中保持光标相对于对象的初始偏移,只需进行以下更改:
1- 在 MousePressed 中,捕获初始偏移量并将其传递给协程:
StartCoroutine(DragUpdate(hitCollider.gameObject, worldPosition - hitCollider.transform.position));
2- 更新 DragUpdate 签名以接受偏移参数:
private IEnumerator DragUpdate(GameObject clickedObject, Vector3 initialOffset)
3- 在 DragUpdate 中计算 targetPosition 时应用偏移量:
Vector3 targetPosition = ray.GetPoint(initialDistance) - initialOffset;
这些更改将保持光标相对于对象的初始位置。