Last active
April 3, 2023 19:54
-
-
Save darkon76/c97c45d1f03f22c0c027bc63d02e24a9 to your computer and use it in GitHub Desktop.
Unity Drag.
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
using UnityEngine; | |
using UnityEngine.EventSystems; | |
public class OrtographicDrag: MonoBehaviour, IDragHandler | |
{ | |
private Camera _mainCamera; | |
public float DistanceToCamera; | |
public void OnDrag(PointerEventData eventData) | |
{ | |
var screenPosition = new Vector3(eventData.position.x, eventData.position.y, DistanceToCamera); | |
var worldPosition = _mainCamera.ScreenToWorldPoint(screenPosition); | |
transform.position = worldPosition; | |
} | |
// Use this for initialization | |
private void Awake() | |
{ | |
_mainCamera = Camera.main; //Cache the camera, micro optimization. | |
} | |
} |
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
using UnityEngine; | |
using UnityEngine.EventSystems; | |
public class PerspectiveDrag: MonoBehaviour, IDragHandler | |
{ | |
private Camera _mainCamera; | |
private Plane _plane; | |
[SerializeField] float Offset = 0; | |
public void OnDrag(PointerEventData eventData) | |
{ | |
var ray = _mainCamera.ScreenPointToRay( eventData.position); | |
float enter; | |
if( _plane.Raycast( ray, out enter ) ) | |
{ | |
var rayPoint = ray.GetPoint(enter); | |
transform.position = rayPoint; | |
} | |
} | |
// Use this for initialization | |
private void Awake() | |
{ | |
_plane = new Plane( Vector3.up, -Offset ); | |
_mainCamera = Camera.main; //Cache the camera, micro optimization. | |
} | |
//If someone changes the offset. | |
private void OnValidate() | |
{ | |
_plane = new Plane( Vector3.up, -Offset ); | |
} | |
} |
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
using System; | |
using UnityEngine; | |
using UnityEngine.EventSystems; | |
public class UIDrag: MonoBehaviour, IDragHandler | |
{ | |
public void OnDrag(PointerEventData eventData) | |
{ | |
transform.position = eventData.position; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment