ball.as

ActionScript source for the Flash bouncing ball, 90 lines: the ball, which moves itself each frame, and the arena, which probes the level and works out the bounce. Raw file

//  0: sprite 4 frame 1

arena = _root.game.arena;
x = _x;
y = _y;
dx = 2.73113;
dy = 3.2121;
r = (_width + _height) * 0.25;
onEnterFrame = function() {
  if (!arena) {
    return;
  }
  hit = arena.workOutBallHit(x, y, dx, dy, r);
  x = hit.new_x;
  y = hit.new_y;
  dx = hit.new_dx;
  dy = hit.new_dy;
  _x = x;
  _y = y;
  if (hit.hitObject) {
    arena.hitBrick(hit.hitObject);
  }
};

//  1: sprite 5 frame 1

function workOutBallHit(x, y, dx, dy, r) {
  debug.clear();
  var o = new Object();
  var d = Math.sqrt(dx * dx + dy * dy);
  var a = Math.atan2(dy, dx);
  var c = Math.cos(a);
  var s = Math.sin(a);
  var a1;
  var a2;
  var h;
  h = false;
  for (a1 = -1.5707963; a1 <= 1.5707963; a1 += 0.1) {
    debug.lineStyle(1, 65280, 50);
    debug.moveTo(x, y);
    debug.lineTo(x + Math.cos(a + a1) * r, y + Math.sin(a + a1) * r);
    h = level.hitTest(x + r * Math.cos(a + a1), y + r * Math.sin(a + a1), true);
    if (h) {
      break;
    }
  }
  if (h) {
    h = false;
    for (a2 = 1.5707963; a2 >= a1; a2 -= 0.1) {
      debug.lineStyle(1, 16711680, 50);
      debug.moveTo(x, y);
      debug.lineTo(x + Math.cos(a + a2) * r, y + Math.sin(a + a2) * r);
      h = level.hitTest(x + r * Math.cos(a + a2), y + r * Math.sin(a + a2), true);
      if (h) {
        break;
      }
    }
  }
  o.new_x = x + dx;
  o.new_y = y + dy;
  debug.lineStyle(1, 0, 50);
  debug.moveTo(x, y);
  debug.lineTo(x + Math.cos(a) * 10, y + Math.sin(a) * 10);
  if (h) {
    debug.lineStyle(1, 0, 50);
    debug.moveTo(x, y);
    debug.lineTo(x + Math.cos(a + a1) * 10, y + Math.sin(a + a1) * 10);
    debug.moveTo(x, y);
    debug.lineTo(x + Math.cos(a + a2) * 10, y + Math.sin(a + a2) * 10);
    var na = a + (a1 + a2) * 0.5;
    var nx = Math.cos(na);
    var ny = Math.sin(na);
    var nd = nx * dx + ny * dy;
    o.new_dx = dx - 2 * nx * nd;
    o.new_dy = dy - 2 * ny * nd;
    debug.lineStyle(1, 255, 50);
    debug.moveTo(x, y);
    debug.lineTo(x + nx * 15, y + ny * 15);
    o.hitObject = null;
  } else {
    o.new_dx = dx;
    o.new_dy = dy;
    o.hitObject = null;
  }
  return o;
}
function hitBrick(hitObject) {
}
createEmptyMovieClip("debug", 2000);