//ドラッグで動かしたいオブジェクトにアタッチ
using UnityEngine;
public class DragTest : MonoBehaviour
{
Vector2 startPos;
Vector2 screenPos;
Vector2 worldPos;
// Start is called before the first frame update
void Start()
{
}
void Update()
{
if (Input.GetMouseButton(0))
{
startPos = transform.position;
screenPos = Input.mousePosition;
worldPos = Camera.main.ScreenToWorldPoint(screenPos);
float timer = 0.01f;
timer += Time.deltaTime;
transform.position = Vector3.Lerp(startPos, worldPos, timer);
}
}
}
/////////////////////////////////////
//MainCameraにPysics2DRaycasterをアタッチ
//EventSystemをシーンに配置
//ドラッグで動かしたいオブジェクトに
//以下のスクリプトとCollider2Dをアタッチ
using UnityEngine;
using UnityEngine.EventSystems;
//CameraのProjectionはOrthographicに。
public class DragEvent : MonoBehaviour, IDragHandler
{
public void OnDrag(PointerEventData data)
{
Vector3 TargetPos = Camera.main.ScreenToWorldPoint(data.position);
TargetPos.z = 0;
transform.position = TargetPos;
}
}
/////////////////////////////////////
// Collider2D
using UnityEngine;
public class DragAndDrop : MonoBehaviour
{
bool canMove;
bool dragging;
private new Collider2D collider;
// Collider2D collider;
void Start()
{
collider = GetComponent();
canMove = false;
dragging = false;
}
void Update()
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Input.GetMouseButtonDown(0) || Input.touchCount == 1)
{
if (collider == Physics2D.OverlapPoint(mousePos))
{
canMove = true;
}
else
{
canMove = false;
}
if (canMove)
{
dragging = true;
}
}
if (dragging)
{
this.transform.position = mousePos;
}
if (Input.GetMouseButtonUp(0) || Input.touchCount <= 0)
{
canMove = false;
dragging = false;
}
}
}