Actionscript:
-
[SWF(width = 600, height = 400)]
-
-
// draw the same grid as yesterday
-
var tileSize:int = 40;
-
var cols:int = stage.stageWidth / tileSize;
-
var rows:int = stage.stageHeight / tileSize;
-
var grid:Sprite = Sprite(addChild(new Sprite()));
-
grid.graphics.lineStyle(0,0x000000);
-
var i:int = 0;
-
for (i = 1; i<cols; i++){
-
var posX:Number = i * tileSize
-
grid.graphics.moveTo(posX, 0);
-
grid.graphics.lineTo(posX, stage.stageHeight);
-
}
-
for (i = 1; i<rows; i++){
-
var posY:Number = i * tileSize
-
grid.graphics.moveTo(0, posY);
-
grid.graphics.lineTo(stage.stageWidth, posY);
-
}
-
-
//
-
// -- add a circle that snaps to the grid when dragged
-
//
-
var circle:Sprite = Sprite(addChild(new Sprite()));
-
with (circle.graphics) beginFill(0xFF0000), drawCircle(0,0,10);
-
circle.x = circle.y = tileSize * 3;
-
circle.buttonMode = true;
-
-
circle.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
-
function onDown(evt:MouseEvent):void {
-
addEventListener(Event.ENTER_FRAME, onRunSnapping);
-
}
-
-
function onRunSnapping(evt:Event):void {
-
circle.x = Math.round(mouseX / tileSize) * tileSize;
-
circle.y = Math.round(mouseY / tileSize) * tileSize;
-
}
-
-
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
-
function onUp(evt:MouseEvent):void {
-
removeEventListener(Event.ENTER_FRAME, onRunSnapping);
-
}
This builds on yesterdays post by adding a draggable red circle that snaps to the grid. This is the real trick:
Actionscript:
-
circle.x = Math.round(mouseX / tileSize) * tileSize;
-
circle.y = Math.round(mouseY / tileSize) * tileSize;