// this pen imports maatter.js from https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.12.0/matter.min.js
//https://cdn.jsdelivr.net/npm/poly-decomp-es@0.4.2/dist/poly-decomp-es.cjs.min.js
// https://cdn.jsdelivr.net/npm/pathseg@1.2.1/pathseg.min.js
// got info from https://www.youtube.com/watch?v=hZkah1Y85Oc&t=109s
const { Engine, Render, Bodies, World, Svg } = Matter;
// svg variables
const svg = document.querySelector("#svg");
const namespace = "http://www.w3.org/2000/svg";
const viewportWidth = 500;
const viewportHeight = 500;
const w = 500;
const h = 500;
// matterjs engine and runner
const engine = Engine.create();
// svg body
let svgBody, floor, leftwall, rightwall;
// svg graphic
let svgGraphic;
let wallThickness = 100;
function initSVG() {
const svg = document.querySelector("svg");
svg.setAttribute("width", `${viewportWidth}`);
svg.setAttribute("height", `${viewportHeight}`);
svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
const bg = document.querySelector("#bg");
bg.setAttribute("width", `${w}`);
bg.setAttribute("height", `${h}`);
bg.setAttribute("fill", "#eaeaea");
}
function initRenderer() {
// create renderer
const rendererHolder = document.querySelector("#rendererHolder");
const render = Render.create({
element: rendererHolder,
engine: engine,
options: {
width: w,
height: h,
showAngleIndicator: true
}
});
Render.run(render);
}
function initParticle() {
const svgPath = document.querySelector(".svgPath");
const verticies = Matter.Svg.pathToVertices(svgPath);
svgBody = Matter.Bodies.fromVertices(0, 0, [verticies], {
restitution: 0.6,
isStatic: false
});
const minX = svgBody.bounds.min.x;
const minY = svgBody.bounds.min.y;
console.log('bounds: ', svgBody.bounds)
console.log("minX: ", minX);
console.log("minY: ", minY);
console.log(minX,minY);
svgGraphic = document.createElementNS(namespace, "g");
svgGraphic.appendChild(svgPath);
svgPath.setAttribute("transform", `translate(${minX} ${minY})`);
svg.appendChild(svgGraphic);
Matter.Body.setPosition(svgBody, { x: w/2, y: 0 });
Matter.Body.setAngle(svgBody, Math.random() * 2 * Math.PI);
}
function makeBoundaries() {
floor = Bodies.rectangle(w/2, h+wallThickness/2, w, wallThickness, {
isStatic: true,
id: "floor"
});
leftwall = Bodies.rectangle(-50, h/2, wallThickness, h, {
isStatic: true,
id: "leftwall"
});
rightwall = Bodies.rectangle(w + wallThickness, h/2, wallThickness, h, {
isStatic: true,
id: "righttwall"
});
}
function makeWorld() {
World.add(engine.world, [svgBody, floor, leftwall, rightwall]);
}
function update() {
Engine.update(engine);
const degrees = (svgBody.angle * 180) / Math.PI;
svgGraphic.setAttribute(
"transform",
`translate(${svgBody.position.x}, ${svgBody.position.y}) rotate(${degrees})`
);
window.requestAnimationFrame(update);
}
initSVG();
initRenderer();
initParticle();
makeBoundaries();
makeWorld();
update();