GAME Instance
Create a new GAME instance
- To create a new game instance, you need to use the GAME constructor.
- Inside your custom script file and inside your jQuery $(document).ready function, create a new variable and asign it a new GAME instance using the new keyword.
- Your syntax should look similar to this: var MyGame = new GAME(.......);
- Whenever you see MyGame in this documentation, it refers to this variable, which contains your GAME instance.
- Inside the parentheses, you need to specify a few parameters. These are: (canvasID, canvasWidth, canvasHeight, fpsLimit, imageSources, audioSources, callback)
- STRING canvasID - The HTML ID of the canvas you want to display the game to. Canvas needs to be already created in the HTML.
- NUMBER width - The width of the canvas. Use -1 to automatically adjust canvas width to fit the whole window.
- NUMBER height - The height of the canvas. Use -1 to automatically adjust canvas height to fit the whole window.
- NUMBER fps - The FPS limit of the game. Use 60 for best results. Too low FPS can cause physics problems.
- OBJECT imageSources - All the images (textures, etc.) the game will need. Create this object beforehand and using this format: {internalName:"url/to/image.png", img2:"test.jpg"}
- OBJECT audioSources - All the audio files (music, sounds, etc.) the game will need. Create this object beforehand and using this format: {internalName:"url/to/sound.mp3", audio2:"test.mp3"}
- FUNCTION callback - The function to run when the game instance is created and all images/sounds are loaded. Treat this function as the MAIN function (as it is known in other programming languages.
- Now that you have created your game instance, you can add objects in the game, attach events and run custom scripts.
- Remember to write all your initial scripts in the callback function (or MAIN, whatever you wanna call it). You should create any of your own functions outside the MAIN function though.
- IMPORTANT!!! - The game starts off in a paused state. You need to write MyGame.start(); at the bottom of your MAIN function to make it start running!
Internal GAME instance structure
Every GAME instance has many properties, some of which are defined by the user, while many others are not.
Here is a complete list of these properties:
- HTML_ELEMENT canvas - This holds the canvas element which the game draws on.
- CANVAS_2D_CONTEXT ctx - The canvas context. Used to draw everything on screen. Can be used for standard canvas functions, like beginPath() etc.
- NUMBER width - The current real canvas width in pixels.
- NUMBER height - The current real canvas height in pixels.
- NUMBER midX - The middle of the canvas width in pixels. Shorthand for width/2.
- NUMBER midY - The middle of the canvas height in pixels. Shorthand for height/2.
- NUMBER canvasX - The current X origin of the canvas. Higher number coresponds to viewport moving to the left. DO NOT MODIFY, for moving the canvas, use MyGame.moveCanvas(), MyGame.moveCanvasTo() or MyGame.centerCanvasTo().
- NUMBER canvasY - The current Y origin of the canvas. Higher number coresponds to viewport moving upwards. DO NOT MODIFY, for moving the canvas, use MyGame.moveCanvas(), MyGame.moveCanvasTo() or MyGame.centerCanvasTo().
- NUMBER setWidth - The desired width of the canvas. If set to -1, the canvas will automatically adjust itself to always fill the entire width of the screen. Use MyGame.updateCanvasSize() to change this value.
- NUMBER setHeight - The desired height of the canvas. If set to -1, the canvas will automatically adjust itself to always fill the entire height of the screen. Use MyGame.updateCanvasSize() to change this value.
- NUMBER zoom - The current zoom level of the canvas. Higher number means closer zoom. DO NOT MODIFY, for zooming the canvas, use MyGame.zoomCanvas() or MyGame.centerCanvasTo().
- BOOL staticBackground - True = background follows the viewport position, false = background stays static. You should use MyGame.setBackground() to change background properties.
- NUMBER backgroundWidth - The width of the background image. DO NOT MANUALLY CHANGE THIS!
- NUMBER backgroundHeight - The height of the background image. DO NOT MANUALLY CHANGE THIS!
- NUMBER backgroundDistance - The distance effect of the background. The higher the number, the farther will the background appear to be, when moving the viewport. 1 = background moves exactly with the foreground, 2 = background moves half as much as the foreground, 0.5 = (probably undesired effect) background moves twice as much, similar effect to looking through a telescope.
- NUMBER speed - The speed of the simulation. 0.5 = slow motion (half speed), 2 = fast-forward (2x speed).
- NUMBER tickSpeed - The length of each tick in milliseconds (tickSpeed = 1000/fps).
- TIMESTAMP lastTick - The UNIX timestamp (custom object) of the last tick.
- NUMBER tickTime - The time passed between current tick and lastTick in seconds. Used for all motion calculations. Very useful for custom functions that calculate some movement.
- BOOL paused - If the game is in paused state. Every GAME instance starts in paused state. DO NOT CHANGE THIS VALUE! Use MyGame.start() and MyGame.stop() functions for starting/pausing the game.
- NUMBER tickCount - The complete number of ticks since the game started. Does not get reset and is incremented by one every tick. Can be used for creating objects with unique names each tick.
- NUMBER collisionCount - The number of collisions that occured in the current tick. Not used for anything by the engine itself.
- BOOL drawCollisions - Debug setting. When true, draws all collision points on screen as small red circles.
- NUMBER cursorX - The X position of the mouse cursor over the canvas element in pixels. Changes every time the mouse moves.
- NUMBER cursorY - The Y position of the mouse cursor over the canvas element in pixels. Changes every time the mouse moves.
- NUMBER mouseX - The X coordinate of the mouse position projected into the game coordinate system. Changes every time the mouse moves.
- NUMBER mouseY - The Y coordinate of the mouse position projected into the game coordinate system. Changes every time the mouse moves.
- NUMBER cursorLastX, cursorLastY, mouseLastX, mouseLastY - Self explanatory. The previous values of all the mouse coordinates.
- OBJECT events - An object holding all the event functions. You can attach your own function to these events using the MyGame.attachEvent() function, or you can replace it directly like this: MyGame.events.tick = function() {/*Your code*/}.
- OBJECT geometry - An object holding all the geometry objects loaded in the game. DO NOT MODIFY! Use MyGame.createObj() and MyGame.deleteObj() instead.
- OBJECT entity - An object holding all the entity objects loaded in the game. DO NOT MODIFY! Use MyGame.createObj() and MyGame.deleteObj() instead.
- NUMBER numGeometry - The number of geometry objects in the game. DO NOT MODIFY!
- NUMBER numEntity - The number of entity objects in the game. DO NOT MODIFY!
- ARRAY geomLayers - All the geometry objects separated into their coresponding layers. Used to optimize rendering. DO NOT MODIFY!
- ARRAY entLayers - All the entity objects separated into their coresponding layers. Used to optimize rendering. DO NOT MODIFY!
- OBJECT texture - All the textures will be loaded into this object as CANVAS PATTERN objects, after the engine is finished loading (all done before the callback function is run). The individual names are the same as the names defined in the imageSources object. DO NOT MODIFY! You cannot load any more images after the GAME instance is created!
- OBJECT audio - All loaded audio elements will be in this object after loading. The individual names are the same as names defined in the audioSources object. Use standard HTML Audio element functions to play / control these. DO NOT MODIFY! You cannot load any more sounds after the GAME instance is created!
- STRING / CANVAS_PATTERN missingTexture - The default texture which is used, if object's texture didn't load properly or if none is provided. This value is a string containing a purple color (in the canvas color format) at first, but is replaced by a CANVAS PATTERN of a missing texture (defined as base64 image) immediately after it is loaded.
Tick flow
Here is a description of all the steps that happen during every tick (in order):
- Cancel all other tick requests (in case there are any) to prevent accidental duplication of the tick loop.
- Schedule the next tick.
- Reset collision count from previous tick.
- Get the time that passed since the last tick ran. Used for all physics calculations.
- Execute the user-specified "beforeTick" event.
- Calculate the new motion and position of all the moveable entities.
- Go through all the entities and check for collisions with all the other entities. The following happens with each pair:
- If the entities are intersecting, separate them.
- If the entities are intersecting at their new positions, continue. If not, skip all this and go check other entity pair.
- Calculate the relative time of collision.
- Push all the information about the collision into a collisionList array.
- Sort all found collisions by time of occurence.
- Resolve all collisions (calculate new motions and positions).
- Execute the user-specified "tick" event.
- Render all visible objects on their coresponding layers.
- If the debug setting drawCollisions is enabled, draw all collision points as small red circles.
- Increment the tickCount.
Rendering layers
Rendering layers can be thought of as different planes of the canvas, or the distance of the given object on the Z axis.
These layers are used to render all the objects in an ordered fashion, such that the foreground objects will be on top of the background objects.
Objects in certain layers are treated as purely aesthetic, and will act as non-solid, which means that they will not collide with anything.
Additionally, Geometry objects and Entities have each their own set of layers, which are then stacked on top of each other in the rendering process.
This is the order of these layers (from the bottom-most to the top-most layer), as well as their intended usage:
- Geometry layer (-1): Used for background geometry, like background walls. These objects don't cause collisions.
- Entity layer (-2): Used for entities that are behind the main level geometry. No collisions.
- Geometry layer (0): Used for main level Geometry objects, like floors, platforms, walls, etc. These objects obviously cause collisions.
- Entity layer (-1): Used for entities, that are behind the main set of entities (like behind the player). Collisions do work here.
- Entity layer (0): Used for the main set of entities. The player entity should be on this layer. Collisions obviously work here.
- Entity layer (1): Used for the entities, that are in front of the main set of entities (like in front of the player). Collisions work here.
- Geometry layer (1): Used for foreground geometry, like pillars or front walls. These objects don't cause collisions.
- Entity layer (2): The top-most layer, used for foreground entities, like birds or even custom GUI elements. There are no collisions of course.
Object structures
Shape structure
There are two types of shapes - ShapeRect and ShapeCircle.
Both shapes are created as an instance of their coresponding constructor.
Their only difference is, that rectangles are defined with width and height, whereas circles are defined with radius.
All the other properties are the same, so I will not be making any difference between them.
new ShapeRect(NUMBER width, NUMBER height, CANVAS_PATTERN / STRING texture, NUMBER outlineWidth, CANVAS_PATTERN / STRING outlineTexture)
OR
new ShapeCircle(NUMBER radius, CANVAS_PATTERN / STRING texture, NUMBER outlineWidth, CANVAS_PATTERN / STRING outlineTexture)
- NUMBER width, height / NUMBER radius - The width and height or radius of the shape. Both width and height are saved with their value divided by 2, because halves are used much more often than the full sizes.
- CANVAS_PATTERN / STRING texture - The texture of the shape. You can provide rgb or rgba colors inside a string, or use the rgb() / rgba() functions to generate those automatically. Otherwise, you can provide an image in the CANVAS PATTERN format, all of which are automatically created from all the loaded images at initialization and can be found in MyGame.texture.YOUR_TEXTURE_NAME.
- NUMBER outlineWidth - Optional value. Objects don't have outlines by default. If you want an outline, set this number to be your desired width of the outline.
- CANVAS_PATTERN / STRING outlineTexture - Required only if outlineWidth is also defined. The texture of the outline. The same rules as with the main texture apply here.
Internal Shape structure
These are all the parameters and their exact names, that are saved inside a Shape object:
- STRING shape - The shape of the Shape (if that makes sense). Can be either "rect" or "circle".
- NUMBER width, NUMBER height / NUMBER r - If the shape is a rectangle: The half of the width and the half of the height (each stored separately). If it's a circle: the radius of the circle.
- OBJECT style
- CANVAS_PATTERN / STRING texture - The texture of the shape. Can be either a string in the canvas color format, or an image in the CANVAS PATTERN format.
- NUMBER outlineWidth - The width of the outline. Is set to undefined, if the shape has no outline.
- CANVAS_PATTERN / STRING outlineTexture - The texture of the outline. Can be either a string in the canvas color format, or an image in the CANVAS PATTERN format. Is set to undefined, if the shape has no outline.
Geometry info
Geometry objects are immoveable objects, that are used to create the game level.
They are used for floors, walls, and other similar objects.
new Geometry(SHAPE shape, BOOL solid, BOOL visible)
- SHAPE shape - A shape object, either ShapeRect or ShapeCircle.
- BOOL solid - True = solid, false = not solid, other objects can pass through it.
- BOOL visible - True = visible, false = invisible, won't be rendered.
Internal Geometry structure
These are all the parameters and their exact names, that are saved inside a Geometry object:
- STRING shape - The shape of the object. Can be either "rect" or "circle".
- NUMBER width, NUMBER height / NUMBER r - If the object is a rectangle: The half of the width and the half of the height (each stored separately). If it's a circle: the radius of the circle.
- OBJECT style
- CANVAS_PATTERN / STRING texture - The texture of the object. Can be either a string in the canvas color format, or an image in the CANVAS PATTERN format.
- NUMBER outlineWidth - The width of the outline. Is set to undefined, if the object has no outline.
- CANVAS_PATTERN / STRING outlineTexture - The texture of the outline. Can be either a string in the canvas color format, or an image in the CANVAS PATTERN format. Is set to undefined, if the object has no outline.
- BOOL solid - If the object is solid. True = solid, false = not solid, other objects can pass through it.
- BOOL visible - If the object will be rendered. True = visible, false = invisible.
Internal Geometry structure AFTER LOADED INTO THE GAME
The Geometry object gains these additional properties, after it is put into the game:
- STRING name - The unique name of the object.
- NUMBER x - The X coordinate of the object.
- NUMBER y - The Y coordinate of the object.
- NUMBER layer - The layer on which the object is located (-1 to 1).
Entity info
Entities are all moveable objects.
They are used for boxes, moving platforms, projectiles, but most importantly - for the player.
They use the same first 3 properties as Geometry objects.
new Entity(SHAPE shape, BOOL solid, BOOL visible, BOOL physics, NUMBER mass, NUMBER bounce, NUMBER airResistance, NUMBER friction, NUMBER gravity)
- SHAPE shape - A shape object, either ShapeRect or ShapeCircle.
- BOOL solid - True = solid, false = not solid, other objects can pass through it.
- BOOL visible - True = visible, false = invisible, won't be rendered.
- BOOL physics - True = entity can move, false = entity is immoveable and stays frozen in place.
- NUMBER mass - The mass of the entity. This doesn't affect gravity! (As it shouldn't.)
- NUMBER bounce - The elasticity of the entity. 0 = not at all bouncy, 1 = completely bouncy.
- NUMBER airResistance - The speed damping of the entity in air. 0 = no slowing down, 1 = fairly quick slow-down to full stop, >1 = even quicker slow-down.
- NUMBER friction - The speed damping of the entity when touching something. Same rules apply here as with airResistance.
- NUMBER gravity - This value is optional. Default gravity is 9.8, 0 = no gravity.
Internal Entity structure
These are all the parameters and their exact names, that are saved inside an Entity object:
- STRING shape - The shape of the entity. Can be either "rect" or "circle".
- NUMBER width, NUMBER height / NUMBER r - If the entity is a rectangle: The half of the width and the half of the height (each stored separately). If it's a circle: the radius of the circle.
- OBJECT style
- CANVAS_PATTERN / STRING texture - The texture of the entity. Can be either a string in the canvas color format, or an image in the CANVAS PATTERN format.
- NUMBER outlineWidth - The width of the outline. Is set to undefined, if the entity has no outline.
- CANVAS_PATTERN / STRING outlineTexture - The texture of the outline. Can be either a string in the canvas color format, or an image in the CANVAS PATTERN format. Is set to undefined, if the entity has no outline.
- BOOL solid - If the entity is solid. True = solid, false = not solid, other objects can pass through it.
- BOOL visible - If the entity will be rendered. True = visible, false = invisible, won't be rendered.
- BOOL physics - If any forces can act upon this entity. True = entity can move, false = entity is immoveable and stays frozen in place.
- NUMBER mass - The mass of the entity.
- NUMBER bounce - The elasticity of the entity. 0 = not at all bouncy, 1 = completely bouncy.
- NUMBER airResistance - The speed damping of the entity in air. 0 = no slowing down, 1 = fairly quick slow-down to full stop, >1 = even quicker slow-down.
- NUMBER friction - The speed damping of the entity when touching something. Same rules apply here as with airResistance.
- NUMBER gravity - Set to 9.8 by default.
Internal Entity structure AFTER LOADED INTO THE GAME
The Entity object gains these additional properties, after it is put into the game:
- STRING name - The unique name of the entity.
- NUMBER x - The X coordinate of the entity.
- NUMBER y - The Y coordinate of the entity.
- NUMBER layer - The layer on which the entity is located (-2 to 2).
- OBJECT lastPos
- NUMBER x - The previous X coordinate of the entity.
- NUMBER y - The previous Y coordinate of the entity.
- VECTOR motion
- NUMBER x - The motion of the entity in the X direction (in pixels per second).
- NUMBER y - The motion of the entity in the Y direction (in pixels per second).
- VECTOR move
- NUMBER x - The change of the X coordinate of the entity.
- NUMBER y - The change of the Y coordinate of the entity.
- VECTOR force
- NUMBER x - The force on the entity in the X direction. Gets reset every tick, after the force is applied.
- NUMBER y - The force on the entity in the Y direction. Gets reset every tick, after the force is applied.
- BOOL surface - If the entity is currently touching any surface.
User engine functions
Overview
User engine functions are functions, which are defined as prototype and are tied to every GAME instance.
Some of these are used by the engine itself, while others are not.
There is also a handful of other functions, which are also tied to the GAME instance, but these have been all left out of this documentation, because they don't have any purpose for the user, as they are only used internally.
To call any of these functions, use MyGame.the_wanted_function().
attachEvent(STRING event_name, FUNCTION callback)
This function is used for attaching custom functions to specific engine events.
See the "Engine events" section for more info, or to see what each event does.
- STRING event_name - The name of the event you want your function to be attached to.
- FUNCTION callback - The function to execute, when the event gets fired.
updateCanvasSize(NUMBER width, NUMBER height, BOOL redraw)
This function is used for resizing the canvas.
- NUMBER width - The new width of the canvas. If set to -1, the canvas will automatically adjust to always fill the entire width of the screen.
- NUMBER height - The new height of the canvas. If set to -1, the canvas will automatically adjust to always fill the entire height of the screen.
- BOOL redraw - If the game should re-render the content on the resized canvas. True = force the game to re-render, false = apply the changes, but do not immediately re-render the content. This should be set to true in most cases.
moveCanvas(STRING direction, NUMBER amount, BOOL usePixels, BOOL redraw)
Moves the canvas viewport in the specified direction by the specified amount.
- STRING direction - The direction in which to move the canvas viewport. ("left", "right", "up", "down")
- NUMBER amount - The move amount.
- BOOL usePixels - What scale to use when the canvas is at different zoom level. True = canvas viewport will be moved by pixels seen on screen, no matter which zoom level it's at. False = canvas viewport will be moved relative to game coordinate system, which will look differently on different zoom levels.
- BOOL redraw - If the changes should be seen immediately. True = force the game to re-render, false = apply the changes, but do not immediately re-render the content. Use false when using this function while the game is running, as it will automatically re-render every tick, so forcing it to re-render immediately would be useless and wasteful.
moveCanvasTo(NUMBER x, NUMBER y, BOOL redraw)
Moves the canvas viewport's top-left corner to the specified coordinates.
For moving the canvas center, use MyGame.centerCanvasTo().
- NUMBER x - The new x coordinate of the canvas viewport's top-left corner.
- NUMBER y - The new y coordinate of the canvas viewport's top-left corner.
- BOOL redraw - If the changes should be seen immediately. True = force the game to re-render, false = apply the changes, but do not immediately re-render the content. Use false when using this function while the game is running, as it will automatically re-render every tick, so forcing it to re-render immediately would be useless and wasteful.
centerCanvasTo(NUMBER x, NUMBER y, NUMBER newZoom, BOOL redraw)
Centers the canvas viewport to the specified coordinates.
- NUMBER x - The x coordinate the canvas should center to.
- NUMBER y - The y coordinate the canvas should center to.
- NUMBER newZoom - Optional value. If specified, canvas will be zoomed in the process. You can set this to false to skip this value.
- BOOL redraw - If the changes should be seen immediately. True = force the game to re-render, false = apply the changes, but do not immediately re-render the content. Use false when using this function while the game is running, as it will automatically re-render every tick, so forcing it to re-render immediately would be useless and wasteful.
zoomCanvas(NUMBER zoomLevel, BOOL redraw)
Sets the canvas zoom to specified level, focused on the center.
- NUMBER zoomLevel - The new zoom level of the canvas. 1 = default, 2 = zoomed-in, 0.5 = zoomed out.
- BOOL redraw - If the changes should be seen immediately. True = force the game to re-render, false = apply the changes, but do not immediately re-render the content. Use false when using this function while the game is running, as it will automatically re-render every tick, so forcing it to re-render immediately would be useless and wasteful.
resetCanvas(BOOL redraw)
Resets the canvas position and zoom to default values - X = 0, Y = 0, Zoom = 1.
- BOOL redraw - If the changes should be seen immediately. True = force the game to re-render, false = apply the changes, but do not immediately re-render the content. Use false when using this function while the game is running, as it will automatically re-render every tick, so forcing it to re-render immediately would be useless and wasteful.
setBackground(STRING image / color, BOOL isImage, BOOL static, NUMBER distance)
Sets a background texture for the canvas.
This texture is set as a css style of the canvas, and isn't rendered by the canvas itself in any way. The canvas is always transparent on the pixels, where there isn't any content.
- STRING image / color - The new texture for the canvas. For specifying images, use the image URL, not a texture! For specifying color, use the rgb() / rgba() functions. If you specify color, not an image, you can leave all the following parameters empty.
- BOOL isImage - True = the previous parameter was an image, false = the previous parameter was a color.
- BOOL static - If the backgound should be static. True = the background will not move, false = the background will follow the movement of the canvas. If the background is not an image, it will always be static.
- NUMBER distance - The distance effect of the background. The higher the number, the farther will the background appear to be when moving the canvas. 1 = background moves exactly with the foreground, 2 = background moves half as much as the foreground, 0.5 = (probably undesired effect) background moves twice as much, similar effect to looking through a telescope.
reposBackground(NUMBER x, NUMBER y)
This function is not really for general use.
It will fake the movement of the canvas, so that the background will look like it's following it.
This function is also used internally by the engine itself to make the background actually follow the real canvas movement. If you want to override this by your own movement, the background needs to be static.
- NUMBER x - The fake X position of the canvas, according to which the background should be moved.
- NUMBER y - The fake Y position of the canvas, according to which the background should be moved.
clearCanvas()
This function clears the visible area of the canvas viewport.
Used internally by the engine everytime any rendering is done, because the canvas needs to be cleared before anything new gets drawn on it.
drawRect(NUMBER center_x, NUMBER center_y, NUMBER half_width, NUMBER half_height, CANVAS_PATTERN / STRING texture, NUMBER outlineWidth, CANVAS_PATTERN / STRING outlineTexture)
Draws a rectangle in the specified position with the specified parameters.
The outline is optional and can be left empty.
- NUMBER center_x - The X coordinate of the center of the rectangle.
- NUMBER center_y - The Y coordinate of the center of the rectangle.
- NUMBER half_width - Half of the width of the rectangle. The distance from it's center to it's side.
- NUMBER half_height - Half of the height of the rectangle. The distance from it's center to it's top / bottom.
- CANVAS_PATTERN / STRING texture - The texture of the rectangle. Either provide a color using the rgb() / rgba() functions, or provide an image in the CANVAS PATTERN format. You can use the pre-converted textures in MyGame.texture or convert your own image using the MyGame.createTexture() function.
- NUMBER outlineWidth - Optional value. The width of the outline.
- CANVAS_PATTERN / STRING outlineTexture - If outlineWidth is specified, this needs to be specified too. The texture of the outline. Same rules apply here as with the main texture.
drawCircle(NUMBER center_x, NUMBER center_y, NUMBER radius, CANVAS_PATTERN / STRING texture, NUMBER outlineWidth, CANVAS_PATTERN / STRING outlineTexture)
Draws a circle in the specified position with the specified parameters.
The outline is optional and can be left empty.
- NUMBER center_x - The X coordinate of the center of the circle.
- NUMBER center_y - The Y coordinate of the center of the circle.
- NUMBER radius - The radius of the circle. The distance from the center to the edge.
- CANVAS_PATTERN / STRING texture - The texture of the circle. Either provide a color using the rgb() / rgba() functions, or provide an image in the CANVAS PATTERN format. You can use the pre-converted textures in MyGame.texture or convert your own image using the MyGame.createTexture() function.
- NUMBER outlineWidth - Optional value. The width of the outline.
- CANVAS_PATTERN / STRING outlineTexture - If outlineWidth is specified, this needs to be specified too. The texture of the outline. Same rules apply here as with the main texture.
drawLine(NUMBER start_x, NUMBER start_y, NUMBER end_x, NUMBER end_y, NUMBER width, CANVAS_PATTERN / STRING texture)
Draws a line from the starting point to the end point with the specified parameters.
- NUMBER start_x - The X coordinate of the starting position of the line.
- NUMBER start_y - The Y coordinate of the starting position of the line.
- NUMBER end_x - The X coordinate of the end position of the line.
- NUMBER end_y - The Y coordinate of the end position of the line.
- NUMBER width - The width of the line.
- CANVAS_PATTERN / STRING texture - The texture of the line. Either provide a color using the rgb() / rgba() functions, or provide an image in the CANVAS PATTERN format. You can use the pre-converted textures in MyGame.texture or convert your own image using the MyGame.createTexture() function.
drawText(STRING text, NUMBER x, NUMBER y, BOOL centered, STRING fontStyle, CANVAS_PATTERN / STRING texture, NUMBER outlineWidth, CANVAS_PATTERN / STRING outlineTexture)
Draws text on the canvas in the specified location with the specified parameters.
- STRING text - The text you want to draw.
- NUMBER x - The X coordinate of the text.
- NUMBER y - The X coordinate of the text.
- BOOL centered - If the X,Y coordinates should corespond to the center of the text. True = the text will be centered at the X,Y coordinates, false = the X,Y coordinates will corespond to the top-left corner of the text.
- STRING fontStyle - The style of the text in the canvas font style format. Use the MyGame.createFontStyle() function to easily generate this style.
- CANVAS_PATTERN / STRING texture - The texture of the text. Either provide a color using the rgb() / rgba() functions, or provide an image in the CANVAS PATTERN format. You can use the pre-converted textures in MyGame.texture or convert your own image using the MyGame.createTexture() function.
- NUMBER outlineWidth - Optional value. The width of the outline of the text.
- CANVAS_PATTERN / STRING outlineTexture - If outlineWidth is specified, this needs to be specified too. The texture of the outline of the text. Same rules apply here as with the main texture.
measureText(STRING text, STRING fontStyle, NUMBER outlineWidth)
Get the width of the text in pixels.
This is the only way to know, how much space will the text take up on the canvas.
If you need to know the height of the text instead, you just need to know the font size of the text, as it directly coresponds with the height of the text in pixels. (If the text has an outline, you need to take that into account too.)
- STRING text - The text you want to measure.
- STRING fontStyle - The style of the text in the canvas font style format. Use the MyGame.createFontStyle() function to easily generate this style.
- NUMBER outlineWidth - Optional value. The width of the outline of the text.
createTexture(HTML_IMAGE image)
Create a CANVAS PATTERN from the given image.
This image needs to be an actual Image Element, not just a link.
The image also needs to be already loaded, or this function will fail.
- HTML_IMAGE image - The image you want to convert to the CANVAS PATTERN texture.
createFontStyle(NUMBER fontSize, NUMBER boldLevel, NUMBER italicLevel, STRING fontFamily)
Generates a string in the canvas font style format.
Used for drawing text on the canvas.
Only the fontSize value is required, other parameters are optional. The default fontFamily will be Arial.
- NUMBER fontSize - The size of the font in pixels. This value coresponds with the actual height of the text, when it is drawn on the canvas.
- NUMBER boldLevel - The strength of the bold effect. 1 = bold, 2 = extra bold, any other value = not bold.
- NUMBER italicLevel - The strength of the italic effect. 1 = italic, 2 = twice as italic, any other value = not italic.
- STRING fontFamily - The name of the font family you want to use. Default is Arial.
createObj(GEOMETRY / ENTITY object, STRING name, NUMBER x, NUMBER y, NUMBER layer)
Puts an object into the game. Can be either Geometry or Entity object.
This is the only way to actually put objects into the game. The object you're trying to put into the game should already be created beforehand, using the Geometry / Entity constructor.
- GEOMETRY / ENTITY object - The object you want to put into the game.
- STRING name - The UNIQUE name of the object, specific to object type. You can have a Geometry object with the same name as an Entity object, but you cannot have two objects in the same category with the same name.
- NUMBER x - The X coordinate where to put the object (center).
- NUMBER y - The Y coordinate where to put the object (center).
- NUMBER layer - The rendering layer on which to put the object. Read the "Rendering layers" section to learn more. Can range from -1 to 1 for Geometry objects, and -2 to 2 for Entity objects.
deleteObj(GEOMETRY / ENTITY object)
Permamently deletes an object from the game.
This is the only way to truly remove an object from the game. The object you're trying to remove needs to be an actual in-game object, not just it's name.
- GEOMETRY / ENTITY object - The object you want to remove from the game.
getObjectAtPos(NUMBER x, NUMBER y, BOOL onlyOne, BOOL searchGeometry, BOOL searchEntity)
Checks which objects are located at the given coordinates.
Goes through all the objects in the order they appear on screen and checks if they intersect with the given coordinates.
Only the first two parameters need to be specified, the rest will be set to default values (true, false, true).
- NUMBER x - The X coordinate of the check.
- NUMBER y - The Y coordinate of the check.
- BOOL onlyOne - True = the search will stop after an object is found (returns the object itself, or returns false if no object was found), false = the search will go through all the objects (returns an array with all the objects, or empty array). Is set to true by default.
- BOOL searchGeometry - If the search should be looking for Geometry objects. False by default.
- BOOL searchEntity - If the search should be looking for Geometry objects. False by default.
collisionCheck(GEOMETRY / ENTITY object1, GEOMETRY / ENTITY object2, BOOL useNewPosition)
Checks if objects are overlaping each other.
It doesn't matter, if the objects aren't solid.
- GEOMETRY / ENTITY object1 - The first object check.
- GEOMETRY / ENTITY object2 - The second object to check with.
- BOOL useNewPosition - Optional value. True = objects will be checked at their new positions (after all physics have been applied), false = objects will be checked at their previous positions before the tick happened. This is set to true by default.
start()
Starts / continues the game loop.
This function needs to be called after the game is created, because every game starts off in the paused state.
The current state of the game can be found in MyGame.paused.
stop()
Stops (pauses) the game loop.
The current state of the game can be found in MyGame.paused.
tick()
Runs the game's tick function.
This function runs automatically when the game is running. Do not interfere with it.
Useful only in rare cases, mainly for running something in step mode.
render()
Runs the game's rendering function.
This function runs automatically at the end of each tick.
Clears the canvas and then draws all game objects on it.
Running this function manually doesn't have many uses. It could, however, be used when the game is in paused state and you are using a custom GUI menu.
Custom Game Utilities (G)
Overview
These utilities are not tied to the GAME instance. They are separate functions and constants located inside an global object called G.
Some of these are used by the engine itself, mainly for collision detection, while others are there just for the user.
To call any of these functions, use G.the_wanted_function().
instances[]
This array holds reference to all the GAME instances, that have been created.
key{}
This object holds name-value pairs of key names and their ids.
This is very useful when deciding, which keys have been presed in the engine event "keydown" or "keyup".
This might look something like this: if(pressed_key_ID === G.key.up) //do something.
keyActive(NUMBER keyID)
This function checks a keyStates array to see, if the given key is currently being pressed down.
This can be used in combination with the G.key object, which may look something like this: if(G.keyActive(G.key.up)) //do something.
mouseActive{}
This object holds the states of the three mouse buttons.
They are simply named left, middle and right, and are all boolean values.
isMobile
This is a simple boolean constant, which specifies, if the user is using a touchscreen device.
There is a small problem, that if the user is using a laptop with touchscreen display, this constant will also be true, but in general, it is a easy check if the user is using a smartphone.
saveToFile(STRING filename, STRING extension, ANY_TYPE data)
This function converts the provided data into a JSON string format, puts it into a file and then triggers a download of this file.
- STRING filename - The name of the file, that will be downloaded.
- STRING extension - The extension of the file (without the dot). Use txt in most cases.
- ANY_TYPE data - The data that will be put into the file. This data can be anything, in most cases you would want to use an array. WARNING - After saving custom object types (like Entity or Vector), they will not remember their type!
openFileDlg(FUNCTION callback)
This function opens the file dialogue window, which let's the user select a file on their computer.
WARNING - If the user closes the file dialogue and doesn't choose a file, the callback won't be run at all (it's not possible to detect). You need to account for this yourself.
- FUNCTION callback - The function to run, when the user selects a file.
If the user selects a file, the callback function will be run with three parameters passed to it.
- FILE file - The opened file itself. Must be read using the G.readFile() function, before it is of any use.
- STRING fileName - The complete name of the opened file, including the extension.
- NUMBER fileSize - The size of the opened file (in bytes).
readFile(FILE file, BOOL parse, FUNCTION callback)
This function reads the contents of the provided file.
- FILE file - The file you want to read. Use G.openFileDlg() let the user select a file first.
- BOOL parse - If the contents of the file should be parsed as JSON. True = the callback will return the parsed data as javascript variable, false = the callback will return the contents of the file as a string.
- FUNCTION callback - The function to call when the file is read. Passes one variable, which will either hold the whole file contents as a string, or it will hold the parsed content directly, depending on the last setting.
getDistance(NUMBER start_x, NUMBER start_y, NUMBER end_x, NUMBER end_y)
This function calculates the pythagorean distance between two points.
- NUMBER start_x - The X coordinate of the first point.
- NUMBER start_y - The Y coordinate of the first point.
- NUMBER end_x - The X coordinate of the second point.
- NUMBER end_y - The Y coordinate of the second point.
getDistanceNoSqrt(NUMBER start_x, NUMBER start_y, NUMBER end_x, NUMBER end_y)
This function partially calculates the pythagorean distance between two points.
This function doesn't have many uses. It doesn't return the true distance, because it doesn't square-root the calculated value.
The only use for this is to save the computer unnecessary square-root operation, when you don't need to know the definitive value. This is possible to utilize when comparing two distances, as you only need to know which one is longer and you don't care about the actual value.
- NUMBER start_x - The X coordinate of the first point.
- NUMBER start_y - The Y coordinate of the first point.
- NUMBER end_x - The X coordinate of the second point.
- NUMBER end_y - The Y coordinate of the second point.
getAngle(NUMBER start_x, NUMBER start_y, NUMBER point_x, NUMBER point_y)
This function calculates the angle (in degrees) at which a point is located relative to a starting point.
- NUMBER start_x - The X coordinate of the starting point.
- NUMBER start_y - The Y coordinate of the starting point.
- NUMBER point_x - The X coordinate of the relative point.
- NUMBER point_y - The Y coordinate of the relative point.
getPointFromAngle(NUMBER start_x, NUMBER start_y, NUMBER angle, NUMBER distance)
This function returns the coordinates of a new point in an object, that is located at a given distance from the starting point and under a certain angle.
- NUMBER start_x - The X coordinate of the starting point.
- NUMBER start_y - The Y coordinate of the starting point.
- NUMBER angle - The angle at which the new point is located (in degrees).
- NUMBER distance - The distance from the starting point at which the new point is located.
intersectLineLine(NUMBER line1_start_x, NUMBER line1_start_y, NUMBER line1_end_x, NUMBER line1_end_y, NUMBER line2_start_x, NUMBER line2_start_y, NUMBER line2_end_x, NUMBER line2_end_y)
This function finds the point of intersection of two lines and returns it in an object.
If lines don't intersect, returns false.
intersectLineCircle(NUMBER line_start_x, NUMBER line_start_y, NUMBER line_end_x, NUMBER line_end_y, NUMBER circle_center_x, NUMBER circle_center_y, NUMBER circle_radius)
This function finds the point of intersection of a line and a circle and returns it in an object.
If they don't intersect, returns false.
intersectLineRect(NUMBER line_start_x, NUMBER line_start_y, NUMBER line_end_x, NUMBER line_end_y, NUMBER rect_center_x, NUMBER rect_center_y, NUMBER rect_half_width, NUMBER rect_half_height)
This function finds the point of intersection of a line and a rectangle and returns it in an object.
If they don't intersect, returns false.
intersectCircleCircle(NUMBER circle1_x, NUMBER circle1_y, NUMBER circle1_radius, NUMBER circle2_x, NUMBER circle2_y, NUMBER circle2_radius)
This function checks if two circles intersect.
Returns true or false.
intersectRectRect(NUMBER rect1_center_x, NUMBER rect1_center_y, NUMBER rect1_half_width, NUMBER rect1_half_height, NUMBER rect2_center_x, NUMBER rect2_center_y, NUMBER rect2_half_width, NUMBER rect2_half_height)
This function checks if two rectangles intersect.
Returns true or false.
intersectRectRect(NUMBER rect_center_x, NUMBER rect_center_y, NUMBER rect_half_width, NUMBER rect_half_height, NUMBER circle_x, NUMBER circle_y, NUMBER circle_radius)
This function checks if rectangle and circle intersect.
Returns true or false.
pointInCircle(NUMBER x, NUMBER y, NUMBER circle_x, NUMBER circle_y, NUMBER circle_radius)
This function checks if a point is located inside circle.
Returns true or false.
pointInRect(NUMBER x, NUMBER y, NUMBER rect_center_x, NUMBER rect_center_y, NUMBER rect_half_width, NUMBER rect_half_height)
This function checks if a point is located inside a rectangle.
Returns true or false.
pointInRect(NUMBER x, NUMBER y, NUMBER rect_left_x, NUMBER rect_top_y, NUMBER rect_right_x, NUMBER rect_bottom_y)
This function checks if a point is located inside a rectangular area.
This function is the same as the G.pointInRect() function, but the input parameters are different.
Returns true or false.
Custom JavaScript Utilities
Overview
These utilities have mostly nothing to do with the game engine stuff.
They are a set of custom functions, that make certain things easier.
These functions are accesed by just their name, as they aren't located inside any container.
new Timestamp()
This is a custom Timestamp object constructor.
When an instance of this constructor is created, the UNIX timestamp (time in milliseconds) is saved in it (in Timestamp.time).
It is used for one function, which is described below.
TIMESTAMP.since()
This function returns the time in seconds that passed since the timestamp was created.
ARRAY.numSort()
Sorts an array with numbers in ascending order.
Interestingly, the default JavaScript ARRAY.sort() function doesn't sort it's content based on the numeric values, but it uses alphabetical order.
NUMBER.fixedTo(INTEGER decimal_positions)
Shortens a decimal (float) number, so it has at most the given amount of decimal positions.
The value is rounded, not truncated.
Interestingly, the default JavaScript NUMBER.toFixed() function returns a string, which is pretty annoying, so this function is beter in that regard.
Math.toRad(NUMBER degrees)
Converts a number representing degrees into radians.
This function is added to the default JavaScript Math function set.
Math.toDeg(NUMBER radians)
Converts a number representing radians into degrees.
This function is added to the default JavaScript Math function set.
Math.randomRange(INTEGER minimum, INTEGER maximum)
Returns a random integer number, that is bigger or equal to the minimum, and always smaller than the maximum.
This function is added to the default JavaScript Math function set.
Math.randomRangeFloat(NUMBER minimum, NUMBER maximum)
Returns a random float number, that is bigger or equal to the minimum, and smaller or equal to the maximum.
This function is added to the default JavaScript Math function set.
Math.randomBool()
Returns a randomly chosen true or false.
This function is added to the default JavaScript Math function set.
Math.average(NUMBER value1, ..., NUMBER valueN)
Returns the average number from all provided values. The amount of parameters is unlimited.
This function is added to the default JavaScript Math function set.
Math.weightedAverage([NUMBER value1, NUMBER weight1], ..., [NUMBER valueN, NUMBER weightN])
Returns the weighed average from all provided value-weight pairs. The amount of parameters is unlimited.
All values and their weights must be grouped in arrays.
This function is added to the default JavaScript Math function set.
rgb(NUMBER red, NUMBER green, NUMBER blue)
This function creates a string in the canvas color format from the given RGB values and returns it.
All values range from 0 to 255.
rgba(NUMBER red, NUMBER green, NUMBER blue, NUMBER alpha)
This function creates a string in the canvas color format from the given RGBA values and returns it.
The RGB values range from 0 to 255.
The alpha value ranges from 0 to 1, where 0 is completely transparent and 1 is completely visible.
Vectors
Overview
Vectors are custom objects, that are defined using the "new Vector()" constructor.
They are heavily used by the engine to unify and simplify many operations.
These vectors have many functions defined by their prototype. This means, that every vector "contains" these functions, therefore they are called on the vector itself.
They can also be defined in multiple ways.
new Vector(NUMBER start_x, NUMBER start_y, NUMBER end_x, NUMBER end_y)
OR
new Vector(NUMBER x_component, NUMBER y_component)
OR
new Vector(NUMBER angle)
The first definition creates a vector using two points.
The second definition creates a vector only by setting it's X and Y components.
The last definition creates a unit vector using only an angle (in degrees).
Every vector is stored as an object containing only it's X and Y values.
VECTOR.copy()
Creates a new vector, that is a copy of the given vector.
VECTOR.length()
Returns the length of the vector.
VECTOR.normalize()
Normalizes the given vector and returns it.
Normalizing a vector means setting it's length to be equal to 1, while preserving it's directiong (angle).
The resulting vector is what's called a unit vector.
VECTOR.reverse()
Reverses the given vector and returns it.
Reversing a vector is simply multiplying it's components by -1, which in practice makes it point in the exact oposite direction, while keeping it's length.
VECTOR.perpendicular(BOOL clockwise)
Rotates the given vector by 90 degrees and the result is returned as a new vector.
If clockwise is true, the vector will be rotated in the clockwise direction. If false, it will be rotated in the anti-clockwise direction.
This value is optional. The default is anti-clockwise.
VECTOR.add(VECTOR vector1, ..., VECTOR vectorN)
Adds all the specified vectors to the vector and the result is returned as a new vector.
The amount of vectors to be added together is unlimited.
VECTOR.subtract(VECTOR vector1, ..., VECTOR vectorN)
Subtracts all the specified vectors from the vector and the result is returned as a new vector.
The amount of vectors to be subtracted is unlimited.
VECTOR.multiply(NUMBER scalar)
OR
VECTOR.multiply(NUMBER x_multiplier, NUMBER y_multiplier)
If only one number is provided, both components of the vector will be multiplied by this number.
If two numbers are provided, each component of the vector is multiplied by the coresponding multiplier.
The result is then returned as a new vector.
TIP: To divide a vector instead, use the formula 1/N. For example, to divide a vector by 2, multiply it by 0.5.
VECTOR.average(VECTOR vector1, ..., VECTOR vectorN)
Calculates the average vector from the vector and all the other vectors, and returns it as a new vector.
The amount of vectors to be added together is unlimited.
VECTOR.dot(VECTOR vector)
Calculates the DOT product of the two vectors.
The returned value is a scalar (number), not a vector.
VECTOR.angle()
OR
VECTOR.angle(VECTOR vector)
If no other vector is provided, returns the angle of the vector.
If another vector is provided, returns the angle between the two vectors. This angle will always be the smaller angle (always smaller or equal to 180).
VECTOR.rotate(NUMBER angle)
Rotates the vector by the given angle and returns it as a new vector.
VECTOR.scalarProject(VECTOR vector)
Calculates the scalar projection of the vector onto the given vector.
The returned value is a scalar (number), not a vector.
VECTOR.vectorProject(VECTOR vector)
Calculates the vector projection of the vector onto the given vector.
The result is returned as a new vector.
VECTOR.vectorReject(VECTOR vector)
Calculates the vector rejection from the vector projection of the vector onto the given vector.
The result is returned as a new vector.