Skip to content

Instantly share code, notes, and snippets.

@kahshiu
Created November 17, 2011 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kahshiu/1372751 to your computer and use it in GitHub Desktop.
Save kahshiu/1372751 to your computer and use it in GitHub Desktop.
Collision Detection between Circles
package
{
import flash.display.Sprite;
/**
* Ball sprite
* @author Shiu
*/
public class Ball extends Sprite
{
private var _radius:Number;
private var _col:Number;
public function Ball(radius:Number = 10, col:Number = 0xFF6633) {
this._radius = radius;
this._col = col;
this.draw();
}
//function to draw the sprite according to specifications
private function draw():void {
graphics.beginFill(_col);
graphics.drawCircle(0, 0, _radius);
graphics.endFill();
}
public function get radius():Number {
return _radius;
}
public function set radius(value:Number):void {
_radius = value;
this.draw();
}
public function get col():Number {
return _col;
}
public function set col(value:Number):void {
_col = value;
this.draw();
}
}
}
package
{
import flash.display.Sprite;
import flash.events.Event;
/**
* Purpose: Demo on circle/ circle collision detection
* @author Shiu
*/
public class Main extends Sprite
{
private var b:Ball;
private var c:Ball;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
c = new Ball; addChild(c); c.x = 300; c.y = 500; c.radius = 30; c.col = 0x339911;
b = new Ball; addChild(b); b.x = 200; b.y = 200; //placing in the sprites
b.addEventListener(Event.ENTER_FRAME, move); // adding in animation
}
//b will always move toward c
private function move(e:Event):void
{
var vec:Vector2D = new Vector2D(c.x - b.x, c.y - b.y);
vec.setMagnitude(10);
if (collide(b,c)) b.removeEventListener(Event.ENTER_FRAME, move);
else {b.x += vec.x; b.y += vec.y;}
}
//collision detection
private function collide (b1:Ball, b2:Ball) :Boolean {
var isCollide:Boolean = false;
var dist:Vector2D = new Vector2D(b1.x - b2.x, b1.y - b2.y);
if (dist.getMagnitude() <= b1.radius +b2.radius) isCollide = true;
return isCollide;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment