Search code examples
javascriptcreatejs

CreateJS - Puzzle Game


I am trying to build a puzzle game where I can change the image that is used in the game dynamically. I create various puzzle shapes using the drawscript plugin for illustrator which is great. That long code in .p() has all the information about the vector shape as well as the x and y positions. The beginBitmapFill() function then creates shapes that contain the information in the image for that shape. The downside is that the registration point is 0,0 which means that there is always a offset when dragging the puzzle pieces. Have a look at my fiddle to see what I mean. I have commented out the beginBitmapFill line but uncomment to see it in action. Anyone have any ideas on how to do this?

g = new createjs.Graphics();
s = new createjs.Shape(g);
s.graphics.beginBitmapFill(image).s().p("AAAAAYEEAAEEAAEEAAYAAAAhGDIBGA8YAyA8CChuAyAyYA8A8AAB4g8A8YgyAyiChugyA8YhGA8BGDSAAAAYAAAAjSA8g8g8Yg8g8Buh4gyg8Yg8gyh4AAg8AyYgyA8BuB4g8A8Yg8A8jSg8AAAAYAAkEAAkEAAj6");
s.name = key;
container.addChild(s);

http://jsfiddle.net/non_tech_guy/1yyn4904/


Solution

  • The problem come from the shapes location. The shapes are drawn in the predefined location, and their size are all 310px. Therefore when you assign the mouse event position to the target object, it becomes far away from the pointer.

    In order to make it works on the current implementation, i created a position references for each shape.

    positionReference = {};
    SHAPE_SIZE=310;
    var yRelCount = 1;
    
    for(var i = 1; i< 17;i++) {
        xRel = i % 4 || 4;
        yRel = yRelCount;
        if (xRel === 4) {
          yRelCount++;   
        }
        positionReference['p'+i] = {
            x: xRel * SHAPE_SIZE / 4,
            y: yRel * SHAPE_SIZE / 4
        }
    }
    

    the positionReference is an object which has the name of shape as the key (eg: p1, p2, p3, ...), and position x and y as the value.

    later on in the dragging event, utilize the position reference so that the shape stick to the mouse pointer

    function pressMove(evt){
        console.log('move')
        var target = evt.target;
        var ref = positionReference[target.name];
        target.x= stage.mouseX-ref.x+(SHAPE_SIZE/8);
        target.y= stage.mouseY-ref.y+(SHAPE_SIZE/8);
    }
    

    you may realise i also added the SHAPE_SIZE/8, the purpose of this is to adjust the position so that the mouse pointer appear in the middle of the shape.

    the working example: http://jsfiddle.net/1yyn4904/1/