MC Template

This page illustrates the basic MC Template. A very small project, which highlights the key essentials to get the new developer started. For this, you need 3 files.

  • The HTML File – this holds the HTML5 canvas element
  • The MC.js File – the engine itself
  • The Game File – in this case called MC Template.js

All these files can be downloaded from the Downloads page, but what follows should guide you through them.

HTML File

This file is the access point to your program. It can be stored locally, or if you want to show your project off, on a web server. Wherever you store it, make sure the other files are held in the correct directory structure, or edit the HTML appropriately.

<!DOCTYPE html>

<html>
    <head>
        <title>MC Template</title>
	<style type="text/css">
		html, body { margin: 0px;}
		canvas {display: block;}
	</style>
	<link rel="icon" href="Images/MCicon.png">
        <script type="text/javascript" src="JS/MC Template.js"></script>
	<script type="text/javascript" src="JS/MC.js"></script>
    </head>   
    <body> 
        <div id="mainDiv">	
              <canvas id="canvas" width="900" height="700"/><br>
	</div>
    </body>
</html>

So far, so HTML. Key points:

  • Line 5: Change the title to anything appropriate
  • Lines 6 – 9: A little in-line CSS to zero padding and margins
  • Line 10: This is the icon that will display on the browser tab. Change to taste (or delete).
  • Line 11: Make sure the “src” points to your Game File.
  • Line 12: As above, but points to the MC.js file
  • Line 16: The canvas element we will be displaying the game on. This template has 900 x 700. But it can be anything, and can be changed dynamically in the Game File to any size, or set to automatically fit the browser window.

The MC.js file

This one is simple too. Make sure you’ve downloaded the MC.js file (from Downloads) and that the HTML references it. Or as a lazy alternative, you can point it to “https://maxcanvas.org/MC/MC.js”.  I always keep the latest copy there.

WARNING: If you are so inclined, please note that the Author (that’s me, that is) reserves the right to update this file with no warning. And you’ll need an internet connection to get to it.

MC Template.js (the game file)

Now to the fun stuff. Once you get the HTML and reference to MC.js, all that remains is the game file. This is the file you will edit to make your creations. Of course, you’ll want to rename it “MyCoolGame.js” and update the HTML accordingly. This basic template has some heavily commented code and produces a simple scene with:

  • Circular Sprites, that bounce off each other and the game bounds (aka: the walls)
  • That have random colors
  • That are held and managed en-masse in a container (a SpriteBin)
  • The walls are set to the right hand 80% of the screen
  • The left 20% has a Graphical User Interface (GUI)
  • Which has a pause button, that responds to a user click

Here’s the code, please take time to read the comments. I spent some time on them ;p

// MaxCanvas Template
// Sample Game Starter JS File
//
// Required to drag MC.js into Intellisense
// thanks to https://visualstudiomagazine.com/blogs/tool-tracker/2018/07/use-javascript-code.aspx (Dec 2018)
/// <reference path="MC.js" />

// Gamecode is wrapped in .. window.onload = (function () { -- ALL CODE HERE --}); .. so game will start AFTER everything else is loaded

