SIMPLE DRAG AND DROP GAME                                           as3


    This tutorial shows how to create simple drag and drop game. In this case I used vegitables images, ofcourse you can use it as you like, its just to demonstrate the idea. The idea is to match the images with their names. Simply hold down mouse button over the image and drag it to the correct target. At the end it should looks like this.



     Insert or draw as many images in new actionscript 3 file as you like. Convert them each to movieclip and name them (instance names) as you like. In my case i used images of vegitables and named them accordingly. Now creat same number of rectangles ( again its up to you ) which will serve as targets. Name them exactly the same as the images earlier but add Target to it. For example my movieclip of apple is named apple (what a shock :) ) and the target is named appleTarget. Now arrange them on the stage as you like. Now open actions window and insert this actionscript code:


var xPos:int;
var yPos:int;

function Main():void {
	addListeners(apple, carrot, strawberry, banana, pepper);
}

function getPosition(target:Object):void {
	xPos=target.x;
	yPos=target.y;
}

function dragObject(e:MouseEvent):void {
	getPosition(e.target);

	e.target.startDrag(true);
}

function stopDragObject(e:MouseEvent):void {
	if (e.target.hitTestObject(getChildByName(e.target.name+"Target"))) {
		e.target.x=getChildByName(e.target.name+"Target").x;
		e.target.y=getChildByName(e.target.name+"Target").y;
	} else {
		e.target.x=xPos;
		e.target.y=yPos;
	}
	e.target.stopDrag();
}

function addListeners(... objects):void {
	for (var i:int = 0; i < objects.length; i++) {
		objects[i].addEventListener(MouseEvent.MOUSE_DOWN, dragObject);
		objects[i].addEventListener(MouseEvent.MOUSE_UP, stopDragObject);
	}
}
Main();


     First two lines are position variables used in script. Line 4 is function that starts it all. It adds listeners to every image on the stage. You can add as many as you like into the brackets, it will work for any number. Those names in brackets are instance names of images (movieclips that will be dragged). Function on line 8 gets x and y position of the target you click on with your mouse. Line 13 starts dragging the clicked object. Function on line 19 checks if you released the object over Target. If yes it checks if their names (adding Target part of the isntance name to images) matches. If they do it set the new position of the dragged image. If their names does not match, it returns the dragged object to its original position. Same happens if you release the object over empty stage. Line 30 adds these functions to each movieclip. Last line executes it all.


DOWNLOAD SOURCE FILE