Skip to content

Instantly share code, notes, and snippets.

@Matthew-J-Spencer
Created January 25, 2021 13:23
Show Gist options
  • Save Matthew-J-Spencer/65aea3d55f1e2c6ccb2c3586bccbdbdb to your computer and use it in GitHub Desktop.
Save Matthew-J-Spencer/65aea3d55f1e2c6ccb2c3586bccbdbdb to your computer and use it in GitHub Desktop.
A simple drag and drop script for Unity. Follow along: https://youtu.be/Tv82HIvKcZQ
using UnityEngine;
public class Dragger : MonoBehaviour {
private Vector3 _dragOffset;
private Camera _cam;
[SerializeField] private float _speed = 10;
void Awake() {
_cam = Camera.main;
}
void OnMouseDown() {
_dragOffset = transform.position - GetMousePos();
}
void OnMouseDrag() {
transform.position = Vector3.MoveTowards(transform.position, GetMousePos() + _dragOffset, _speed * Time.deltaTime) ;
}
Vector3 GetMousePos() {
var mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
return mousePos;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment