This tutorial aims to explain how to make a jigsaw puzzle using Scirra's Construct2. This is part three, "Snap pieces." We will tell you how to make pieces "snap" each other.
Previous in this series
Previous in this series are two chapters,
Making a jigsaw puzzle - Part one: concept.
Making a jigsaw puzzle - Part two: Making jigsaw pieces
The first chapter shows some of the concepts we'll use in this tutorial, while the part two explains you how to "jigsaw cut" a piece from a bigger image, so you can make jigsaw pieces on the fly from any image.
In the last part (part two) I suggested you to improve the events in the file adding a for... loop to make all the pieces, using the same logic we used to make the top-left corner piece. The attached file contains a for...loop such that one.
The file also contains another improvement: "harcoded" piece sizes have been "softcoded" with variables instead, and we added a "Resize" group to do all the resizing we did "by hand" on the second part of this tutorial.
Tutorial_puzzle_2b.capx contains all we have done until this point.
Putting the resize routines inside a group uses an extra event (you should consider it if you are using the free version of Construct2), but it helps you to remember the purpose of all these events. It has another advantage, also: Now you can hide the whole "Resize" until we need to change it again.
Drag and drop, the simplest way
The first thing we will do is adding some interaction from the user. Go to the Layout view and add the "drag and drop" behaviour to the "Canvas" canvas (make sure to act on Piece and not on its clone --by the way, we could delete the clone now). The "drag and drop" behaviour is great since it saves us from using "Mouse" and "Touch" objects and events.
We add the "drag and drop" behaviour to "Canvas" instead of "Piece" because the actual piece we move is an instance of the Canvas object. Since having our pieces named "Canvas" is a little prone to error, we will also rename our objects:
- Rename "Piece" and "Piece2" into "PieceMask" and "PieceMask2"..
- Rename "Canvas" into "ActualPiece".
Move active pieces to top
Run your project. You will see you can move the pieces, but, when you move them, they are hidden by other pieces in the layout. We will need to add some code to our events:
At the end of the event view, add another event:
ActualPiece.On DragDrop drag start => ActualPiece.MoveToTop
You will also see you have an spurious "ActualPiece" object (a yellow square). This is the first "ActualPiece" Object included in our layout. We need it to be placed in the layout in order to access the "ActualPiece" class, but, since we will be working with clones, we should delete it at start of layout.
At the first "Start of layout" event, add a "ActualPiece.Destroy".