Skip to main content
eugener2418576
Inspiring
November 19, 2018
Answered

Dragging onto the wrong object

  • November 19, 2018
  • 1 reply
  • 556 views

Hi there,

Simple request, I have some code that I got from here originally which lets me drag objects onto baskets

// mouse down event

function onMouseDown1(evt){

var item = evt.currentTarget;

item.offset = {x:0, y:0};

var pt = item.parent.globalToLocal(evt.stageX, evt.stageY);

item.offset.x = pt.x - item.x;

item.offset.y = pt.y - item.y;

item.drag = true;

}

// mouse up event

function onMouseUp1(evt){

var item = evt.currentTarget;

item.drag = false;

var pt = item.localToLocal(item.dot.x, item.dot.y, this.basket2.hitBox);

var pt2 = item.localToLocal(item.dot.x, item.dot.y, this.basket1.hitBox);

if(this.basket2.hitBox.hitTest(pt.x, pt.y) ){

item.x = this.basket2.x;

item.y = this.basket2.y;

item.gotoAndPlay('endState');

createjs.Tween.get(item)

.wait(500)

.to({alpha:0, visible:false}, 1000);

item.mouseEnabled = false;   // prevents object from being move when place correctly

finish();

} else if (this.basket1.hitBox.hitTest(pt2.x, pt2.y) ){

item.gotoAndPlay('wrongBox');

}

}

// mouse move event

function onMouseMove1(evt){

var item = evt.currentTarget;

if (item.drag){

var pt = item.parent.globalToLocal(evt.stageX, evt.stageY);

item.x = pt.x - item.offset.x;

item.y = pt.y - item.offset.y;

}

}

In this code, I have added my own else if which checks to see if the item has hit the wrong basket. If it has, it plays its own movie clip.

The part where I need help - how would I get the item to snapback to it's original position?

Cheers

    This topic has been closed for replies.
    Correct answer kglad

    in onMouseDown1:

    item.origX=item.x;

    item.origY=item.y;

    in onMouseUp1 in your else if branch:

    item.x=item.origX;

    item.y=item.origY;

    1 reply

    kglad
    Community Expert
    kgladCommunity ExpertCorrect answer
    Community Expert
    November 20, 2018

    in onMouseDown1:

    item.origX=item.x;

    item.origY=item.y;

    in onMouseUp1 in your else if branch:

    item.x=item.origX;

    item.y=item.origY;

    eugener2418576
    Inspiring
    November 21, 2018

    Perfect mate!

    A little bug - if I move the object someplace else and then move it to the wrong container, the object will snapback to the second stated position.

    I tried to set the root position of the elements to see if that'd work but had no luck.

    Any ideas mate?

    Cheers

    kglad
    Community Expert
    Community Expert
    November 21, 2018

    in onMouseDown1:

    if(!item.alreadyMoved){

    item.origX=item.x;

    item.origY=item.y;

    }

    in onMouseUp1 in your else if branch:

    item.x=item.origX;

    item.y=item.origY;

    item.alreadyMoved=true;