Created
January 25, 2021 13:23
-
-
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
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; | |
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