{"id":419,"date":"2019-04-20T23:06:53","date_gmt":"2019-04-20T22:06:53","guid":{"rendered":"https:\/\/www.maxcanvas.org\/?page_id=419"},"modified":"2026-10-25T22:13:26","modified_gmt":"2026-10-25T22:13:26","slug":"spring","status":"publish","type":"page","link":"https:\/\/www.maxcanvas.org\/?page_id=419","title":{"rendered":"Spring"},"content":{"rendered":"\n<figure><iframe loading=\"lazy\" width=\"905px\" height=\"705px\" src=\"https:\/\/www.maxcanvas.org\/MaxCanvas\/Examples\/MC%20-%2009%20-%20Spring.html\"><\/iframe><\/figure>\n\n\n\n<p>The Spring project demonstrates some advanced concepts for the MC engine.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The GUI work is non-trivial<\/li><li>The &#8220;line&#8221; is made up of an array of MC.Point objects, which &#8211;<\/li><li>Emulates the MC Sprite.update() method and uses the MC.game.deltaTime and MC.game.physicsUpdates variables in a physics loop (via the SS.updateLines() method)<\/li><li>Has the array clean itself, in a similar fashion to a MC SpriteBin<\/li><li>The resulting line is then rendered using the MC.draw.polyLine() method<\/li><li>Additionally, the spring is rendered the same way with the points array created &#8220;on-the-fly&#8221;<\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Code<\/h4>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ MaxCanvas Project\n\/\/ 09-Spring.JS File (April 2019)\n\/\/\n\/\/ Required to drag MC.js into Intellisense\n\/\/ thanks to https:\/\/visualstudiomagazine.com\/blogs\/tool-tracker\/2018\/07\/use-javascript-code.aspx (Dec 2018)\n\/\/\/ &lt;reference path=\"MC.js\" \/>\n\nwindow.onload = (function() {\n\n    \/\/ AQUIRE HTML DOM CANVAS REFERENCE\n    var c=document.getElementById(\"canvas\");\n\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/ INITIALISE MC Engine \/\/\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    MC.init(c);\n\n    \/\/ Configure .game\n    MC.game.physicsUpdates = 10;     \n\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/ END OF Initialisation \/\/\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/-----------------------------------------------------------------------------\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/ VARIABLE DECLARATION \/\/\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n    \/\/ SS = Spring Simulator, container object for program variables and methods, so as to not pollute global namespace too much\n    \/\/ more complex mthods defined after inital declaration, as it's easier to follow \/ edit.\n    var SS = {\n        BGColor: new MC.Color(157, 226, 228, 1),\n        titleType : new MC.Typeface(\"Arial\", 40, \"black\"),\n        Top: new MC.Sprite({ type: \"circ\", size1: 4, fillColor: \"Black\", edgeColor: \"Black\", pos: new MC.Point(800, 50) }),\n        Datum: new MC.Point(800, 400),\n        MaxTravel: 200,\n        Radius: 30,\n        Efficiency: 1,\n        K: 25,\n        Selecting: false,\n        Pen: {}, \/\/ it's complicated, will configure later\n        Nodes: 40,\n        GUI: new MC.GUI(),\n        Points: []\n    };\n\n    SS.Pen = SS.Top.clone();\n    SS.Pen.pos.set(SS.Datum).add(0,SS.MaxTravel);\n    SS.Pen.dev.update = function () {\n\n        \/\/ user visual feedback, is the mouse in the \"you can select the pen\" bounds?\n        SS.Pen.fillColor = \"Black\";\n        if (SS.inBox() || SS.Selecting) {\n            SS.Pen.fillColor = \"Red\";\n        }\n\n        if (SS.Selecting) {  \/\/ if \"selecting\", Pen moves up\/down to match mouse y coordinate (within bounds)\n            var y = MC.mouse.pos.y;\n            y = MC.maths.clamp(y, SS.Datum.y - SS.MaxTravel, SS.Datum.y + SS.MaxTravel);\n            SS.Pen.moveTo(new MC.Point(SS.Datum.x, y));\n        }\n        else {\n            \/\/ damp movement\n            SS.Pen.vel.times(SS.Efficiency);\n\n            \/\/ Calculate and apply Acceleration\n            var disp = SS.Datum.y - SS.Pen.pos.y;\n            SS.Pen.acc.set(0, disp * SS.K);\n\n            \/\/ add a new point to the line points array (if required)\n            var len = SS.Points.length;\n            if (len == 0 || MC.maths.rangeSqr(SS.Pen.pos, SS.Points[len - 1]) >= 1) SS.Points.push(SS.Pen.pos.clone());\n        }\n    };\n\n    \/\/ Increments the points in Spring.Points to the left,\n    \/\/ eliminates any that have fallen off the edge of the screen\n    \/\/ Done by cycling through the Array, populating a new one, then overwriting the original (Something JavaScript does very efficiently)\n    SS.updateLines = function () {\n        var len = SS.Points.length;\n        var na = [];\n        for (var i = 0; i &lt; len; i++) {\n            SS.Points[i].minus(100 * MC.game.deltaTime \/ MC.game.physicsUpdates, 0);\n            if (SS.Points[i].x > -5) na.push(SS.Points[i]);\n        }\n        SS.Points = na;\n    }\n\n    \/\/ Clears existing line and sets Spring to bottom of travel, with velocity 0\n    SS.resetSpring = function () {\n        SS.Points = [];\n        SS.Pen.vel.set(0, 0);\n        SS.Pen.pos.set(SS.Datum).add(0, SS.MaxTravel);\n    }\n\n    \/\/ Check if the mouse if \"inside\" an imaginary box reflecting the spring boundaries.\n    \/\/ only want the mouse to select the end of the spring (aka the \"pen\") if inside this\n    SS.inBox = function () {\n        var m = MC.mouse.pos;\n        var d = SS.Datum;\n        var r = SS.Radius;\n        var l = SS.MaxTravel;\n        return (m.x > d.x - r &amp;&amp; m.x &lt; d.x + r &amp;&amp; m.y > d.y - l &amp;&amp; m.y &lt; d.y + l);\n    }\n\n    \/\/ Spring draw function\n    \/\/ generates a array of MC.Points and calls MC.draw.polyLine to render them\n    SS.drawSpring = function () {\n        var r = SS.Radius;\n        var t = SS.Top.pos;\n        var t2 = t.clone().add(0, 25);\n        var b = SS.Pen.pos;\n        var b2 = b.clone().minus(0, 25);\n        var dy = (b2.y - t2.y) \/ SS.Nodes;\n        var s = [];\n        s.push(t);\n        s.push(t2);\n        for (var i = 0; i &lt; SS.Nodes; i = i + 2)\n        {\n            s.push(new MC.Point(t2.clone().add(-r, ((i + 0.5) * dy))));\n            s.push(new MC.Point(t2.clone().add(r, ((i + 1.5) * dy))));\n        }\n        s.push(b2);\n        s.push(b);\n\n        MC.draw.polyLine(s, \"black\", 1.5);\n    }\n\n    \/\/ Variable management functions, called by GUI elements\n    \/\/ Each resets the simulation upon calling.  Parameter = 1 increments, anything else decrements\n    SS.incrementK = function (value) {\n        var oldValue = SS.K;\n        var mod = -5;\n        if (value === 1) mod *= -1;\n        SS.K = MC.maths.clamp(SS.K + mod, 5, 50);\n        if (oldValue != SS.K) {\n            SS.KReport.setValues({ text: \"K : \" + SS.K });\n            SS.resetSpring();\n        }\n    }\n\n    SS.incrementEff = function (value) {\n        var oldValue = SS.Efficiency;\n        var mod = -0.0005;\n        if (value == 1) mod *= -1;\n        SS.Efficiency = MC.maths.clamp(SS.Efficiency + mod, 0.99, 1);\n        if (oldValue != SS.Efficiency) {\n            SS.DReport.setValues({ text: \"d : \" + SS.Efficiency.toFixed(4) });\n            SS.resetSpring();\n        }\n    }\n\n    \/\/ GUI elements\n    SS.Kdown = new MC.ConBox({\n        text: \"&lt;\",\n        type: \"c\",\n        width: 50,\n        pos: new MC.Point(35, 85),\n        onClick: function () { SS.incrementK(0); }\n    });\n\n    SS.Kup = SS.Kdown.clone();\n    SS.Kup.setValues({\n        text: \">\",\n        pos: new MC.Point(235, 85),\n        onClick: function () { SS.incrementK(1); }\n\n    });\n\n    SS.KReport = new MC.ConBox();\n    SS.KReport.setValues({\n        text: \"K: \" + SS.K,\n        colorBodyHover: SS.KReport.colorBody,  \/\/ Setting these means the colors will not change upon mouse hover over\n        colorEdgeHover: SS.KReport.colorEdge,\n        pos: new MC.Point(135, 85),\n        width: 200,\n        onClick: function () { } \/\/ required to silence the default onClick method\n    });\n\n    SS.Ddown = SS.Kdown.clone();\n    SS.Ddown.setValues({\n        pos: new MC.Point(300, 85),\n        onClick: function () { SS.incrementEff(0); }\n    });\n\n    SS.Dup = SS.Ddown.clone();\n    SS.Dup.setValues({\n        pos: new MC.Point(600, 85),\n        text: \">\",\n        onClick: function () { SS.incrementEff(1); }\n    });\n\n    SS.DReport = SS.KReport.clone();\n    SS.DReport.setValues({\n        text: \"d : \" + SS.Efficiency.toFixed(4),\n        pos: new MC.Point(450, 85),\n        onClick: function () { },\n        width: 300\n    });\n\n    \/\/ Add GUI elements to the GUI object\n    \/\/ N.B.  Placement Order = draw order, so e.g. the Kup\/down GUI elements are drawn after (and over) the KReport dummy element\n    SS.GUI.push(SS.KReport, SS.Kup, SS.Kdown, SS.DReport, SS.Ddown, SS.Dup);\n\n    \/\/ Finally finished defining the SS object.  Now to set the ..\n    \/\/ Mouse Handlers\n    MC.mouse.onClickL = function () {\n\n        SS.GUI.click();          \/\/ check the GUI upon click\n\n        if (SS.inBox()) {        \/\/ toggle selecting (if eligible)\n            SS.Selecting = true;\n            SS.Pen.vel.set(0, 0);\n            SS.Pen.acc.set(0, 0);\n        }\n        else { SS.Selecting = false; };\n    }\n\n    MC.mouse.onClickUpL = function () {\n        if (SS.Selecting) SS.Points = []; \/\/ clear existing line, if a legal mouse up\n        SS.Selecting = false;\n    }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ END OF declarations  \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/-----------------------------------------------------------------------------\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/      GAME LOOP       \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ first call, request subsequently made within\ngameLoop();\n\nfunction gameLoop() {\n    \/\/ ESSENTIAL MAINTAINANCE\n    requestAnimationFrame(gameLoop);\n    MC.game.update();                   \n    \n    \/\/ PHYSICS UPDATE LOOP\n    for (var i = 0; i &lt; MC.game.physicsUpdates; i++) {\n        SS.Pen.update();\n        SS.updateLines();\n    }\n    \n    \/\/ NON-PHYSICS UPDATES\n    SS.GUI.update();\n\n    \/\/ RENDER\n    \/\/ Stage 1.  Clear the canvas\n    MC.draw.clearCanvas(SS.BGColor);\n\n    \/\/ Stage 2.  Render Sprites\n    SS.Top.render();\n    SS.drawSpring();\n    MC.draw.polyLine(SS.Points, \"black\", 6);\n    SS.Pen.render();\n\n    \/\/ Stage 3.  Render GUI\n    MC.draw.text(\"Line = \" + SS.Points.length + \" Points\", new MC.Point(5, MC.canvas.height - 5));\n    MC.draw.text(\"Hooke's Law Spring Simulation\", new MC.Point(35, 40), SS.titleType);\n    MC.draw.text(\"drag pen @ bottom of Spring to reset\", new MC.Point(230, MC.canvas.height - 10), SS.titleType);\n    SS.GUI.render();\n\n}\n\n}); \/\/ EoF\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>The Spring project demonstrates some advanced concepts for the MC engine. The GUI work is non-trivial The &#8220;line&#8221; is made up of an array of MC.Point objects, which &#8211; Emulates the MC Sprite.update() method and uses the MC.game.deltaTime and MC.game.physicsUpdates variables in a physics loop (via the SS.updateLines() method) Has the array clean itself, in [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_oct_exclude_from_cache":false,"footnotes":""},"class_list":["post-419","page","type-page","status-publish","hentry","entry"],"_links":{"self":[{"href":"https:\/\/www.maxcanvas.org\/index.php?rest_route=\/wp\/v2\/pages\/419","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.maxcanvas.org\/index.php?rest_route=\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.maxcanvas.org\/index.php?rest_route=\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.maxcanvas.org\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.maxcanvas.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=419"}],"version-history":[{"count":9,"href":"https:\/\/www.maxcanvas.org\/index.php?rest_route=\/wp\/v2\/pages\/419\/revisions"}],"predecessor-version":[{"id":606,"href":"https:\/\/www.maxcanvas.org\/index.php?rest_route=\/wp\/v2\/pages\/419\/revisions\/606"}],"wp:attachment":[{"href":"https:\/\/www.maxcanvas.org\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=419"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}