Snap to Grid

Actionscript:
  1. [SWF(width = 600, height = 400)]
  2.  
  3. // draw the same grid as yesterday
  4. var tileSize:int = 40;
  5. var cols:int = stage.stageWidth / tileSize;
  6. var rows:int = stage.stageHeight / tileSize;
  7. var grid:Sprite = Sprite(addChild(new Sprite()));
  8. grid.graphics.lineStyle(0,0x000000);
  9. var i:int = 0;
  10. for (i = 1; i<cols; i++){
  11.     var posX:Number = i * tileSize
  12.     grid.graphics.moveTo(posX, 0);
  13.     grid.graphics.lineTo(posX, stage.stageHeight);
  14. }
  15. for (i = 1; i<rows; i++){
  16.     var posY:Number = i * tileSize
  17.     grid.graphics.moveTo(0, posY);
  18.     grid.graphics.lineTo(stage.stageWidth, posY);
  19. }
  20.  
  21. //
  22. // -- add a circle that snaps to the grid when dragged
  23. //
  24. var circle:Sprite = Sprite(addChild(new Sprite()));
  25. with (circle.graphics) beginFill(0xFF0000), drawCircle(0,0,10);
  26. circle.x = circle.y =  tileSize * 3;
  27. circle.buttonMode = true;
  28.  
  29. circle.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
  30. function onDown(evt:MouseEvent):void {
  31.     addEventListener(Event.ENTER_FRAME, onRunSnapping);
  32. }
  33.  
  34. function onRunSnapping(evt:Event):void {
  35.     circle.x =  Math.round(mouseX / tileSize) * tileSize;
  36.     circle.y =  Math.round(mouseY / tileSize) * tileSize;
  37. }
  38.  
  39. stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
  40. function onUp(evt:MouseEvent):void {
  41.     removeEventListener(Event.ENTER_FRAME, onRunSnapping);
  42. }

This builds on yesterdays post by adding a draggable red circle that snaps to the grid. This is the real trick:

Actionscript:
  1. circle.x =  Math.round(mouseX / tileSize) * tileSize;
  2. circle.y =  Math.round(mouseY / tileSize) * tileSize;

This entry was posted in Graphics, UI, motion and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*