How To Drag and Drop a 2D Object
Learn how to drag a 2D object with the mouse. In this tutorial we will create at general drag and drop script you can use on any sprite.
❤️ Subscribe to Oxmond Tutorials. Stay ahead of the game:
https://bit.ly/SubscribeOxmondTutorials
✅ Download the free Japanese Dishes sprites here:
https://assetstore.unity.com/packages/2d/textures-materials/food/japanese-dishes-82383?aid=1100l4p9k
✅ Other Free Assets in the Unity Assets Store:
https://assetstore.unity.com/lists/top-free-packages-13201?aid=1100l4p9k
😷👕 Need a face mask / developer T-shirt? Drop by our shop and get a 20% DISCOUNT on your first purchase by using the discount code OXMONDSALE. Click here:
https://shop.oxmond.com/discount/OXMONDSALE
The DragAndDrop script:
/* .-------. .--. .-------. .--. .--. .--. | |--.--.--------.-----.-----.--| | |_ _|--.--| |_.-----.----|__|---.-| |-----. | - |_ _| | _ | | _ | | | | | | _| _ | _| | _ | |__ --| |_______|__.__|__|__|__|_____|__|__|_____| |___| |_____|____|_____|__| |__|___._|__|_____| © 2019 OXMOND / www.oxmond.com */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class DragAndDrop : MonoBehaviour { private bool isDragging; public void OnMouseDown() { isDragging = true; } public void OnMouseUp() { isDragging = false; } void Update() { if (isDragging) { Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; transform.Translate(mousePosition); } } }
Tags In
2D
Beginner Tutorial - Unity 2019
coding pirates
development
drag
drag and drop
drag and drop example
drag gameobject with mouse
drop
example
free lesson
game
game object
gameobject
Hans Oxmond
how to
image
instruction
learn
mouse
object
Oxmond Unity Tutorials
script
sprite
target
tip
trick
tutorials
unity 2019
Unity3d
video games
Short and to the point, glad to see you could give us just the bare amount of code needed to create the drag and drop functionality.
bool isDragging;
Vector2 difference;
public void OnMouseDown()
{
isDragging = true;
difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) – transform.position;
}
public void OnMouseUp()
{
isDragging = false;
}
// Update is called once per frame
void Update()
{
if(isDragging)
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition) – transform.position;
transform.Translate( mousePos- difference);
}
}
This does not work in unity 2019 this just moves the sprite to the moon once you click. I might be doing something wrong but this has little room for mistakes.
Absurd.