Created
November 25, 2019 15:39
-
-
Save dyguests/5670c5822df13c685cb679587e683c6e to your computer and use it in GitHub Desktop.
Unity Draggable
This file contains 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
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