- Home /
Drag and Drop w/ Snapping
I have a sprite that can be clicked and dragged around the screen. The sprites need to be placed in such a way that they connect. I've scaled the sprites so that the objects can snap if they are moving in steps of 0.25
The script seems to check that the mouse has moved the correct distance once and continues to move the objet.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Pipe : MonoBehaviour {
private const float X_BOUND = 4.4f;
private const float Y_BOUND = 4.0f;
private const float STEP = 0.25f;
private const float STEP_TEST = 1.5f;
private bool isSelected;
private Vector3 lastMousePos;
private void Update () {
if (isSelected) {
Vector3 newPos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
float yDist = newPos.y - lastMousePos.y;
float xDist = newPos.x - lastMousePos.y;
if ((STEP_TEST <= Mathf.Abs (xDist)) || (STEP_TEST <= Mathf.Abs (yDist))) {
print (Time.deltaTime);
print ("last: " + lastMousePos + " New: " + newPos);
if (newPos.y < lastMousePos.y) {
transform.position += Vector3.down * STEP;
} else if (newPos.y > lastMousePos.y) {
transform.position += Vector3.up * STEP;
}
if (newPos.x < lastMousePos.x) {
transform.position += Vector3.left * STEP;
} else if (newPos.x > lastMousePos.x) {
transform.position += Vector3.right * STEP;
}
lastMousePos = newPos;
}
}
Vector3 clamped = new Vector3 (
Mathf.Clamp (transform.position.x, -X_BOUND, X_BOUND),
Mathf.Clamp (transform.position.y, -Y_BOUND, Y_BOUND)
);
transform.position = clamped;
}
private void OnMouseDown () {
isSelected = true;
PipeManager.selected = this.transform;
}
private void OnMouseUp () {
isSelected = false;
PipeManager.selected = null;
}
public void Snap () {
}
}
Comment
Don't know if this is the cause, but this is suspicious: float xDist = newPos.x - last$$anonymous$$ousePos.y;
. That should probably be last$$anonymous$$ousePos.x
The Sprite moves more s$$anonymous$$dily. However, the mouse cursor seems to lag behind in some cases. Is there a better way to go about doing this?