Skip to content

Instantly share code, notes, and snippets.

@darkon76
Last active April 3, 2023 19:54
Show Gist options
  • Save darkon76/c97c45d1f03f22c0c027bc63d02e24a9 to your computer and use it in GitHub Desktop.
Save darkon76/c97c45d1f03f22c0c027bc63d02e24a9 to your computer and use it in GitHub Desktop.
Unity Drag.
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.
}
}
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 );
}
}
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