window.onload = (function() {

// AQUIRE HTML DOM CANVAS REFERENCE
//     HTML has to have a HTML5 canvas element tagged as "canvas"
var c=document.getElementById("canvas");

//////////////////////////
// INITIALISE MC Engine //
//////////////////////////
// CHOOSE a canvas size option // 

// CHOICE 1: Canvas Size fixed by HTML
MC.init(c);

// CHOICE 2: Full Window Option (Canvas will be resized to fit window)
//MC.init(c,"fullWindow");

// Configure .game
MC.game.setBounds(0, 1, 0.2, 1);  // parameters are 0-1 for (top, bottom, left, right) this example, 20% left hand side will be reserved for the GUI
MC.game.gravity.set(0,100);        // gravity this game
MC.game.physicsUpdates = 1;       // Simple example, no need for multiple physics Updates

///////////////////////////
// END OF Initialisation //
///////////////////////////
//-----------------------------------------------------------------------------
//////////////////////////
// VARIABLE DECLARATION //
//////////////////////////

    // Simple GUI Example.  Will Hold a "Pause" Button
    var ExampleGUI = new MC.GUI();      // GUI = holder for Control Boxes (MC.ConBox)
    var Pause = new MC.ConBox({ width: 150,
                                height: 40,
                                text: "Pause",
                                onClick: function () { MC.game.paused = !MC.game.paused; } 
                             });   // this ConBox function toggles the game pause.  When paused, Sprites do not update()
    ExampleGUI.push(Pause);  // Add the ConBox to the GUI
    MC.mouse.onClickL = function () { // configure MC.game so it checks the GUI upon Left click down 
        ExampleGUI.click();
        // Feel free to add further code for Left Clicks here 
    };    
    
    // Example SpriteBin which will hold a number of MC.Sprites
    var ExampleSpriteBin = new MC.SpriteBin();    
    
    // But first let's define a "Sprite Factory" which will return fully fledged Sprites upon request
    function spriteFactory () {
        // When called create, a Sprite
        var mySprite = new MC.Sprite({  type: "circ",
                                        size1: 25,
                                        pos: new MC.Point(MC.maths.randBetween(MC.canvas.left + 30, MC.canvas.right - 30), MC.maths.randBetween(30, MC.canvas.bottom - 30)),
                                        vel: new MC.Point(MC.maths.randBetween(-150, 150), MC.maths.randBetween(-150, 150)), // velocity is in Pixel's per Second
                                        edgeBounce: true,   // we want these to bounce inside the Bounds
                                        gravity: true,      // gravity will be applied to these Sprites
                                        fillColor: MC.utils.randomColor(),
                                        edgeColor: MC.utils.randomColor()
            });
        // Let's pretend we forgot this, values can be changed after creation
        mySprite.setValues({edgeWidth : 3 });
        return mySprite;     // return the newly created Sprite
    }
    
    // Now to populate the SpriteBin with 15 of them
    for (var i = 0; i < 15; i++) {
        ExampleSpriteBin.push( spriteFactory() );
    }


//////////////////////////
// END OF declarations  //
//////////////////////////
//-----------------------------------------------------------------------------
//////////////////////////
//      GAME LOOP       //
//////////////////////////

// first call, request subsequently made within
gameLoop();

function gameLoop() {
    // ESSENTIAL MAINTAINANCE
    requestAnimationFrame(gameLoop);    // Required so the PC will automatically call the gameLoop again when (1) the screen is ready and (2) the CPU has finished any previous frame calculations
    MC.game.update();                   // Essential to update MC.game to ensure MC.game.deltaTime is available
    
    // PHYSICS UPDATE LOOP
    for (var i = 0; i < MC.game.physicsUpdates; i++) {
        ExampleSpriteBin.update();      // calls update on all Sprites in the bin.  So moves them.
        ExampleSpriteBin.bounce();      // for fun, let's bounce the contents of the bin off themselves
            // Add Further Sprite and SpriteBin updates here
    }
    
    // NON-PHYSICS UPDATES
    ExampleGUI.update();    // calls update on all ConBoxes in the GUI.  Required so they can change colour if the mouse "hovers" over them
        // Add further game logic here

    // RENDER
    // Stage 1.  Clear the canvas
    // COULD USE  MC.draw.clear("Black");  ... if it was a full canvas application, but we want the "bounds" to be a different colour
    MC.draw.clearInBounds("Black");     // CSS / HTML5 Color strings can be used
    MC.draw.clearOutBounds("Olive");
    
    // Stage 2.  Render Sprites
    ExampleSpriteBin.render();
    
    // Stage 3.  Render GUI
    ExampleGUI.render(0,0);
}

}); // EoF

And that’s it ! If you got it right, when you load the HTML in your web browser (I prefer Google Chrome btw) … you should see something like this.

PRESS F5 NOW

Be warned, the MaxCanvas has insecurity issues and likes to be the centre of attention. When the “focus” is off it, it can misbehave. This varies between browsers and is a known issue. Don’t let it put you off. There are work-around’s you’ll figure out later. And an F5 always kicks it back into shape.