lundi 25 mai 2015

Flash: Dragging an object that snaps to a target

Okay, wasn't sure about the title. But here's what I am trying to achieve:

Basically i am trying to do something like a quiz, where you can drag and drop the answers into a field. And if they are correkt it should snap the answer field position.

It should be something like

if(myobject.hitTestObject(targetField) && isCorrectAnswer()) {
   myobject.x = targetField.x;
   myobject.y = targetField.y;

But it's not really working.

So here is what I have:

* Generating dragable answer fields based on an array.

function generateAnswer():void {

// creating text format
var myFormat:TextFormat = new TextFormat(); 

myFormat.color = 0x0066FF;    
myFormat.size = 24;  
myFormat.align = TextFormatAlign.CENTER 

// reference array to store all textfields
var referenceArray:Array = new Array();

// iterate through all answers in vocabListItems and generate textfields
var i:int; 

for (i = 0; i < vocabListItems.length; i++) { 
    var answerField:TextField = new TextField();   
    // Setting text to current answer
    answerField.text = vocabListItems[i];    
    answerField.width = 140;    
    answerField.height = 40;    
    answerField.x = 60+ i*150;    
    answerField.y = 410;  
    answerField.background = true;
    answerField.backgroundColor = 0xffffff;
    answerField.selectable = false;
    answerField.type = TextFieldType.DYNAMIC

    // store the textfield in a container so drag and drop
    // will work
    var textContainer:Sprite = new Sprite();

for each (var item in referenceArray) {
    item.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
    item.addEventListener(MouseEvent.MOUSE_UP, stopDragging);

And then I start my drag

var start_x:Number;
var start_y:Number;

function startDragging(e: MouseEvent):void {

  var object = e.currentTarget;
  start_x = e.currentTarget.x;
  start_y = e.currentTarget.y;

And my stop dragging

function stopDragging(e:MouseEvent):void {

if (e.currentTarget.hitTestObject(targetField)) {
    e.currentTarget.x = targetField.x;
    e.currentTarget.y = targetField.y;

} else {
    e.currentTarget.x = start_x;
    e.currentTarget.y = start_y;

So the problem however is, that e.currentTarget.x is starting from 0. And not from the absolute position on the screen. Its always a relative value, so if i drag it to the targetField its x and y is something like -100, -40

If I set it to the targetField x and y it disappears somewhere in the nirvana of the screen.

How can I position it to the absolute x and y?

Aucun commentaire:

Enregistrer un commentaire