globalToLocal() in 3D

Actionscript:
  1. [SWF(frameRate=60, backgroundColor=0x000000, width=500, height=500)]
  2. stage.quality = "medium";
  3. var frame:Sprite = Sprite(addChild(new Sprite()));
  4. with (frame.graphics) beginFill(0xCCCCCC), drawRect(-200, -200, 400, 400), endFill();
  5. frame.x = stage.stageWidth / 2;
  6. frame.y = stage.stageHeight / 2;
  7. frame.z = 100;
  8.  
  9. var canvas:Shape = Shape(frame.addChild(new Shape()));
  10. var msk:Shape = Shape(frame.addChild(new Shape()));
  11. with (msk.graphics) beginFill(0x00FF00), drawRect(-200, -200, 400, 400), endFill();
  12. canvas.mask = msk
  13.  
  14. var txt:TextField = TextField(addChild(new TextField()));
  15. txt.defaultTextFormat = new TextFormat("_sans", 12);
  16. txt.x = txt.y = 10;
  17. txt.textColor = 0xFFFFFF, txt.autoSize="left", txt.text = "Draw on the 3D plane...";
  18.  
  19. stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
  20. stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
  21. function onDown(evt:MouseEvent):void{
  22.     canvas.graphics.lineStyle(4, 0x000000);
  23.     var pnt:Point = frame.globalToLocal(new Point(mouseX, mouseY));
  24.     canvas.graphics.moveTo(pnt.x, pnt.y);
  25.     addEventListener(Event.ENTER_FRAME, onDraw);
  26. }
  27. function onUp(evt:MouseEvent):void{
  28.     removeEventListener(Event.ENTER_FRAME, onDraw);
  29. }
  30.  
  31. var t:Number = 0;
  32. addEventListener(Event.ENTER_FRAME, onLoop);
  33. function onLoop(evt:Event):void {
  34.     frame.rotationY = 35 * Math.sin(t);
  35.     frame.rotationX = 35 * Math.cos(t);
  36.     t+=0.02;
  37. }
  38.  
  39. function onDraw(evt:Event):void {
  40.         var pnt:Point = frame.globalToLocal(new Point(mouseX, mouseY));
  41.     canvas.graphics.lineTo(pnt.x, pnt.y);
  42. }

This demo shows that globalToLocal() works with 3D - saving us the trouble of doing some extra math if we want to draw on 3D display objects...

Have a look at the swf....


Was made aware of this trick by watching a video that kevinSuttle sent me via twitter. The video is an interview with Chris Nuuja (one of the flash player engineers).

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

3 Comments

  1. Posted September 1, 2009 at 1:39 pm | Permalink

    fun to just park the mouse on it and let it draw itself -

  2. Posted September 3, 2009 at 2:50 am | Permalink

    Another excellent example :)

  3. Posted September 4, 2009 at 11:54 am | Permalink

    @Brendan … hadn’t noticed that - pretty funny
    @dVyper thanks

Post a Comment

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

*
*