Question

I've added a Quad to the stage, which I have made draggable.

However when I touch the draggable object and start to drag it, the object is "centered" to my finger touching (the x and y coordinates of my finger) the screen? As if the center of the Quad snaps to my touch point??? So touch the corners of the Quad will make it "snap" to my touch point => moving slightly.

So what I really want to know is, is it possible to "grab/drag" an object without having it adjusting and centering to my actual touch point? Ie. so that I can drag the object touching one of the corners of the squared Quad object?

My code can be seen below:

public function Game() {
            addEventListener(Event.ADDED_TO_STAGE, onAdded);
    }

    private function onAdded (e:Event):void { 
        var q:Quad = new Quad(200,200);
        q.x = 100;
        q.y = 100;
        q.addEventListener(TouchEvent.TOUCH, touchHandler); 
        addChild(q);

    }

    private function touchHandler(e : TouchEvent) : void 
    {
        var touch:Touch = e.getTouch(stage);
        var position:Point = touch.getLocation(stage);
        var target:Quad = e.target as Quad;

        if(touch.phase == TouchPhase.MOVED ){
            target.x = position.x - target.width/2;
            target.y = position.y - target.height/2;
            trace("x:" + target.x + " y:" + target.y)
        }
    }

Cheers

Was it helpful?

Solution

Of course you can. It's normal to snap, as you do this:

 target.x = position.x - target.width/2;
 target.y = position.y - target.height/2;

The thing to do here is to save the location at which the object was touched. This way you can calculate the difference between it's origin point and the actual point that you've touched it. Let's say you have a square of 100x100, your origin point is at 0x0, and you touch it at 50x50.

If you move your finger exactly one pixel (just for explanation), the object should actually move ONE pixel. Logic is this:

  • save touch point only once (50x50)
  • every time there is a movement, check location
  • make calculation: current location (51x51) - initial point (50x50) = difference (1x1)
  • move the object with the difference: 0x0 + 1x1 = 1x1, which means the object will move one pixel

OTHER TIPS

Right. Using:

touch = event.getTouch(stage);
touchX = touch.globalX;
touchY = touch.globalY;

And calculating the offset (x and y) did the trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top