Limiting drag and drop movement for a game in Flash CS3 with ActionScript 3

Post to Twitter

Sometimes its useful to limit drag and drop of an object to an area you define. For example, lets say you are building a game in Flash CS3 and are allowing the player to move their character around in a dungeon via drag and drop. They click on their character and begin to move them about however you want to only allow them to move a certain distance.

In this case I’ll use a simple green circle to represent the character and when you press and click on it to drag it you will see a gray square show that indicates the area you can move within per turn.

This can be easily accomplished with a little ActionScript:


var currentX:Number;
var currentY:Number;
var currentOldX:Number;
var currentOldY:Number;

player1_mc.buttonMode = true;
player1_mc.addEventListener(MouseEvent.MOUSE_DOWN, mouseEventDown);
player1_mc.addEventListener(MouseEvent.MOUSE_UP, mouseEventReleased);

player1Mask_mc.x = player1_mc.x;
player1Mask_mc.y = player1_mc.y;

var lastChildIndex:int = 0;

function mouseEventDown(evt:MouseEvent):void
	currentX = player1_mc.x;
	currentY = player1_mc.y;
	currentOldX = player1_mc.x;
	currentOldY = player1_mc.y;

	var r:Rectangle = new Rectangle(currentX - 50, currentY - 50, currentX + 50, currentY + 50);
	var square:Shape = new Shape();, 0xEEEEEE); - 40, currentY - 40, 80, 80);;
	lastChildIndex = this.numChildren - 1;

	player1_mc.startDrag(false, new Rectangle(currentX - 40, currentY - 40, 80, 80));

function mouseEventReleased(evt:MouseEvent):void
	player1Mask_mc.x = player1_mc.x;
	player1Mask_mc.y = player1_mc.y;

When the player moved their character I trace a square to the area they are confined to, normally in a game you wouldn’t do this but I put the square in to make it more clear how they are constrained.

One quick note: if you over extend the drag the little gray square doesn’t always erase but since that won’t ever be visible in a real game the code that manages it can be removed as its only here to allow us to visibly see the movement constraint.

Post to Twitter

This entry was posted in ActionScript, Flash. Bookmark the permalink.

One Response to Limiting drag and drop movement for a game in Flash CS3 with ActionScript 3

  1. Elvis Oliveira says:

    Please, republish the example if possible, i’m having some problems with this, and i believe it could help others too.

Comments are closed.