123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <html>

<head lang="en">
  <meta charset="UTF-8">
  <title>Testing physics</title>
  <link rel="stylesheet" href="style.css">
  <script src="js/physics.js"></script>
</head>

<body>
  <canvas id="c"></canvas>

</body>

</html>
            
          
!
            
              /**
 * Created by Pierre on 01/12/2014.
 */

/********** Object **********/

var Object = function(t, W, cx, cy, dim, col) {
  this.color = col;
  this.type = t;
  this.weight = W;

  if (t == "circle") {
    this.dim = {
      r: dim.r
    }
  } else if (t == "rectangle") {
    this.dim = {
      w: dim.w,
      h: dim.h
    }
  }

  this.pos = {
    x: cx,
    y: cy
  };
  this.speed = {
    x: 0,
    y: 0
  };
  this.acc = {
    x: 0,
    y: 0
  };
  //this.forces ??
};

Object.prototype.getSpeedVector = function() {
  var O, P;
  O = {
    x: this.pos.x,
    y: this.pos.y
  };
  P = {
    x: this.pos.x + this.speed.x,
    y: this.pos.y + this.speed.y
  };
  return {
    A: O,
    B: P
  }
};

Object.prototype.update = function(force) {
  this.updatePosition();
  this.updateSpeed();
  this.updateAcc(force);
};

Object.prototype.updatePosition = function() {
  this.pos.x += this.speed.x;
  this.pos.y += this.speed.y;
};

Object.prototype.updateSpeed = function() {
  if (Math.abs(this.speed.x) < 0.0001) this.speed.x = 0;
  if (Math.abs(this.speed.y) < 0.0001) this.speed.y = 0;
  this.speed.x += this.acc.x;
  this.speed.y += this.acc.y;
};

Object.prototype.updateAcc = function(force) {
  this.acc.x = force.x / this.weight;
  this.acc.y = force.y / this.weight;
};

Object.prototype.draw = function() {
  ctx.beginPath();
  ctx.strokeStyle = this.color;
  if (this.type == "circle") {
    ctx.arc(this.pos.x, this.pos.y, this.dim.r, 0, Math.PI * 2);
  } else if (this.type = "rectangle") {
    ctx.rect(this.pos.x, this.pos.y, this.dim.w, this.dim.h)
  }
  ctx.stroke();
};

/********** Force **********/

var Force = function(params, fct, pos) {
  this.params = params;
  this.function = fct;
  this.pos = {
    x: pos.x,
    y: pos.y
  };
};

Force.prototype.get = function(object) {
  return this.function(object)
};

function gravityFunction(object) {
  //Force params must be of form {g:<>,angle:<>}
  return {
    x: object.weight * this.params.g * Math.cos(this.params.angle),
    y: object.weight * this.params.g * Math.sin(this.params.angle)
  }
}

function customForceFunction1(object) {
  var dx = this.x - object.pos.x;
  var dy = this.y - object.pos.y;
  var d = Math.sqrt(dx * dx + dy * dy);
  var magnitude = this.params.value * 10 * Math.exp(-0.01 * (d - 10));
  return {
    x: dx / d * magnitude,
    y: dy / d * magnitude
  }
}

/********** Engine **********/

var Engine = function() {
  this.surfaces = [];
  this.objects = [];
  this.forces = [];
};

Engine.prototype.addSurface = function(x, y, w, h, f) {
  var surface = {
    orig: {
      x: x,
      y: y
    },
    width: w,
    heigth: h,
    frictionCoef: f
  };
  this.surfaces.push(surface);
};

Engine.prototype.getFriction = function(x, y) {
  var i = this.surfaces.length;
  while (i--) {
    if (x > this.surfaces[i].orig.x && x < this.surfaces[i].orig.x + this.surfaces[i].width) {
      if (y > this.surfaces[i].orig.y && y < this.surfaces[i].orig.y + this.surfaces[i].height)
        return this.surfaces[i].frictionCoef;
    }
  }
};

Engine.prototype.addObject = function(object) {
  this.objects.push(object);
};

Engine.prototype.addForce = function(force) {
  this.forces.push(force);
};

Engine.prototype.update = function() {
  var i = this.objects.length;
  while (i--) {
    this.objects[i].update(resolveForces(this.forces, this.objects[i]));
    if (objectOutOfBounds(-200, boundx + 200, -200, boundy + 200, this.objects[i])) {
      this.objects.splice(i, 1);
    }
  }
  if (COLLISIONS) resolveCollisions(this.objects);
};

Engine.prototype.render = function() {
  var i = this.objects.length;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  while (i--) {
    ctx.beginPath();
    this.objects[i].draw();
    ctx.stroke();
  }
};

function objectOutOfBounds(xMin, xMax, yMin, yMax, object) {
  if (object.pos.x > xMax) return 1;
  if (object.pos.x < xMin) return 1;
  if (object.pos.y > yMax) return 1;
  if (object.pos.y < yMin) return 1;
  return 0;
}

function resolveForces(forces, object) {
  var i = forces.length;
  var F;
  var fx = 0;
  var fy = 0;
  while (i--) {
    F = forces[i].get(object);
    fx += F.x;
    fy += F.y;
  }
  return {
    x: fx,
    y: fy
  }
}

function detectCollision(object1, object2, collisionType) {
  switch (collisionType) {
    case "circlecircle":
      var sqD = Math.pow(object1.pos.x - object2.pos.x, 2) + Math.pow(object1.pos.y - object2.pos.y, 2);
      if (sqD <= Math.pow(object1.dim.r + object2.dim.r, 2)) {
        return 1;
      } else {
        return 0;
      }
      break;
    case "rectanglecircle":
      //TODO
      return 0;
      break;
    case "circlerectangle":
      //TODO
      return 0;
      break;
    case "rectanglerectangle":
      //TODO
      return 0;
      break;
  }
}

function resolveCollision(object1, object2, collisionType) {
  /**resolve pos intersect**/
  var o1o2 = new Vect({
    x: object1.pos.x,
    y: object1.pos.y
  }, {
    x: object2.pos.x,
    y: object2.pos.y
  });
  var o2o1 = invertVect(o1o2);
  var colPoint, newO1, newO2;
  colPoint = translate({
    x: object1.pos.x,
    y: object1.pos.y
  }, o1o2, object1.dim.r - (object1.dim.r + object2.dim.r - Math.sqrt(sqNorm(o1o2))) * ((object2.dim.r * object2.weight) / (object1.dim.r * object1.weight + object2.dim.r * object2.weight)));
  newO1 = translate(colPoint, o2o1, object1.dim.r);
  newO2 = translate(colPoint, o1o2, object2.dim.r);
  object1.pos.x = newO1.x;
  object1.pos.y = newO1.y;
  object2.pos.x = newO2.x;
  object2.pos.y = newO2.y;
  /**update speeds**/
  var n = o1o2;
  var t = new Vect(o1o2.A, {
    x: o1o2.A.x - (o1o2.B.y - o1o2.A.y),
    y: o1o2.A.y + (o1o2.B.x - o1o2.A.x)
  });
  var S1 = object1.getSpeedVector();
  var S2 = object2.getSpeedVector();
  var S1t = projectV(S1, t);
  var S1n = projectV(S1, n);
  var S2t = projectV(S2, t);
  var S2n = projectV(S2, n);
  var w1 = object1.weight;
  var w2 = object2.weight;
  var wt = object1.weight + object2.weight;

  object1.speed.x = (2 * w2 / wt) * (S2n.B.x - S2n.A.x) + ((w1 - w2) / wt) * (S1n.B.x - S1n.A.x) + S1t.B.x - S1t.A.x;
  object1.speed.y = (2 * w2 / wt) * (S2n.B.y - S2n.A.y) + ((w1 - w2) / wt) * (S1n.B.y - S1n.A.y) + S1t.B.y - S1t.A.y;
  object2.speed.x = (2 * w1 / wt) * (S1n.B.x - S1n.A.x) + ((w2 - w1) / wt) * (S2n.B.x - S2n.A.x) + S2t.B.x - S2t.A.x;
  object2.speed.y = (2 * w1 / wt) * (S1n.B.y - S1n.A.y) + ((w2 - w1) / wt) * (S2n.B.y - S2n.A.y) + S2t.B.y - S2t.A.y;
}

function resolveCollisions(objects) {
  //TODO : use quadtree instead of testing all objects
  var collisionType;
  var i = objects.length;
  var j;
  while (i--) {
    j = i;
    while (j--) {
      collisionType = objects[i].type + objects[j].type;
      if (detectCollision(objects[i], objects[j], collisionType)) {
        resolveCollision(objects[i], objects[j], collisionType);
      }
    }
  }
}

/********** Math **********/

var Vect = function(p1, p2) {
  this.A = {
    x: p1.x,
    y: p1.y
  };
  this.B = {
    x: p2.x,
    y: p2.y
  }
};

Vect.prototype.update = function() {

};

Vect.prototype.draw = function() {
  ctx.beginPath();
  ctx.moveTo(this.A.x, this.A.y);
  ctx.lineTo(this.B.x, this.B.y);
  ctx.arc(this.B.x, this.B.y, 2, 0, Math.PI * 2);
  ctx.stroke();
};

function sumVect(vect1, vect2) {
  return {
    A: {
      x: vect1.A.x,
      y: vect1.A.y
    },
    B: {
      x: vect1.B.x + vect2.B.x - vect2.A.x,
      y: vect1.B.y + vect2.B.y - vect2.A.y
    }
  }
}

function invertVect(vect) {
  return {
    A: {
      x: vect.B.x,
      y: vect.B.y
    },
    B: {
      x: vect.A.x,
      y: vect.A.y
    }
  }
}

function getDir(vect) {
  var dirX, dirY;
  if (vect.B.x - vect.A.x == 0) dirX = 0;
  else dirX = (vect.B.x - vect.A.x) / Math.abs(vect.B.x - vect.A.x);
  if (vect.B.y - vect.A.y == 0) dirY = 0;
  else dirY = (vect.B.y - vect.A.y) / Math.abs(vect.B.y - vect.A.y);

  return {
    x: dirX,
    y: dirY
  }
}

function sqNorm(vect) {
  return Math.pow(vect.B.x - vect.A.x, 2) + Math.pow(vect.B.y - vect.A.y, 2);
}

function translate(p, vect, value) {
  var v = {
    x1: vect.A.x,
    y1: vect.A.y,
    x2: vect.A.x + (vect.B.x - vect.A.x) / Math.sqrt(sqNorm(vect)),
    y2: vect.A.y + (vect.B.y - vect.A.y) / Math.sqrt(sqNorm(vect))
  };
  return {
    x: p.x + (v.x2 - v.x1) * value,
    y: p.y + (v.y2 - v.y1) * value
  }
}

function projectP(point, vect) {
  // http://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
  var b = (vect.B.x - vect.A.x);
  var a = -(vect.B.y - vect.A.y);
  var c = -(vect.A.x * a + vect.A.y * b);
  return {
    x: (b * (b * point.x - a * point.y) - a * c) / (a * a + b * b),
    y: (a * (-b * point.x + a * point.y) - b * c) / (a * a + b * b)
  }
}

function projectV(vect1, vect2) {
  return new Vect(projectP(vect1.A, vect2), projectP(vect1.B, vect2));
}

/** Test environment, requires html with a canvas **/

var COLLISIONS = true,
  GRAVITY_ANGLE = 0,
  GRAVITY_VALUE = 1,
  GLOBAL_FRICTION = 1;

var iterator = 0,
  engine,
  canvas,
  ctx,
  boundx = window.innerWidth,
  boundy = window.innerHeight;

window.requestAnimFrame =
  window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  window.oRequestAnimationFrame ||
  window.msRequestAnimationFrame ||
  function(callback) {
    window.setTimeout(callback, 1000 / 60);
  };

window.onload = function() {
  canvas = document.getElementById('c');
  ctx = canvas.getContext('2d');
  canvas.width = boundx;
  canvas.height = boundy;
  start();
};

function newBall(x, y, w, r, sx, sy) {
  var ball = new Object("circle", w, x, y, {
    r: r
  }, "#FF0000");
  ball.speed.x = sx;
  ball.speed.y = sy;
  engine.addObject(ball);
}

function ballGenerator() {
  if (iterator % 2 == 0) {
    newBall(0, boundy / 2 + Math.sin(5 * 0.01 * iterator * 4) * 100, iterator % 15, iterator % 15, 6, 0)
  }
  if (iterator % 300 == 0) {
    newBall(0, boundy / 2 + 50 - Math.random() * 100, 200, 50, 20, -3 + Math.random() * 6)
  }
  iterator++;
}

function start() {
  engine = new Engine();
  engine.addSurface(-200, -200, boundx + 400, boundy + 400, GLOBAL_FRICTION);

  newBall(boundx, boundy / 2, 9E+300, 350, 0, 0);

  update()
}

function update() {
  ballGenerator();
  engine.update();
  engine.render();
  requestAnimFrame(update);
}
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console