Last active
January 17, 2024 12:51
-
-
Save zonaryFUND/2af97dcb52a9eb2f83c1d91132b418fa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IDropSender { | |
void OnBeginDrag(); | |
bool IsCorrespondingObject(GameObject obj); | |
void OnOverlappingCorrespondingReceiverChange(GameObject receiverObject); | |
void OnDrop(GameObject receiverObject); | |
} | |
public interface IDropReceiver { | |
void OnOverlappingCorrespondingSenderChange(GameObject senderObject); | |
void OnDrop(GameObject senderObject); | |
} | |
public class DragDropSender : MonoBehaviour | |
{ | |
private Vector3 prevPos; | |
private GameObject currentOverlappingReceiver = null; | |
private IDropSender sender; | |
void Awake() { | |
sender = GetComponent<IDropSender>(); | |
} | |
public void OnMouseDown() | |
{ | |
// ドラッグ前の座標を覚えておく | |
prevPos = transform.position; | |
// ドラッグ開始時の処理 | |
sender.OnBeginDrag(); | |
} | |
public void OnMouseDrag() | |
{ | |
// ドラッグ中はオブジェクトをマウスに追従 | |
var currentMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); | |
currentMousePos.z = prevPos.z; | |
transform.position = currentMousePos; | |
// ドラッグ中に下に受信オブジェクトがあるかどうかを判別 | |
var objTarget = GetRecieveObject(); | |
if (objTarget != prevOverObject) | |
{ | |
// オーバーオブジェクトが変更になった場合、通知する | |
sender.OnOverlappingCorrespondingReceiverChange(objTarget); | |
prevOverObject?.GetComponent<IDropReceiver>().OnOverlappingCorrespondingSenderChange(null); | |
objTarget?.GetComponent<IDropReceiver>().OnOverlappingCorrespondingSenderChange(gameObject); | |
} | |
currentOverlappingReceiver = gameObject; | |
} | |
public void OnMouseUp() | |
{ | |
if (currentOverlappingReceiver == null) { | |
// オブジェクトをドラッグ前の位置に戻す | |
transform.position = prevPos; | |
} | |
sender.OnDrop(currentOverlappingReceiver); | |
currentOverlappingReceiver?.OnDrop(gameObject); | |
} | |
private GameObject GetRecieveObject() | |
{ | |
var hitAll = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); | |
foreach (var hit in hitAll) | |
{ | |
if (hit.collider != null) | |
{ | |
var receptor = hit.collider.gameObject; | |
if (receptor != null && sender.IsCorrespondingObject(receptor)) | |
{ | |
return receptor; | |
} | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment