Physics Engine

by 79brue

JavaScript

document.write('<div id="canvasArea"> </div> <br /> 점선 위의 원하는 지역을 클릭해 공을 추가하세요.<br />');

var canvasArea = document.getElementById('canvasArea');
canvasArea.innerHTML = '<canvas id="myCanvas" width="720" height="480" style="border:1px solid #000000;"> </canvas>';
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

const restitution = 0.9;

var abs = function(x) {
  if (x < 0) return -x;
  return x;
};

var SQR = function(x) {
  return x * x;
}

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

var changeCoordinates = function(p, deg) {
  return new Point(p.x * Math.cos(deg) + p.y * Math.sin(deg),
    p.y * Math.cos(deg) - p.x * Math.sin(deg));
}

class Sphere {
  constructor(x, y, r, movable) {
    this.type = 'Sphere';
    this.center = new Point(x, y);
    this.r = r;
    this.movable = movable;
    this.vx = 0;
    this.vy = 0;

    if (movable) {
      this.mass = Math.PI * r * r;
    } else this.mass = 1e20;

    console.log(this.mass);
  }

  updateLocation() {
    if (!this.movable) return;
    if (this.center.x - this.r < 0) {
      this.vx = abs(this.vx) * restitution;
      this.center.x = this.r;
    }
    if (this.center.x + this.r > 720) {
      this.vx = -abs(this.vx) * restitution;
      this.center.x = 720 - this.r;
    }
    if (this.center.y - this.r < 0) {
      this.vy = abs(this.vy) * restitution;
      this.center.y = this.r;
    }
    if (this.center.y + this.r > 480) {
      this.vy = -abs(this.vy) * restitution;
      this.center.y = 480 - this.r;
    }

    this.vy += 0.98 * 1.7; // g = 9.8m/s^2
    this.center.x += 0.01 * this.vx;
    this.center.y += 0.01 * this.vy;
  }

  drawInCanvas() {
    ctx.strokeStyle = "black";
    ctx.setLineDash([]);
    ctx.beginPath();
    ctx.arc(this.center.x, this.center.y, this.r, 0, 2 * Math.PI);
    if (!this.movable) {
      ctx.fillStyle = 'black';
      ctx.fill();
    }
    ctx.stroke();
  }
}
class fixedRectangle {
  constructor(x, y, a,...