Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@dyguests
Created November 25, 2019 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyguests/5670c5822df13c685cb679587e683c6e to your computer and use it in GitHub Desktop.
Save dyguests/5670c5822df13c685cb679587e683c6e to your computer and use it in GitHub Desktop.
Unity Draggable
using UnityEngine;
namespace Game.Model
{
/// <summary>
/// 有可拖拽的
/// </summary>
public class Draggable : MonoBehaviour
{
private float startPosX;
private float startPosY;
private bool isBeingHeld = false;
private void Update()
{
if (isBeingHeld)
{
Vector3 mousePos;
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
gameObject.transform.localPosition = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, 0);
}
}
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePos;
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
startPosX = mousePos.x - gameObject.transform.localPosition.x;
startPosY = mousePos.y - gameObject.transform.localPosition.y;
isBeingHeld = true;
}
}
private void OnMouseUp()
{
isBeingHeld = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment