- Home /
Drag and Drop Using Mouse (2D)
Hi Unity Masterbrains, I have been trying my very first project (!) and I was trying to code a process whereby if you drag an object (a 'Coin) onto another object, it is destroyed...but ONLY when the mouse is released. I have the dragging and the destruction down, but I can't get it to work when the mouse is released. I applied the following to an area:
void OnCollisionEnter2D (Collision2D coll) {
if (coll.gameObject.tag == "Coin")
{
Destroy(coll.gameObject);
}
}
Which works fine - as soon as the two objects touch, the 'Coin' disappears. Then I tried nesting another if statement like this:
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Coin")
{
if (GetMouseButtonUp(0))
{
Destroy(coll.gameObject);
}
}
}
The upshot being that it doesn't register when the mouse has been released and so is never destroyed! Any hints oh wise ones?
Answer by mealone · Jun 25, 2015 at 01:25 PM
Try using this : Var drag : boolean = true; function OnMouseDown (){ drag = false; }
function OnMouseUpAsButton (){
drag = true;
}
Function Update (){
if (!drag){ // pseudo code - gameobject.transform.position = mouse position;}
else{gameobject.transform.position = game object.transform.position;} }
This is untested... But it's also pseudo code just so that you can get the concept. On mouse down you're constraining the game object to the mouse.... So that would drag the object where the mouse moves... Then when you release the click the variable will be turned on so that the game object is no longer constrained to the mouse position....
Your answer
Follow this Question
Related Questions
Duplicate Object, by dragging? (SporeCreatureCreator Like) 0 Answers
Throwing an object (applying force to it when mouse is released) 2 Answers
Mouse/Wacom stylus drag not working. 1 Answer
How to calculate angles and apply to rotate an object. 1 Answer
How do i disable my buttons while dragging ScrollRect? 0 Answers