Search the Community

Showing results for tags 'javascript'.

More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


  • HTML5 Game Coding
    • News
    • Game Showcase
    • Facebook Instant Games
    • Web Gaming Platform
    • Coding and Game Design
  • Frameworks
    • Phaser 3
    • Phaser 2
    • Pixi.js
    • Babylon.js
    • Panda 2
    • melonJS
  • General
    • General Talk
  • Business
    • Collaborations (un-paid)
    • Jobs (Hiring and Freelance)
    • Services Offered

Find results in...

Find results that contain...

Date Created

  • Start


Last Updated

  • Start


Filter by number of...


  • Start



Website URL





Found 695 results

  1. Hi, I'm trying to create an explosion when I shoot an enemy jet. Not just an image when I shoot an enemy but an explosion to where it explodes and then fades like a GIF files. How could I implement that on my game? Right now I'm using a sprite sheet. Any help would be great thanks!
  2. One of the hardest things I've found in getting to grips with JavaScript is translating a classical, statically typed mindset into the dynamical, prototypal world. I'm currently trying to find a nice, regular pattern to use as my bread-and-butter structure for writing and instantiating objects; I believe that the ability to make private properties and methods is genuinely useful, and so am particularly enjoying the 'module' pattern using closures. I've read a little about the negative performance implications of closures vs prototypes, and have checked on jsperf: - where it appears that closures are generally slower to init, but quicker to read/write; the lesson I'm learning: prototypal architecture suits objects that are read/written very little but instantiated lots (particles?), and closures work for 'chunkier' implementations that benefit from a proper 'public' interface, with other properties hidden (game controller?). Do you guys have a preference or any wisdom either way? I'm trying to master JS before delving into TypeScript, which I know will make this a moot point!
  3. Hi, I'm a programmer, composer and hobbyist HTML5 game developer. I just released my second game a few days ago. You can play it for free here : Boba Jet is a free 2D javascript / html5 canvas shooter. Fight your way through various levels with your jetpack and your gun. Destroy all foes and travel through portals to rescue your brother. This game was mostly about learning basics of video game programming and building a reliable and comprehensive Javascript game engine. I'm looking for opinions on the game and joining an html5 game devs community.
  4. Hi. I'm trying to make my jet shoot red bullets, but for some reason they're coming out at green. Here's my code.... function Jet() { this.srcX = 0; this.srcY = 510; this.width = 100; this.height = 40; this.speed = 3; this.drawX = 220; this.drawY = 200; this.noseX = this.drawX + 100; this.noseY = this.drawY + 30; this.isUpKey = false; this.isRightKey = false; this.isDownKey = false; this.isLeftKey = false; this.isSpacebar = false; this.isShooting = false; this.bullets = []; this.currentBullet = 0; for (var i = 0; i < 25; i++) { this.bullets[this.bullets.length] = new Bullet(); }}Jet.prototype.draw = function() { clearCtxJet(); this.checkDirection(); this.noseX = this.drawX + 100; this.noseY = this.drawY + 30; this.checkShooting(); this.drawAllBullets(); ctxJet.drawImage(imgSprite, this.srcX, this.srcY, this.width, this.height, this.drawX, this.drawY, this.width, this.height);};Jet.prototype.checkDirection = function() { if (this.isUpKey) { this.drawY -= this.speed; } if (this.isRightKey) { this.drawX += this.speed; } if (this.isDownKey) { this.drawY += this.speed; } if (this.isLeftKey) { this.drawX -= this.speed; }};Jet.prototype.drawAllBullets = function() { for (var i = 0; i < this.bullets.length; i++) { if (this.bullets[i].drawX >= 0) this.bullets[i].draw(); if (this.bullets[i].explosion.hasHit) this.bullets[i].explosion.draw(); }};Jet.prototype.checkShooting = function() { if (this.isSpacebar && !this.isShooting) { this.isShooting = true; this.bullets[this.currentBullet].fire(this.noseX, this.noseY); this.currentBullet++; if (this.currentBullet >= this.bullets.length) this.currentBullet = 0; } else if (!this.isSpacebar) { this.isShooting = false; }};function clearCtxJet() { ctxJet.clearRect(0, 0, gameWidth, gameHeight);}// end of jet functions// bullet functionsfunction Bullet() { this.srcX = 100; this.srcY = 460; this.drawX = -20; this.drawY = 0; this.width = 5; this.height = 5; this.explosion = new Explosion();}Bullet.prototype.draw = function() { this.drawX += 3; ctxJet.drawImage(imgSprite, this.srcX, this.srcY, this.width, this.height, this.drawX, this.drawY, this.width, this.height); this.checkHitEnemy(); if (this.drawX > gameWidth) this.recycle();}; = function(startX, startY) { this.drawX = startX; this.drawY = startY;};Bullet.prototype.checkHitEnemy = function() { for (var i = 0; i < enemies.length; i++) { if (this.drawX >= enemies[i].drawX && this.drawX <= enemies[i].drawX + enemies[i].width && this.drawY >= enemies[i].drawY && this.drawY <= enemies[i].drawY + enemies[i].height) { this.explosion.drawX = enemies[i].drawX - (this.explosion.width / 2); this.explosion.drawY = enemies[i].drawY; this.explosion.hasHit = true; this.recycle(); enemies[i].recycleEnemy(); } }};Bullet.prototype.recycle = function() { this.drawX = -20;};// end of bullet functions// explosion functionsfunction Explosion() { this.srcX = 728; this.srcY = 520; this.drawX = 0; this.drawY = 0; this.width = 50; this.height = 50; this.hasHit = false; this.currentFrame = 0; this.totalFrames = 10;}Explosion.prototype.draw = function() { if (this.currentFrame <= this.totalFrames) { ctxJet.drawImage(imgSprite, this.srcX, this.srcY, this.width, this.height, this.drawX, this.drawY, this.width, this.height); this.currentFrame++; } else { this.hasHit = false; this.currentFrame = 0; }};// end of explosion functions// enemy functionsfunction Enemy() { this.srcX = 0; this.srcY = 559; this.width = 100; this.height = 40; this.speed = 2; this.drawX = Math.floor(Math.random() * 1000) + gameWidth; this.drawY = Math.floor(Math.random() * 360);}Enemy.prototype.draw = function() { this.drawX -= this.speed; ctxEnemy.drawImage(imgSprite, this.srcX, this.srcY, this.width, this.height, this.drawX, this.drawY, this.width, this.height); this.checkEscaped();};Enemy.prototype.checkEscaped = function() { if (this.drawX + this.width <= 0) { this.recycleEnemy(); }};Enemy.prototype.recycleEnemy = function() { this.drawX = Math.floor(Math.random() * 1000) + gameWidth; this.drawY = Math.floor(Math.random() * 360);};Any help would be gladly appreciated!!
  5. In my code, below, I have a bouncing circle animation. I would like to make an array called circles and push back new circles when needed. I want every circle in the array to be represented by the variable circle, but have separate x and y values. Any ideas as to how I could do this ? window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function */ callback, /* DOMElement */ element){ window.setTimeout(callback, 1000 / 60); }; })(); // example code from mr doob : canvas = document.getElementById("myCanvas"), c = canvas.getContext("2d"), time = 0, gravity = 0.1, dampening = 0.99, pullStrength = 0.01;var circle = { x: 50, y: 50, //(VX, VY) = Velocity Vector vx: 0, vy: 0, radius: 20};function update(){ requestAnimFrame(update); render();}function render (){ //c.clearRect(0, 0,canvas.width, canvas.height); c.fillStyle = 'rgba(255, 255, 255, 0.05)'; c.fillRect(0, 0, canvas.width, canvas.height); //Increment location by Velocity circle.x += circle.vx; circle.y += circle.vy; //Increment gravity over time -- Acceleration circle.vy+= gravity; //Slow it down circle.vy *= dampening; circle.vx *= dampening; //Bouncing //bottom if(circle.y + circle.radius > canvas.height){ circle.vy = -Math.abs(circle.vy); } //top if(circle.y - circle.radius < 0){ circle.vy = Math.abs(circle.vy); } //right if(circle.x + circle.radius > canvas.width){ circle.vx = -Math.abs(circle.vx); } //left if(circle.x - circle.radius < 0){ circle.vx = Math.abs(circle.vx); } c.fillStyle = 'black'; c.beginPath(); c.arc(circle.x,circle.y,circle.radius, 0 , 2* Math.PI); c.closePath(); c.fill();} canvas.addEventListener('mousedown', function(e){ var mouseX = (e.pageX||e.clientX||e.offsetX) - canvas.offsetLeft, mouseY = (e.pageY||e.clientY||e.offsetY) - canvas.offsetTop; var dx = mouseX - circle.x, dy = mouseY - circle.y; circle.vx += dx * pullStrength; circle.vy += dy * pullStrength;});update();
  6. This is the main question, I posted it on Stack Overflow so here's the link:
  7. this is my situation: I want to show twitter tweets like this: This is what I have now: The boxes are tweets from the user: @BachelorGDM. What I would like now is that there is always one selected and that you can navigate through them with the arrow keys on the keyboard. This is my javascript code: // THE TWEETS var data = loadTweets()// FUNCTION SHOW THE TWEETSfunction ShowTweets(){// VARS TABLE WITH TWEETS / PLACE IN COLUMN / PLACE IN ROWvar table = [];var column = 1;var row = 1;// LOOP THROUGH DATA AND CREATE TABLE WITH TWEET DETAILS + PLACE $.each(data, function(i) { // DETAILS TWEET var idstring = data[i].id_str; var screenname = data[i].user.screen_name; var imageurl = data[i].user.profile_image_url; // 9 TWEETS NEXT TO EACH OTHER if(column % 9 == 0) { row++ column = 1; } var array = [imageurl, idstring, screenname, column, row ] column++; table.push(array);});// VARIABLES THREE JSvar camera, scene, renderer;var controls;var objects = [];var targets = { table: [], sphere: [], helix: [], grid: [] };init(); // CALL INIT FUNCTIONanimate(); // CALL ANIMATE FUNCTIONfunction init() { // INITIALIZE CAMERA camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 5000 ); camera.position.z = 1800; // INITIALIZE SCENE scene = new THREE.Scene(); // LOOP THROUGH TABLE ARRAY (ARRAY WITH ARRAYS IN IT) for ( var i = 0; i < table.length; i ++ ) { var item = table[i]; // ITEM IS ARRAY WITH [imageurl, idstring, screenname, column, row] var element = document.createElement( 'div' ); element.className = 'element'; = item[1]; // ITEM IDSTRING = 'rgba(0,127,127,' + ( Math.random() * 0.5 + 0.25 ) + ')'; // BG COLOR + OPACITY FROM FRAME var number = document.createElement( 'div' ); number.className = 'number'; number.textContent = i + 1; // NUMBER IN THE RIGHT TOP element.appendChild( number ); var symbol = document.createElement( 'div' ); symbol.className = 'symbol'; var img = document.createElement('img'); img.src = item[0]; // IMAGE SOURCE IS LINK TO IMAGE symbol.appendChild(img); element.appendChild( symbol ); var details = document.createElement( 'div' ); details.className = 'details'; details.innerHTML = "" + '<br>' + item[2]; // SCREENNAME element.appendChild( details ); var object = new THREE.CSS3DObject( element ); // POSITION OBJECTS AGAINST EACH OTHER object.position.x = Math.random() * 4000 - 2000; object.position.y = Math.random() * 4000 - 2000; object.position.z = Math.random() * 4000 - 2000; // ADD OBJECTS TO SCENE scene.add(object); // ADD OBJECT TO OBJECTS ARRAY objects.push(object); } // TABLE VIEW for ( var i = 0; i < objects.length; i ++ ) { var item = table[i]; // ITEM IS ARRAY WITH [imageurl, idstring, screenname, column, row] var object = new THREE.Object3D(); object.position.x = ( item[3] * 160 ) - 1540; // X-POSITION (COLUMN) object.position.y = - ( item[4] * 200 ) + 1100; // Y-POSITION (ROW) // targets = { table: [], sphere: [], helix: [], grid: [] }; targets.table.push(object); // PUSH OBJECT IN TABLE ARRAY (IN TARGETS ARRAY) } // SPHERE VIEW var vector = new THREE.Vector3(); for ( var i = 0, l = objects.length; i < l; i ++ ) { var phi = Math.acos( -1 + ( 2 * i ) / l ); var theta = Math.sqrt( l * Math.PI ) * phi; var object = new THREE.Object3D(); object.position.x = 1000 * Math.cos( theta ) * Math.sin( phi ); object.position.y = 1000 * Math.sin( theta ) * Math.sin( phi ); object.position.z = 1000 * Math.cos( phi ); vector.copy( object.position ).multiplyScalar( 2 ); object.lookAt( vector ); // targets = { table: [], sphere: [], helix: [], grid: [] }; targets.sphere.push( object ); // PUSH OBJECT IN SPHERES ARRAY (IN TARGETS ARRAY) } // HELIX VIEW var vector = new THREE.Vector3(); for ( var i = 0, l = objects.length; i < l; i ++ ) { var phi = i * 0.175 + Math.PI; var object = new THREE.Object3D(); object.position.x = 1100 * Math.sin( phi ); object.position.y = - ( i * 8 ) + 450; object.position.z = 1100 * Math.cos( phi ); vector.copy( object.position ); vector.x *= 2; vector.z *= 2; object.lookAt( vector ); // targets = { table: [], sphere: [], helix: [], grid: [] }; targets.helix.push( object ); // PUSH OBJECT IN HELIX ARRAY (IN TARGETS ARRAY) } // GRID VIEW for ( var i = 0; i < objects.length; i ++ ) { var object = new THREE.Object3D(); object.position.x = ( ( i % 5 ) * 400 ) - 800; object.position.y = ( - ( Math.floor( i / 5 ) % 5 ) * 400 ) + 800; object.position.z = ( Math.floor( i / 25 ) ) * 1000 - 2000; // targets = { table: [], sphere: [], helix: [], grid: [] }; targets.grid.push( object ); // PUSH OBJECT IN GRID ARRAY (IN TARGETS ARRAY) } renderer = new THREE.CSS3DRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); = 'absolute'; // ADD RENDERER TO CONTAINER document.getElementById( 'container' ).appendChild( renderer.domElement ); // TRACKBALLCONTROLS => WHEN YOU HOLD DOWN MOUSECLICK controls = new THREE.TrackballControls( camera, renderer.domElement ); controls.rotateSpeed = 0.5; //controls.minDistance = 500; // MAX ZOOM IN => MIN DISTANCE controls.maxDistance = 2500; // MAX ZOOM OUT => MAX DISTANCE controls.zoomSpeed = 1; // STANDARD IS 1.2 controls.keys = [ 37 /*LEFT*/, 38 /*UP*/, 39 /*RIGHT*/, 40 /*DOWN*/ ]; controls.addEventListener( 'change', render ); // RENDER ON CHANGE var button = document.getElementById( 'table' ); button.addEventListener( 'click', function ( event ) { transform( targets.table, 2000 ); }, false ); var button = document.getElementById( 'sphere' ); button.addEventListener( 'click', function ( event ) { transform( targets.sphere, 2000 ); }, false ); var button = document.getElementById( 'helix' ); button.addEventListener( 'click', function ( event ) { transform( targets.helix, 2000 ); }, false ); var button = document.getElementById( 'grid' ); button.addEventListener( 'click', function ( event ) { transform( targets.grid, 2000 ); }, false ); transform( targets.table, 5000 ); // window.addEventListener( 'resize', onWindowResize, false ); // WHEN PRESSED ON KEY window.addEventListener( 'keydown', keydown, false ); function keydown( event ) { };}function transform( targets, duration ) { TWEEN.removeAll(); for ( var i = 0; i < objects.length; i ++ ) { var object = objects[ i ]; var target = targets[ i ]; new TWEEN.Tween( object.position ) .to( { x: target.position.x, y: target.position.y, z: target.position.z }, Math.random() * duration + duration ) .easing( TWEEN.Easing.Exponential.InOut ) .start(); new TWEEN.Tween( object.rotation ) .to( { x: target.rotation.x, y: target.rotation.y, z: target.rotation.z }, Math.random() * duration + duration ) .easing( TWEEN.Easing.Exponential.InOut ) .start(); } new TWEEN.Tween( this ) .to( {}, duration * 2 ) .onUpdate( render ) .start();}function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight );}function animate() { requestAnimationFrame( animate ); TWEEN.update(); controls.update();}// RENDER SCENE/CAMERAfunction render() { renderer.render( scene, camera );}}My tweets are initially in the variable data. I now have added this to my code: controls.keys = [ 37 /*LEFT*/, 38 /*UP*/, 39 /*RIGHT*/, 40 /*DOWN*/ ];window.addEventListener( 'keydown', keydown, false );function keydown( event ) {};But now how can I navigate through the tweets (boxes) with my arrows on the keyboard? I want to change the css of the selected box and open an overlay of the associated tweet. (You can see this when you click on a box on the link) I have no clue on how to start with this. Can somebody help me?
  8. Hi, I'm fairly new to game programming using HTML5. Although saying that I have been using Javascript for many years and will continue to do so for years to come. Basically I have made a couple of very basic games up to now just practising in general for when I decide to consider making a more serious attempt at a game for people to play. I noticed while learning some of the basics that there was quite a lot of code that I had to rewrite almost exactly the same for all the basic games I made, so I figured "Why not make a file that I can reuse for almost all games I intend to make?". Well I begun doing so and soon ran into a few "scope" problems, I figured out a way around them but then after reading a few threads on these forums when I first landed here yesterday, I am afraid that my style of OOP (So to speak) with Javascript is not the best way to go about things. I was just looking for pointers in regards to where this file can be improved due to not programming the way accepted by most Javascript developers? function Canvas(canvasID){ this.canvasID = canvasID; this.canvasDOM = document.getElementById(this.canvasID); this.ctx = this.canvasDOM.getContext('2d'); this.width = this.canvasDOM.width; this.height = this.canvasDOM.height; this.clear = function(){ this.ctx.clearRect(0, 0, this.width, this.height); }; this.fill = function(color){ this.ctx.fillStyle = color; this.ctx.fillRect(0, 0, this.width, this.height); };}var engine = new function(){ this.running = false; this.animator = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame; this.start = function(){ this.running = true; this.tick(); }; this.stop = function(){ this.running = false; }; this.tick = function(){ if(!this.running) return; update(); render();, function(){ engine.tick(); }); };} Now there are a few things I am sure are terribly wrong, the most prominent being in the tick method of the engine instance where I call itself by using "engine.tick()" . This is where, as I mentioned before, I had "scope" issues. Any advice regarding how I should change that would be much appreciated. Now the way in which I currently (And intend to continue if possible) using this file for my games is like so - var canvas = new Canvas("gameCanvas");engine.start();function update(){ canvas.clear(); //update game}function render(){ //render game} I hope you manage to decipher what I mean by this and understand my programming. Thanks in advance, Chuxx.
  9. Hey everyone, I have been searching and searching and still can't find a good solution to this... The best answer I have come across is to just add to the prototype of an existing object the functionality I need. Then if I wanted to override something just wrap another function call around the function I want to override and just call the function then do what I need to do after it. Are there any cleaner ways to go about doing this sort without having to copy large chunks of code over and over again? Maybe perhaps Phaser already has something built in to make this easier? Another example of what I am trying or want to do would be like how in Flixel you'd have those certain functions you'd always override in a object after you'd extend it and add functionality to everything that could be re-used over and over again. If using the prototype is the only way that's cool... Just wondering.
  10. Hey, I have developed an early 80's styled arcade shooter called Huoli Arcade. It's available for play here: Huoli Arcade - Brooklyn CodeBits (NEW LINK! USES MY WEBCADEJS GAME LIBRARY) It even has gamepad/joystick support for certain browsers. You can double click to toggle full screen. I hope you guys like it!
  11. Hi, i tried to figure out how the getImageData()-Function works. After several tutorials i wrote a script to enlarge the pictures pixels in a canvas. here's my code: var canvas = document.getElementById('canvas'); var cwidth = $("canvas").innerWidth();var cheight = $("canvas").innerHeight();if (canvas.getContext){ var ctx = canvas.getContext('2d');}var lvlImg = new Image();var lvlReady = false;lvlImg.onload = function(){ lvlReady = true; ctx.drawImage(lvlImg, lvl.x, lvl.y);}lvlImg.src = 'testbild.png';var lvl = { h: 16, w: 16, x: 0, y: 0};var pdata = new Array(); for(i=1;i<=lvl.h * lvl.w;i++){ pdata[i] = new Array(); pdata[i][0] = 0; pdata[i][1] = 0; pdata[i][2] = 0; pdata[i][3] = 0; }$(document).ready(function(){ var bd = ctx.getImageData(0, 0, 16, 16); for(i=0;i<lvl.h;i++){ for(l=0;l<lvl.w;l++){ var punktwert = (i*lvl.w) + l; var bdwert = punktwert * 4; pdata[punktwert][0] =[bdwert]; //R-Wert pdata[punktwert][1] =[bdwert + 1]; //G-Wert pdata[punktwert][2] =[bdwert + 2]; //B-Wert pdata[punktwert][3] =[bdwert + 3]; //A-Wert } } // For each pixel draw a rectangular shape filled with its color for(i=0;i<= lvl.h * lvl.w;i++){ var offsx = 20; var offsy = 20; var groessenfaktor = 3; ctx.beginPath(); var fss = "rgba(" + pdata[i][0] + "," + pdata[i][1] + "," + pdata[i][2] + "," + pdata[i][3] + ")"; ctx.fillStyle = fss; var actx = offsx + ((i%16) * groessenfaktor); var acty = offsy + (((i/16) - (i%16)) * groessenfaktor); ctx.moveTo(actx, acty); ctx.lineTo(actx + groessenfaktor, acty); ctx.lineTo(actx + groessenfaktor, acty + groessenfaktor); ctx.lineTo(actx, acty + groessenfaktor); ctx.lineTo(actx, acty); ctx.fill(); }});I tried to save the image-pixel-data in the variable "bd", but debugging with Firebug only returns: TypeError: can't convert undefined to objectpdata[punktwert][0] =[bdwert]; //R-Wert So is no array or it contains no data... Whats my fault in this case? Already now, thank you for your answers Greetings GamerXy1
  12. With traceGL you can see all JavaScript codeflow, in a high performance webGL visualiser. Its like an oscilloscope, for code. (this is freaking amazing!)
  13. WebCode is a vector drawing app for Mac that generates JavaScript+Canvas, CSS+HTML or SVG code.
  14. I have created a loader for tiled in the JSON format for my JavaScript game. The game is based on a 2048 x 1280 map and my canvas size is 704 x 608. So my predicament is how would i create a viewport/camera when the player approaches the edge of the canvas ,so that the map will move? In my situation, it is a little more difficult, because im not using a standard 2D array like most of the tutorials, so it is confusing me very much. The code for loading my map is like so: function Level (){var data;this.tileset = null;var returned;var t = this;this.load = function(name){$.ajax({type:"POST",url: "maps/" + name + ".json",dataType: 'JSON',async: false,success: function(success){returned = loadTileset(success);}});return returned;};function loadTileset(json){data = json;Level.tileset = $("<img />", { src: json.tilesets[0].image })[0]Level.tileset.onload = done = true;if(done){return data;}elsereturn 0;}this.draw_layer = function(layer){if (layer.type !== "tilelayer" || !layer.opacity) { return; }// if ( && {// return;// }var size = data.tilewidth;, i) {if (!tile_idx) { return; }var img_x, img_y, s_x, s_y,tile = data.tilesets[0];tile_idx--;img_x = (tile_idx % (tile.imagewidth / size)) * size;img_y = ~~(tile_idx / (tile.imagewidth / size)) * size;s_x = (i % layer.width) * size;s_y = ~~(i / layer.width) * size;ctx.drawImage(Level.tileset, img_x, img_y, size, size,s_x, s_y, size, size);});};this.collisionLayer = function(layer){var row = [];t.solids = [];, i) {var s_x,s_y,size = 32;s_x = (i % layer.width) * size;s_y = ~~(i / layer.width) * size;if (i % layer.width === 0 && i) {t.solids.push(row);row = [];}row.push([idx,s_x,s_y]);});t.solids.push(row);};return t.solids;} And this Level class is called from my main javascript file like this: layer = scene.load("level_"+level);layer = $.isArray(layer) ? layer : layer.layers;layer.forEach(function(layer){if( == "v.bottom" && layer.type == "tilelayer"){b_layer = layer;}else if(layer.type == "tilelayer" && !{t_layer.push(layer);}else if (layer.type == "objectgroup"){$.each(layer.objects, function(i, value){coll_layer.push([value.x,value.y,value.width,value.height,"dialogue"]);});}}); And then scene.draw_layer() is called from my update function lower in my main javascript function. My map holds different layers and you can see in the code above there is and if statement determining where the layer is the bottom layer, top layer or and object layer and storing it in the specific array. This is just so the player is shown between layers. So to clarify, for my game, how would i create a view port/camera according to my map loader? Also do i move the map or the player? And should i keep the player centered? if the player is centered then what happens when the edge of the map is visible? Here is a live version of the game so you can see how it works etc: Use guest as the username and password Thankyou very much
  15. I've ported the Ash Framework to Javascript and it can be found on github at: Ash is a high-performance entity system framework for game development originally written in Actionscript 3. It organizes code in an interesting way that is reminiscent of data-driven programming. Those of you with backgrounds in Flash and Actionscript may know the Ash Framework already but more information can be found at There are a couple of good introductory articles there as well as links to other ports and demos. Hope this is useful to some of you. Cheers, Brett
  16. Hello, fist than ever, i need to say that i don't speak english or write, what ever, but i'm learning so please try to understand me. Well i'm here because i need to do an a loading screen in my canvas before it get load, mmm i don't know how explain it. I'm doing a multiplayer game, and i have many functions to draw on canvas, but i need that when de browsers load,appears an image in the canvas saying "Please wait Loading Tilesets etc...", and when the browsers load that images, the image "Please wait loading..." disappears. So i need a method or function that tells me if all the images are loaded, and if area loaded, extract the image "Please wait loading", it's like AJAX, when you send an a petition you can use an a gif, and that gif says to the person "Loading" Thanks by your help.
  17. Hi, I am currently (or better: since the last weeks) making up my mind about how to build a asset loader that makes sense to me. The problem I have with most asset loaders is, that they act very much like assets are loaded from a harddrive, instead from the web. They further have the problem that they do not really care about the order and relation of the assets you are trying to load. The most basic ones just get passed a list of files to download and you can access that file contents through keys. While the basic behaviour of these loaders are fine to me, I think they are missing a great number of things: The game might not require ALL assets to get started. Its entirely fine to get a game started and not rendering all decorations and/or particles right from the beginning. Some of you might disagree, but I as a player would be totally okay that some eye-candy appears later during my game progress but I don't have to wait for minutes until I get to play the game. Assets might be required in different resolutions. Right now, we have a landscape of mobile and desktop systems which offer a wide range of display resolutions. The last generations of displays offer resolutions with over 300px per inch which requires games to load assets with nearly the double resolution to appear sharp while being rendered at the same size. This comes at the cost of performance, true - but I think in the future when mobile processing performance increases we don't have to think very much about that. Let our games look great! I think assets should be organized in groups (or "packages"). You have a asset group for your UI, one with basic game elements and maybe one asset group with special assets per game level. Organizing them in groups enables the developer to have a much better overview and being able to re-use assets more easily. I know its hard to detect if a user is currently on a mobile network over 3G, or in a WiFi environment from our JavaScript/Browser context, but bigger games have options/settings, so why shouldn't html5 games offer some graphical settings? Let the user decide if he wants to play with low-resolution assets because he's currently in a train with a slower connection, or let him load the full highRes beauty when he has a strong connection. The way my loader is (or will be) built, its very easy to switch asset resolutions without any impact on the game code itself. Below you can see my current specs I wrote down to see if my API idea makes any sense to me. I would love to discuss my idea with you and include your thoughts and opinions into the creation process. Have fun with reading my specs, just ask if you have any questions or anything is unclear Edit: If you don't like the boards code formatting, I uploaded the specs as a gist. //Cargo Asset Manager//===================//This file defines the API for a HTML5 asset loader that is mainly designed to be used for games//but could be used for any kind of HTML5 application that requires some kind of asset management.//@version: 1 (April 2nd, 2013)//@author: Christian Engel <>//The Cargo asset loader should deliver the following number of features:// * Loading all needed assets (huh, obvious)// * Differenciating between mandatory and optional assets// * Making it easy to switch to lowRes and highRes versions of assets, depending on the environment// * Providing a rich event list to enable the game to react to different situations// * Providing an easy interface for accessing loaded assets//The biggest difference to conventional asset loaders is, that Cargo don't just loads a number//of assets and calls a callback after that has been done. Cargo should enable the developer to//get the game loaded as quickly as possible by loading mandatory assets at first, maybe even with//low resolution, then loading optional assets, or higher resolutions after that.//A player doesn't care if the game does additional downloads in the background after it has been//started, but he DOES care about having a long waiting time at the beginning.//This means that developers need to approach developing their games a bit different. Asset loading//with Cargo will always be asyncronous and deferred and will even continue when the user is//accessing a game menu, or is already playing.//When a user is in the main menu and assets for the first level are not yet fully loaded, the game//needs to show a loading screen again, but the progress could already be very advanced since all//the time the user has spent in the main menu has been used to pre-load the next assets.//Another thing is on-the-fly updating of assets during a running game. Cargo can be configured//or advised to load low-res versions of the assets to get the game running really quick.//When the game is already running, optional assets or high-res assets are loaded and Cargo//notifies the game logic about asset updates and additions via the included event system.//-------------------------------------------------------------------------------------------//At first, require a reference to the cargo asset loader via AMD or commonJS.var cargo = require('cargo');//Set up the cargo object with the defaults you'd like to use.//Heads up! If you require the cargo element again at a later point in your//program flow, you don't need to re-configure it again.cargo.config({ basepathGlobal: 'lib/', //A basepath to be put in front of every relative URL. basepathImage: 'img/', //Basepath for all image files. Appended to global basepath. basepathSound: 'snd/', //Basepath for all sound files. Appended to global basepath. basepathText: 'txt/', //Basepath for all text files. Appended to global basepath. parseJSON: true, //Should the content of *.json files be parsed to objects? Default: true parallels: 5, //How many parallel downloads should cargo do? timeout: 2000 //After how much milliseconds with no response should an asset be considered as timed out? lowResPattern: '{filename}@low.{extension}', //The default schema for low-res versions of images. highResPattern: '{filename}@2x.{extension}', //The default schema for high-res versions of images. cacheBusterPattern: '{filename}.{version}.{extension}', //The pattern for the cache-busting mechanism for where to apply version numbers. imageTypes: ['png', 'jpg', 'gif'], //Extensions for assets to be recognized as an image. soundTypes: ['mp3', 'aac', 'ogg'], //Extensions for assets to be recognized as a sound. textTypes: ['txt', 'html', 'css', 'json', 'js'] //Extensions for assets to be recognized as plaintext.});//About the lowRes and highRes patterns//-------------------------------------//Since Cargo is able to load the same asset in multiple resolutions, the package definitions//have to hint Cargo that other resolutions are available.//The patterns are used to help the developer to not being required to specify the URL for every//version of the asset, but only saying "true" to a version. Cargo then uses the given pattern to//build the URL by itself.//About cache busting//-------------------//Dealing with the browsers cache to load//The idea behind cargo is, that cargo is able to load assets in packages.//For example, you define a package "ui", which you need to create your user interface from,//or you need another package "level1" which contains all assets you need for your first game level.//You can define one or more packages before you start loading them.//Define a single package by passing in its JSON structure, or directly pass an array of package objects,//or a URL to a JSON file containing the package definition(s).cargo.definePackage({ id: 'level1' //The identifier of this package to access it at a later point. mandatory: { 'ship1': { //A detailed asset definition. src: 'player-ship.png', //The URL to the asset. Since this is an image, it will be prefixed with basepathGlobal and basePathImage fsize: 128, //Optional definition of the filesize of the asset. Used to calculate more accurate progress. fsize_hi: 256, //Equivalent to fsize, but for the hiRes version. fsize_lo: 64, //Equivalent to fsize, but for the loRes version. hi: true, //By setting the "hi" property to true, Cargo uses the lowResPattern to guess the filename of the hiRes image. lo: 'player-ship.0.5.png' //The lowRes version is specifically defined here. version: 1 //Optionally specify a version number of the asset and increase it after changes to bust the browser cache. }, 'game_bkg': 'some_background.jpg', //A shorthand asset definition. No low/high res version given. 'bkg_music': 'soundtrack.ogg', //Will be recognized as sound and prefixed with basepathGlobal and basepathSound. 'enemy_defs': 'enemies.json' //If the option parseJSON is set to true, the JSON file will be parsed automatically. }, optional: { //Use this like the "mandatory" property. Optional assets won't be loaded until all mandatory assets are done loading. }});//After a package has been defined, its not instantly loaded.//You may specify a great number of packages before loading anything. The idea is, that you can load one or more packages together.cargo.load({ packages: ['ui', 'base_assets', 'level1'], //This tells cargo which packages have to be loaded to finish the load. optionals: false, //Pass false here, to completely ignore optional assets from loading. incremental: true, //Pass true to automatically increase the resolution. loadHighRes: false, //Setting this to "false" prevents incremental to load highRes assets. progress: progressHandler, finish: doStuff, optionalFinish: doMoreStuff error: errorHandler});//Setting the incremental option to "true" will cause Cargo to download the lowRes version of all mandatory//assets first, then continue with switching to standard, then continue with switching to highRes (if possible).//This will cause a overall bigger traffic impact, but will get the players into the game much quicker//and delivering better graphics after some time.//The cargo.load() method returns a loading object which enables you to react to different events.//In this example, three packages are being loaded. During the process, the progressHandler() function is//being called on every update and gets passed the current loading progress.function progressHandler(percent, calculatedSpeed, calculatedDuration){ $('.loadingLabel').text(percent);}//The calculatedSpeed and calculatedDuration arguments may not contain values at the beginning.//Both are calculated during the download process, when fsize hints are given in the package//definitions. The speed is given in kb/s, the calculated remaining duration is given in seconds.function errorHandler(fails){ $.post('errortracker.php', fails);}//The "fails" attribute is an object that contains the keys of all assets that have been failed//loading, as well as the HTTP statuscodes of the fail(s).//Now lets see how we can actually work with the assets.function doStuff(){ var pkg, ctx; //We're getting a reference to the package object here for faster interaction. pkg = cargo.getPackage('ui'); ctx = $('#canvas')[0].getContext('2d'); //Entering some kind of game loop. myEngine.onFrame(function(){ //This draws the asset "ship1" at the position x:1, y:1 in a canvas. ctx.drawImage(pkg.get('ship1'), 1, 1); });}//Calling the get() method of a package will return the asset with the given key.//Now its getting interesting:pkg.setResoluion('high'); //high, standard, low//This makes cargo download the high resolution version of every asset if neccessary.//After that, the get() method automatically returns the highRes version without further//configuration.//Listen to the changeResolution event to get notified to resolution changes that are//made manually or automatically:pkg.on('changeResolution', function(res){ //Maybe modify your game loop.});//The res attribute can be "low", "standard" or "high"//Handling optional assets//------------------------//Well, the finish handler is being called after all mandatory assets have been loaded.//But whats with the optional assets?//You may have already spotted the "optionalFinish" option for the load() method.//This callback is being called after all optional assets of a package have been loaded.//When the callback has been called, you can be sure that all optional assets are available for use.function doMoreStuff(){ //Prepare your game for using the optional assets}//Optionally, you can check the "optionalsAvailable" boolean property of your package object //to do a quick check inside your game loop:function myGameLoop(){ var pkg, ctx; pkg = cargo.getPackage('game_assets'); ctx = $('#canvas')[0].getContext('2d'); while(doLoop){ ctx.drawImage(pkg.get('player'), 10, 50); if(pkg.optionalsAvailable){ ctx.drawImage(pkg.get('player_decoration'), 10, 50); } }}Thanks for reading it! I am looking forward for your comments greetings, Chris
  18. Not strictly aimed at game dev, but some useful tips in here nonetheless...
  19. Hello, let me introduce you my new open-source library PolyK - . It is written in pure JavaScript, without any bindings to DOM, CSS or anything else. It is a set of several functions, which take an array of numbers and process it. It my be useful for some games, but you can use it even for non-graphical computation. I have several ideas for games, which may use that library. I don't have a time to make them, but maybe you will you click on some button in the middle of labyrinth (polygon) and you have to get mouse cursor out without touching the polygon. (PolyK.ContainsPoint) using PolyK.ClosestEdge you can test intersection with polygon and circle. You can make balls bouncing inside the polygon and then a character, which should go throught the polygon avoiding those balls. You can make car racing. Real physical models (Box2D, Bullet) are usually bad for car racing. With PolyK you can make pseudo-physical model. If you attach Z coordinate to road points and interpolate it, you can make 3D racing with jumping above the road, just like Need for speed With raycasting, you can test visibility between 2 points throught polygon. You can make your secret agent character run through the map while avoiding guards. Using Slice function, you can do something like Fruit ninja, but with multiple slicing and much interesting shapes.
  20. Hey Guys, I have made my first HTML5 game and wrapped it with CocoonJS to get native performance on iOS. Check it out! Thanks, StormPie.