As3 Collision Detection

[ 2009-08-23 14:38:17 | Author: liuhuan ]
Font Size: Large | Medium | Small
uploads/200908/23_140651_untitled1.gif


I used the CollisionDetection(by scratchbrain) to detect collision between complex shapes. download: http://www.libspark.org/wiki/scratchbrain/CollisionDetection


package {
  import flash.display.*;
  import flash.events.*;
  import flash.geom.Rectangle;
  import fl.controls.Button;

  import net.scratchbrain.geom.CollisionDetection;
  public class Main extends Sprite {
    private var arr:Array = new Array();
    private var button:Button;
    public function Main():void {
      init();
      button = new Button();
      button.label = "re-generate";
      button.addEventListener(MouseEvent.MOUSE_DOWN, onStageMouseDown);
      addChild(button);
    }
    private function init():void {
      for (var i in arr) {
        removeChild(arr[i]);
      }
      arr[0] = drawRandomShape();
      arr[1] = drawRandomShape();
      checkCollision();
    }
    private function drawRandomShape():Sprite {
      var sprite:Sprite = new Sprite();
      sprite.graphics.clear();
      sprite.graphics.beginFill(Math.floor(Math.random() * 0xFF) << 16 | Math.floor(Math.random() * 0xFF) << 8 | Math.floor(Math.random() * 0xFF));
      sprite.graphics.moveTo(Math.floor(Math.random()*stage.stageWidth), Math.floor(Math.random()*stage.stageHeight));
      sprite.graphics.lineTo(Math.floor(Math.random()*stage.stageWidth), Math.floor(Math.random()*stage.stageHeight));
      sprite.graphics.lineTo(Math.floor(Math.random()*stage.stageWidth), Math.floor(Math.random()*stage.stageHeight));
      sprite.graphics.lineTo(Math.floor(Math.random()*stage.stageWidth), Math.floor(Math.random()*stage.stageHeight));
      sprite.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownHandler);
      sprite.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
      sprite.alpha = .7;
      sprite.useHandCursor = true;
      addChild(sprite);
      return sprite;
    }
    private function onMouseDownHandler(e:MouseEvent):void {
      e.currentTarget.startDrag();
      e.currentTarget.alpha = .3;
    }
    private function onMouseUpHandler(e:MouseEvent):void {
      e.currentTarget.stopDrag();
      e.currentTarget.alpha = .7;
      checkCollision();
    }
    private function checkCollision():void {
      this.graphics.clear();
      var colRec:Rectangle = CollisionDetection.checkForCollision(arr[0],arr[1]);
      if (colRec) {
        this.graphics.beginFill(0xFF0000,.1);
        this.graphics.lineStyle(2,0xFF0000);
        this.graphics.drawRect(colRec.x,colRec.y,colRec.width,colRec.height);
      }
    }
    private function onStageMouseDown(e:MouseEvent):void {
      init();
    }
  }
}

ref: http://www.scratchbrain.net/
Comments Feed Comments Feed: http://www.liuhuan.com/blog/feed.asp?q=comment&id=1018

There is no comment on this article.

You can't post comment on this article.