Particles to Denote Movement in Space I'm currently working on a WebGL project to realise an idea I've had for some years. On my desk is book on making a space sim written 15 years ago. There I found some algorithm for particles in space. The idea is simple A cloud of particles that stay in place so they fly past the player, but reset to be in front of the player when they move past the ship. This shows the player they're moving while there's nothing else around. For this, I reworked the algorithm found in the book a little ParticleField.prototype.updateCloud function(frustum, position, direction) var s this.size, s2 s 2 for (var i 0 i lt this.vertices.length i ) if (!frustum.containsPoint(this.vertices i )) this.vertices i .set( (position.x s Math.floor(Math.random() s2)) (s direction.x), (position.y s Math.floor(Math.random() s2)) (s direction.y), (position.z s Math.floor(Math.random() s2)) ((s Math.floor(Math.random() s2)) direction.z) ) Where s is the size of cloud. I played around with the sizes, but this simple function has several weaknesses. The particles 'pop up' in front of the player when they're moving. If the player backs up and moves backwards, the particles won't reset, leaving the cloud visible popping the illusion. Particles appear to be flying through the player. Without regard of how the particles look (they're simple points right now), how can I make this look more natural? I've seen the effect in games like Elite Dangerous and Freelancer, and I'd like to be closer to them, and I'd appreciate any hint on the topic.


HTML Canvas drawing Firefox error I am getting the following error ONLY when running my game in Firefox (3.6) Component returned failure code 0x80040111 (NS ERROR NOT AVAILABLE) nsIDOMCanvasRenderingContext2D.drawImage The issue does not occur in the other major browsers, and my game runs completely fine after I click 'OK.' Here are a few snippets of code where I have localized the issue to. Has anybody seen this issue before? According to Google it has something to do with drawing the image before it is loaded, but from my understanding I am loading it properly before using it!. player class var player new (function() var that this that.image new Image() that.image.src "res enemy1 sprites.png" that.width 16 that.height 16 that.frames 2 that.actualFrame 0 that.spriteXoffset 0 that.spriteYoffset 0 that.moved false that.boundary false that.num balls 5 that.rootX 350 that.rootY 250 that.ballX that.rootX,0,0,0,0 that.ballY that.rootY,that.rootY,that.rootY,that.rootY,that.rootY that.directions "up" 0, "right" 1, "down" 2, "left" 3 that.dirs that.directions.right,that.directions.right,that.directions.right,that.directions.right,that.directions.right for (i 1 i lt that.num balls i ) that.ballX i that.rootX (i that.width) ... ... that.draw function() try for (var i that.num balls 1 i gt 0 i ) update animation switch (that.dirs i ) case that.directions.left that.moveLeft() break case that.directions.right that.moveRight() break case that.directions.up that.moveUp() break case that.directions.down that.moveDown() break ctx.drawImage(that.image, that.spriteXoffset, that.spriteYoffset, that.width, that.height, that.ballX i , that.ballY i , that.width, that.height) catch (e) alert(e.message) if (that.moved) if (that.spriteYoffset gt 0) that.spriteYoffset 0 else that.spriteYoffset 16 that.moved false )() game loop var GameLoop function() .. .. player.move() player.draw() .. .. if (state) gLoop setTimeout(GameLoop, GAME SPEED)


Array of map data renders the map the opposite way A while ago by following some tutorials I made a game map array consisting of 0, 1 and 2. I program it the way I want to see it var mapArray 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 2, 2, 0 , 0, 0, 1, 1, 1, 0, 0, 2, 0, 0 , 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 , 0, 0, 0, 1, 1, 1, 1, 1, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 , 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 2, 2, 0 , 0, 0, 1, 1, 1, 0, 0, 2, 0, 0 , 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 , 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 , 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 So for example the line 0, 0, 0, 1, 1, 1, 1, 1, 0, 0 lies on the X axis and I want to see grass 1 horizontally, but when I draw it on the canvas it's being rendered vertically instead. So the y and x axis are being swapped in place. Why is this so? Here is the rendering code function render(viewport) context.save() context.translate(view.x, view.y) requestAnimationFrame(render) var oldPosX boatPosX var oldPosY boatPosY for (let i 0 i lt mapArray.length i ) for (let j 0 j lt mapArray i .length j ) if (mapArray i j 0) this.sprite.draw( background, 190, 230, 26, 26, i this.sprite.width, j this.sprite.height, this.sprite.width, this.sprite.height ) if (mapArray i j 1) this.sprite.draw( background, 30, 30, 26, 26, i this.sprite.width, j this.sprite.height, this.sprite.width, this.sprite.height ) if (mapArray i j 2) this.sprite.draw( background, 200, 20, 26, 26, i this.sprite.width, j this.sprite.height, this.sprite.width, this.sprite.height ) this.ship.drawimage(boat, boatPosX, boatPosY, 50, 50) var lineHeight 16 2.286 var textWidth context.measureText(theArray moveCount .question).width 3 context.textAlign 'left' context.textBaseline 'top' context.font "14px Verdana" context.fillStyle 'rgba(0, 0, 0 ,0.9)' context.fillRect(boatPosX ship.width 2, boatPosY ship.height 2, textWidth, lineHeight) context.fillStyle 'white' context.fillText(theArray moveCount .question, boatPosX ship.width 2, boatPosY ship.height 2) answerBtn1.innerHTML theArray moveCount .answer1 answerBtn2.innerHTML theArray moveCount .answer2 if(isPositionWall(boatPosX, boatPosY)) boatPosX oldPosY console.log("collision") context.restore()


HTML5 Canvas Depth Sorting I'm have problem with Isometric. I'm don't know how to name this "problem", but I'm show you some sceen what I get and what I'm need to get. My code now drawing something like http 2.bp.blogspot.com rqhF 8E1nlA R59d PmoREI AAAAAAAAAGo 3yHpmy55moc s400 lore2.png But I'm need draw something like this http 3.bp.blogspot.com rqhF 8E1nlA R59epfmoRFI AAAAAAAAAGw cE o A0bvm0 s400 lore3.png I'm hear this is "Depth sort" But what it is? how I'm can apply to my code and where I'm can learn this? My code 'http jsdo.it keichioor exU1


2D Grid based Pathfinding with Elevation I'm creating an isometric game which currently uses A Pathfinding on a basic grid representation of the map. Having elevations and allowing the Players to traverse up and down is an integral part of the game however I'm stuck on exactly how to implement that, whether it be with A or something else. For example, 0 0 0 X 0 4 4 4 0 0 0 0 0 4 4 4 0 0 1 2 3 4 4 4 Assuming X is the Player, the numbers are tile elevations, and that the Player can only traverse tiles 1 elevation to the tile they're currently on, is there an accepted known way of doing this pathfinding?


How would I process accelerometer data to use it for camera rotation? I'm using Three.js to make a web based 3D first person game. I would like the player to be able to control the camera rotation with their device's accelerometer. The sensor data is received via the DeviceMotionEvent event listener. Here is an example of what it returns How should I proceed with this?


ECS Components inside components? Reading up on ECS, I've tried to implement a simple 'game', if you can call it that. Basic concepts You have planets(entity), they produce gold. (gold is a component inside planet) Planets can build buildings on themselves(Buildings component) A building(entity) has associated gold costs(Costs component) But costs component has Gold in it(or it needs to anyway) As to my question Am I close with my interpretation of ECS(Should components be inside other components?) Are resources a valid Component? if not, where would it make sense to place them? Edit for clarity ECS Entity Component System. My entities are empty hash tables of components. My components are used inside systems for game logic, the Treasury entity has a Gold component and the IncomeSystem updates that component. Other components (Buildable, Population, Moveable)


OOP implementation of BUFFS and Stats. Suggestion I am developing an MMORPG server using NodeJS. I am not sure how to implement Buffs, i mean, equipped objects or used skills have effects on the Player() which has many Stats(), some of them have a max cap... Effects can change the Stat value, increasing or decreasing it by a value, a percentage or completly rewrite the value of the stat. After a while I have decided to create a base class for buffs, which can be hidden (if they are casted from an equipped object) or shown if they came from an ability (Spell). Anyway I need suggestion how to implement it, use an array for all active buffs for a stat and have a function calculate the value of the stat affected by buffs each time I need the value of the stat or...? Other more OOP's ways to do it? I have read this What 39 s a way to implement a flexible buff debuff system? but this implements only a percentage system, which buffs can only say " 10 , 20 , etc...", but I would love to have an hybrid system, which can have percentage values or static values (like WoW does), and using modifiers it's hard to implement, because modifiers refers to the current value of stat Thanks for suggestions )


Centering camera on player div I've been making a roguelike style game in HTML5 without using canvas (only divs) with pure JS (fiddle!). I've been trying to enlarge the tile size (font size) while keeping the player centered within the camera. For some reason, when the tile size isn't equal to the map size, the camera will be slightly off. Note that the 3D effect is on purpose. Without it, the camera is still off center, and I believe it adds some much needed depth to the scene. D When tileScale (line 4 in the fiddle) is 9 (very undesirable the dots on the player's y axis should be aligned, not at a slight angle) When tileScale is 25 (on point!) Here's some relevant (trimmed) code window.onresize function() game.viewportWidth Math.max(document.documentElement.clientWidth, window.innerWidth 0) game.viewportHeight Math.max(document.documentElement.clientHeight, window.innerHeight 0) game.windowSize Math.min(game.viewportWidth, game.viewportHeight) Droid Sans Mono has a ratio of 3 4 (width height), conveniently. This may be problematic. I'm not sure. game.tileWidth game.windowSize .6 game.tileScale game.tileHeight game.windowSize .8 game.tileScale Update the camera position (needs help?) this.updateCamera function() Get player coordinates ( .5 because we need to get the player tile center) times the tileWidth plus the game window (inner square) size divided by two. var left (( game.player.x .5) game.tileWidth game.windowSize 2) "px" var top (( game.player.y .5) game.tileHeight game.windowSize 2) "px" game.planeContainer.style.left left game.planeContainer.style.top top How can I ensure that the dots in the center of the screen will be always lined up, instead of on a slight angle? My current evidence suggests that the position of the game.planeContainer object isn't being established correctly. I know this is a super tough problem, so any help will be greatly appreciated. Thanks in advance! (Another fiddle link, in case you skimmed over the first one. D)


DOM for GUI display animated objects I'm creating an HTML5 game using Canvas, but want to use DOM for the GUI for the reasons mentioned in there articles http blog.sklambert.com html5 game tutorial game ui canvas vs dom http www.html5gamedevs.com topic 29569 how do you guys build your ui http www.html5gamedevs.com topic 802 gui methodologies That being said, we have a component on the GUI that needs to be animated which will be through a sprite. Is it possible to render sprite animations through a DOM element?


Isometric game engine in JavaScript HTML5 Is anybody aware of any stable ish (ie out of alpha) isometric drawing engines for JavaScript HTML5? I have done some Google searches and found a few, but they were mostly in alpha invite only status. Is there anything mature enough to be used in a production environment? Or should I simply roll my own implementation for now and wait for the rest of the world to catch up?


Regeneration using Time.deltaTime I'm trying to regenerate stamina at a rate of 1 per second using Time.deltaTime, however this doesn't do anything (My 'current stamina' doesn't change at all). I've done some looking around and I have tried Time.fixedDeltaTime. Also tried Time.time, but that just regenerated all my stamina in under a second. Here is my code var max stamina int 100 var cur stamina int var staminaRegenRate int 1 function Update() regen if(cur stamina lt max stamina) cur stamina staminaRegenRate Time.deltaTime Debug.Log("Second has passed") What am I doing wrong?


Changing JavaScript Player Object based on keypress I'm currently working on a basic JavaScript top down shooter and I've run into a dilemma. I'm trying to implement a basic toggle weapon system however when I press the key it changes the weapon properly but when I press it again to toggle back it doesn't work. I don't think it's an issue with the rendering because the drawing function is able to detect the different weapons properly. I feel it's an issue with the actual toggle system code. Here's the code for the player class class Player constructor(set) this.cx set.x this.cy set.y this.r set.r this.color set.color this.angle 0 this.toAngle this.angle this.state 1 this.up false this.down false this.right false this.left false this.bind() bind() const self this c.addEventListener('mousemove', (e) gt self.update(e.clientX, e.clientY) ) window.addEventListener('keydown', (e) gt if(e.keyCode 81) if(self.state 1) self.state 0 if(self.state 0) self.state 1 ) toggle code window.addEventListener('keyup', (e) gt if(e.keyCode 81) if(self.state 1) self.state 0 if(self.state 0) self.state 1 ) update(ex, ey) this.toAngle Math.atan2(ey this.cy, ex this.cx) canv() if(this.angle ! this.toAngle) clear() ctx.save() ctx.translate(this.cx, this.cy) ctx.rotate(this.toAngle this.angle) ctx.translate( this.cx, this.cy) drawPlayer(this.cx, this.cy, this.r, 0, 180, this.color, this.state) this.angle this.toAngle drawing code (above this one in the complete file) function drawCircle(x, y, rad, startAngle, endAngle, color) ctx.fillStyle color ctx.beginPath() ctx.arc(x, y, rad, startAngle, endAngle) ctx.fill() function drawPlayer(x, y, playerR, playerStartAng, playerEndAng, color, state) left hand start if(state 0) ctx.fillStyle color ctx.beginPath() ctx.arc(x 15, y 15, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() end right hand start ctx.beginPath() ctx.arc(x 15, y 15, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() if(state 1) right hand start ctx.beginPath() ctx.arc(x 7, y 21, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() ctx.fillStyle color ctx.beginPath() ctx.arc(x 7, y 17, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() gun start ctx.fillStyle "black" ctx.beginPath() ctx.ellipse(x, y 20, 3, 25, 0, 0, 2 Math.PI) ctx.fill() gun border ctx.strokewidth 10 ctx.strokeStyle "black" ctx.stroke() end draw player drawCircle(x, y, playerR, playerStartAng, playerEndAng, color)


custom SetInterval function in javascript i am trying to make an custom set interval function for my game but everytime i tried, i end up with a infinite loop. I can't use the default javascript's set interval because it can not take the random number. any idea?


what function creates rotation effect in three.js? which part of the code is responsible for the rotation in this example? Is it the camera or the scene itself? http threejs.org examples canvas camera orthographic


Javascript How to create a moving bullet animation from canvas the bullet cant see to move at all function bullet() this.x playerx this.y playery this.init function() this.x 5 draw(this.x,this.y,10,10,"blue") console.log(this.x) in another function if(k.keyCode 17) bullets new bullet() bullets.init()


How can i fix "get transform can only be called from the main thread" error in my code? Here's my code var forward transform.TransformDirection(Vector3.forward) var input Input.GetAxis("Vertical") function Update() transform.position forward input Time.deltaTime transform.Rotate( 0 , Input.GetAxis("Horizontal") 45 Time.deltaTime , 0 ) I keep getting this error get transform can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.


cocos2d js displays only one type of tile from a tmx file I am using Tiled to produce a tmx which I use in my code using cocos2d js. The problem is that when I run it on the browser, a wrong tile gets displayed, the first one of the image (0,0) and repeats for the whole map. The relevant js code is this this.farm new cc.TMXTiledMap(res.farm tmx) this.addChild(this.farm) where res.farm tmx the path to the tmx file. What could be the source of the problem? And how do I fix it? It seems to me that it is specific to my code. I do not find any other reports of the same problem.


creating a simulation game, what type of knowledge is needed? I am a beginner in game development. As a part of learning and fun, want to create a game in java script and html5. I am planning a game that we were used to play in childhood, that is "new business" a monopoly game, in that we used to buy ,rent,sell places and bank we get some money to play and etc. are features. Its just simple ludo like game. So can anyone suggest me from where to start? what will be the designing? Is it possible to create it only in a html5 and java script.


How can i call a thing a lot of times (game dodger) Hey I am new to coding and i want to know how to get the same thing to hapen until i "say" stop. The game is that you need to dodge stuff that is falling, i was thinking that i could use a while loop and Push the object in the list like the following Var i 0 Var theObjects While ( i lt 100) theObjects.push() i But that would be 1. Spawn them at the same time and the it would be 2. This only works for x amount of time. How can i make the object spawn til i say stop and spawn at difrent times Sorry for my bad english.


Keyboard input conflict in wall jump I'm trying to make a Megaman style wall jump in my 2D platform game with JavaScript. The character can do A,B,C motions when it sticks the wall My problem is that when I trying to jump off the wall(motion C), it goes to motion A or B first, C was not happened. I think the keyboard input was conflict but I have no idea how to handle it. Here is my current code if(key 'right' amp amp key 'jump' ) it doesn't work jump off the wall else if(key 'right' ) leave the wall else if(key 'left' ) stick the wall else release all keys falling down Please, Any help would be appreciated.


Making an enemy shoot every few seconds so I am making a 2d canvas game in Javascript and I want the enemy mobs to shoot a bullet every let's say 3 seconds. I'm almost done with the code , i made everything i just don't know how to make the function repeat. this is the enemy object function Enemy(x, y) this.sprite enemySprite this.x x this.y y this.shooting function() while(enemyBullets lt bulletsPerTick) var enemybullet new enemyBullet(this.x , this.y) enemyBullets.push(enemybullet) i'm adding the bullet object to an array . for(var i 0 i lt enemyBullets.length i ) enemyBullets i .show() enemyBullets i .move() if there is an element in the array , draw and update the bullet. i left only the important elements of the object needed to answer my question this is the enemy bullet object function enemyBullet(x, y) this.x1 x this.y1 y this.r 5 this.show function () ctx.beginPath() ctx.arc(this.x1, this.y1, this.r, 0, Math.PI 2) ctx.fillStyle "black" ctx.fill() ctx.closePath() drawing the bullet this.move function () this.x1 this.x1 5 updating the bullet In my main file , i have a function draw() which is in requestAnimationFrame(draw) for (var j 0 j lt enemies.length j ) enemies j .show() here i spawn the enemy sprite enemies j .shooting() this is the function which adds the bullets to the array , draws them and updates them. Basically , when i press the start the program now , only one bullet flies and disappears and i want that process to continue over and over again every few seconds , let's say 3 seconds for example , i tried to add enemies j .shooting() in an interval and timeout but they are in draw, which is in requestAnimationFrame and it doesn't seem to work , if anyone have any clue how to help me I want every advice possible. Also if you need more information about the problem , let me know.


Initial force to achieve orbital velocity I'm attempting to get asteroid to orbit a black hole that is asserting gravity. Some parts currently work, like the black hole asserting gravity, attracting asteroids in and destroying them. And sometimes the asteroids, or smaller chunks end up in orbit around the black hole. But my desire is to have them orbiting at random distances at the start of the game. Gravity First please note, I am certain the math behind a lot of this is off, I'm hacking a concept at the moment and once enough pieces are in place I intent to come back through and apply proper scale and units to everything. Next, it's written in JS but concepts should be fairly universal. function attractBodyToBlackHole(body) var sx body.position 0 var sy body.position 1 var bx blackHoleBody.position 0 var by blackHoleBody.position 1 var angleToBody Math.atan2(sx bx, sy by) var distanceToBody Math.sqrt(Math.pow(sx bx, 2) Math.pow(sy by, 2)) var magGrav 0.8 (distanceToBody 14) if(magGrav lt 0) magGrav 0 body.force 1 magGrav Math.cos(angleToBody) body.force 0 magGrav Math.sin(angleToBody) This function is applied to each object on p2's step, attracting it closer to the black hole. Asteroids function addAsteroid() var bx blackHoleBody.position 0 var by blackHoleBody.position 1 var a Math.random() (Math.PI 2) var dist 3 (Math.random() 3) var x dist Math.cos(a) var y dist Math.sin(a) var vx ? var vy ? var asteroidBody new p2.Body( mass 10, position x,y , velocity vx, vy ) So my question is, how can I calculate velocity x y (or force x y ideally) to get these objects, based on their position, distance and the force of attraction from the black hole?


Why Won't Image Drawing Work In JavaScript In my game at the beginning the first thing that you'll see is a campfire with this code var campfire new Image() campfire.onload function () ctx.drawImage(campfire, campfireX, campfireY) campfire.src "Sprites Campfire.png" However, it doesn't work, I put an alert("All systems a ok") at the end and i get the alert so i don't understand why it's there. You can find the actual image file here and the full code here. Sorry if I didn't format this well or something, I'm not very good at this 3 This may seem similar to an older question of mine in which I stated how to add a sprite onto the canvas, though in this case, I'm asking why the image doesn't appear on the canvas at all, even though there's no errors.


How to work with edge Texture Im not sure if i use the right terms, but im not able to find something to start with. Im trying to develop a little HTML5 game. I have a ground with a texture and now I want to make a surrounding texture. The texture is an image wich should be bend around the ground. At the moment im using easelJS for display my images textures. So im looking for some sort of Tutorial Script Advice. Im not even sure if I can bend a image in javascript. So the worst case I can think of is split the image in 100 pieces and then put it back together and rotate each piece. for example like this


Can I have keyboard controls in an MMO and still do movement calcuation in the server? I'm trying to decide between keyboard and mouse movement controls for a web based multiplayer. It would be quite resource intensive to use the WASD keys and AJAX the server with controls every second. Can I implement WASD key movement and still have the server do all the movement calculations (to deter cheating)?


Using dom elements for game interaction slow performance I have a need for my html5 game (using melonjs) to allow users to click tile areas on the map. The idea is it will show a css styled hover area. The browser tested is chrome. I could do this natively in the game engine but the styling options available for canvas entities is limited. So I went with creating a dom element for each item in the canvas map. As the player moves, I update only the positions of the dom elements which are on the viewport. Probably 70 total elements are created and only 2 3 are on the screen updating at any given time. I'm pretty surprised how slow it's making my browser. So my questions are why would updating 2 3 elements as the player moves be so slow? is it better to remove elements when offscreen then readd when they are back on, even though they arent updating as they move off screen? should I just scrap the dom solution altogether and rely on the api the canvas and game engines provide for styling


Why cap game loop delta time? I was reading some game's source code on Github and saw this game loop implementation for the first time var lastTime 0 var maxTime 1 30 param DOMHighResTimeStamp curTime requestAnimationFrame provides this value automatically this.loop function(curTime) requestAnimationFrame(Game.loop) Same as division by 1000 var dt (curTime lastTime) 0.001 if(dt gt maxTime) dt maxTime for(var i 0, len boards.length i lt len i ) if(boards i ) boards i .step(dt) boards i .draw(Game.ctx) lastTime curTime The key thing The game updates and draws at every step, but the delta time is capped at the desired maximum delta. That way, if a frame takes too long, the next frame steps with a constant delta. What are the pros and cons of this approach? I imagine it's useful for preventing huge entity movements caused by a long timestep, but can it cause problems? Edit Use curTime as provided by window.requestAnimationFrame in order to simplify stuff and avoid comments that don't deal with my main question.


How to display a lot of small objects using WebGL? Introduction The game scene contains a lot of 10x10 pixel elements for 1980x1200 px. screen the number of elements on the scene can vary from 0 to 23760 (elements cannot intersect). The live example http fintank.ru game The entire game space comprised of tiles each tile is responsible for some area and keeps elements for that area (similar to google maps). Each tile exist as 2 entities S and G. S is a set of elements in the tile, G is rendered image of a tile. When the server put remove elements to the tile, we change S and then re render the G. To draw a frame (at 20 fps) I just put the G of each visible tile using the putImageData(). That is done without WebGL. The question What is the most CPU effective approach to implement such many elements management using WebGL? Should I render each tile to a texture or each element may be implemented as a separate textured rectangle? The main concern is that each tile may be updated 30 60 times a second (elements adding removal). How to avoid memory leaks (how to reuse buffers?) if we make many new textures every second? What is the most effective way to manipulate pixels during rendering a 100x100 tile? How to avoid re uploading the unchanged textures to graphic card?


how to detect if a line is crossing another shape in javascript? given the situation here http jsfiddle.net h902cLpy is it possible to detect that a line going from A to B does cross another shape while A to C doesn't?


Animating a background 'pulse' with easing equation I'm trying to find a suitable easing equation (or other method) to animate an object so that it 'pulses' (imagine a 'spike' on a music visualiser, or see the image I drew badly below) 'v' is the value I'm using to scale. 't1' and 't2' mark the end of a single pulse. The game I'm working on is a puzzler, but I'd like to have objects in the background pulse in time with user selected music. I'm sure it's just a case of knowing what to search for, but any advice would be appreciated on how best to achieve this.


Increasing speed of circle over time as linear with Box2d Assume that there is a circle and it can be moved by using keyboard arrows.Is required that increasing speed over time like increasing car speed. For example max speed is 25 and time to reach max speed shall be 5 sec. Over 5 sec the speed will reach to max speed. Does Box2d handle that situation?. I tried setting linear valocity but it seems to make the circle have constant speed instead of increased speed over time. Thank You! Note I'm using Box2DWeb Javascript port of Box2D.


p2.js body position is NaN when spawned inside of each other I'm working on a project for which I need a physics engine. At the moment I'm playing around with p2.js but I'm running into a problem When I try to create multiple bodies (circles and or boxes) which overlap the positions are set to NaN as soon as world.step() is called. The bodies have a mass of 5 and are dynamic. In very rare occasions it does actually work. How can I make sure it works every time? Do I have to wait for the bodies to be initialized? 4 circles before the simulation starts, once world.step is called the positions of these circles is NaN var world new p2.World( gravity 0, 9.82 ) function PhysicsBody(type, x, y, widthOrRadius, height) this.body new p2.Body( mass 5, position x, y , ) this.type type if (this.type 'rectangle') this.shape new p2.Box( width widthOrRadius, height height ) else if (this.type 'circle') this.shape new p2.Circle( radius widthOrRadius ) this.body.addShape(this.shape) world.addBody(this.body) var bod1 new PhysicsBody('circle', 0, 0, 32) var bod2 new PhysicsBody('circle', 10, 0, 32)


How to calculate whether a cuboids face edge is infront of or behind another for sorting I'm building an isometric game, I want to position and sort objects in a particular way. All my entities have 3d bounds which determines their cuboid, looking my example, a different edge is used to decide if a cuboid is in front of another, depending on whether the point b2 is left or right of a2. I have already calculated all the points a1,a2,b1,b2 which are x,y,z I think I basically need to virtually draw "aedge" and "bedge", and compare some intersection. If b2 is right of a2 the green cuboid (b) is consider in front of the red cuboid when bline is south east of aline. If b2 is left of a2 the green cuboid (b) is considered in front of the red cuboid when bline is south west of aline. Please forgive my ignorance here, I'm sure there's some terminology I should have used here. I'm struggling to put down in words what it is I need.


Selecting objects on a 2D map I have a object selection function by checking the mouse click and getting the relevant object. How ever there is a rare situation where if one object is partially behind the other then both objects are in the given area so im wondering how I can make the game know which one was selected, as currently my method does not know. This is my function that works it out function getobj(e) mx e.pageX curleft mouse click x my e.pageY curtop mouse click y function searchSprites(sprites, x, y) var matches , i 0, data null for (i 0 i lt spritea.length i) data spritea i .data if (x gt data 0 amp amp y gt data 1 amp amp x lt data 2 amp amp y lt data 3 ) var imageData ctx2.getImageData(x, y, 1, 1) if(imageData.data 3 ! 0) return spritea i .id i spritea.length res searchSprites(spritea, mx, my) bid res 0 if(bid '1') alert('You selected the skyscraper in front!') else if(bid '3') alert('You selected the skyscraper behind!') Image of the map It keeps telling me I clicked the skyscraper behind which is not necessarily what the user is trying to do. How can I improve the accuracy of this ?


HTML5 game Secure way of saving score I wrote a pretty basic game for colleagues to play the player shoots on an enemy which has 50 lives while other smaller enemies pop randomly on the screen. The goal is to kill the main enemy as fast as possible. One important point the game is written in javascript (using HTML5 canvas). At the end of the game, I send the score and username to my php function in Ajax, and that's where I have trouble I find it really hard to restrain my colleagues from cheating. Here are the different ways of cheating I've noted so far Changing the score sent during the ajax call At the beginning of the game, reducing the number of lives of the enemy At the beginning of the game, reducing the probability for enemies to appear Here are the solutions I implemented to counter that cheating Create an array that I fill each time I enter the game loop with "delta", the time between that frame and the previous. I send that list to my php save function and then check that the total time of the deltas is equal to the score sent. Create an array where I store the times when the Enemy loses 1 life. Then in the php save function I check that the list trully has 50 elements, and that the time between 2 elements is not less than a certain value Create an array where I store the time when an enemy appears. Then in the php save function I check the number of enemies is not less than a certain number. The 2 first points seem good enough for me it becomes too much trouble for anyone to try and cheat that. The last point is causing me much trouble. I cannot stop the user from changing apparition rate to 0, then in the ajax call just fill the array with 30 values, that seems pretty easy. This is my first try with this kind of issue, so I have several questions Am I on the good way? Are there any "patterns" I am missing for this kind of issue? What would be your approach? What would you do? How to make it even more difficult for the players to cheat?


why are my client and server physics not syncing up? node.js and html5 My server looks like this var timestep 1000 30 var delta 0 var lastFrameTimeMs 0 function panic() delta 0 var update function() currentTime Date.now() if (currentTime lt lastFrameTimeMs (timestep)) setTimeout(update) return delta currentTime lastFrameTimeMs lastFrameTimeMs currentTime let numUpdateSteps 0 previousTime currentTime while (delta gt timestep) player.update(timestep 1000) delta timestep if ( numUpdateSteps gt 240) panic() fix things break bail out setTimeout(update, 60) setTimeout(update, 60) and then my client looks like var timestep 1000 30 var delta 0 var lastFrameTimeMs 0 function panic() delta 0 discard the unsimulated time ... snap the player to the authoritative state function mainLoop(timestamp) Throttle the frame rate. if (timestamp lt lastFrameTimeMs (timestep)) requestAnimationFrame(mainLoop) return delta timestamp lastFrameTimeMs lastFrameTimeMs timestamp let numUpdateSteps 0 while (delta gt timestep) if(player ! undefined) player.update(timestep 1000) delta timestep if ( numUpdateSteps gt 240) panic() fix things break bail out requestAnimationFrame(mainLoop) requestAnimationFrame(mainLoop) I've been trying to get this work for days. I'm trying to have a fixed time step on both the client and server so they both simulate physics exactly the same down to the decimal point. But for some reason my client is moving much faster than my server. I used this article as a reference. https www.isaacsukin.com news 2015 01 detailed explanation javascript game loops and timing Where am I doing something wrong in one of my loops? They both use a .033333333333 timestep like I want them to, but they move at different speeds. What am I doing wrong?


HTML5 clicking objects in canvas I have a function in my JS that gets the user's mouse click on the canvas. Now lets say I have a random shape on my canvas (really its a PNG image which is rectangular) but i don't want to include any alpha space. My issue lies with lets say i click some where and it involves a pixel of one of the images. The first issue is how do you work out the pixel location is an object on the map (and not the grass tiles behind). Secondly if i clicked said image, if each image contains its own unique information how do you process the click to load the correct data. Note I don't use libraries I personally prefer the raw method. Relying on libraries doesn't teach me much I find.


Instantiate objects that share same variable I'm just wondering how to instantiate the same objects that all share the same variables, except their positions. I'm basically working on the scene of my HTML5 game, and I've build a streetlamp post that turns on and off. All the lamps will have the same variables, such as Image, Size, on off function. The only thing that will be different will be the position x and y. I've built my lamp within a variable function (I think they're called that var ), and within my actual game DrawFunction, I'm calling LampPost.draw() . Is it possible to do something like this? LampPost(0,0) LampPost(100, 0) LampPost(200, 0) etc ... and then possibly place each instantiate Lamp within an array? This is a snippet code for the lamp var LampPost lamp xsprite 0, lamp ysprite 0, light xsprite 0, lightysprite 0, x 440, y 320, Flicker effects lightFlicker 0, seconds Off 0, seconds On 0, randomLength Off 500, randomLength On 150, draw function(x, y) this.x x this.y y ctxPropsOver.setTransform(1, 0, 0, 1, Map.x gameWidth 2, Map.y gameHeight 2) ctxPropsOver.rotate(Math.PI 25) ctxPropsOver.clearRect(0, 0, 1000, 1000) ctxPropsOver.globalAlpha this.lightFlicker ctxPropsOver.drawImage(imgLights, 0, 36, 500, 463, 60 this.x, 190 this.y, 500, 463) ctxPropsOver.globalAlpha 1 ctxPropsOver.drawImage(imgLights, 0, 0, 210, 36, 0 this.x, 0 this.y, 210, 36) UPDATE Okay, So I've converted it into an instance of object, this is what I have so far LampPost function(lx, ly, la) x lx 500 y ly 335 centrex 12 centrey 17 rotate la 8 LampPost.prototype.draw function () ctxPropsOver.setTransform(1, 0, 0, 1, ( Map.x gameWidth 2), ( Map.y gameHeight 2) ) ctxPropsOver.clearRect(0, 0, 1000, 1000) ctxPropsOver.save() ctxPropsOver.translate(this.x, this.y) ctxPropsOver.rotate(this.rotate Math.PI 180) ctxPropsOver.translate( this.centrex, this.centrey) ctxPropsOver.globalAlpha this.lightFlicker ctxPropsOver.drawImage(imgLights, 0, 36, 500, 463, 60, 190, 500, 463) ctxPropsOver.globalAlpha 1 ctxPropsOver.drawImage(imgLights, 0, 0, 210, 36, 0, 0, 210, 36) ctxPropsOver.restore()


How to encode a save game game state as a string? I'm building an HTML game. For this game I want to implement a save feature that should work like in some already existing games The user can chose export, this will create a string, representing the game state (I guess). This string can be pasted into an import input and will load the save game. I thought about storing the state in a JSON, minifying it, stringifying and encoding it in Base64. But I don't think this is a good idea, users could easily cheat in this game by decoding the string, changing whatever they want, encoding it again and loading this string. I already tried generating save files in games with this feature and decoding them in Base64 which didn't work, so I assume they use a different encoding. How can I encode the JSON like this?


How do I maintain an online users list? In a multiplayer JavaScript game client, is it a good idea to poll the server periodically to refresh online user list, or keep track of joined left users? Is there a better option?


Detecting keys presses between keyboard layouts, operating systems and javascript I've recently encountered a few headaches when I tried to detect key presses for a custom game engine to supports Windows, MacOS, Linux, and WebGL. Naive approach At first I naively thought that using GLFW's keycodes instead of scancodes will be the best solution to cover as many operating systems as possible. I later found out that if the player has a different keyboard layout, the keys will be bound all over the place instead of having the WASD keys (regardless of what character they represent) sit together. Problem 1 So then I moved over to using scancodes. So this works great (other than having a different set of scancodes for each operating system) but it also introduces my first issue. Since scancodes are position based and defined as integers, how will I display to the player what character, for their unique keyboard layout, is currently bound in the game's "Keyboard Settings" dialog. I don't imagine detecting a keyboard layout is plausible (might even be impossible with Javascript since I don't have access to OS calls). Problem 2 My second issue is when the game is deployed with WebGL. In Javascript the keyCode value is just fed to the browser from the underlying operating system. What this means is I have to check the OS at runtime and remap all the keybinds based on the operating system. This is a nightmare because, if the user has customised keybinds (stored to his cloud profile) that was created on MacOS but then later opened up on Windows, then the code will have to do three remaps in order to, get the OS when keys where customised, then get the current OS, and then the conversion between the two prior to taking into consideration the customised remaps... Is there not a better way?! This would also mean I will have to send all the keycode constants for everything possible operating system to each user. Resulting in a lot of unnecessary boat in the Javascript file. Just assume? It seems like the big game engines out there have this issue solved and I am curious how they got around these issues. Do they just assume all players use QWERTY keyboards at the risk possibly frustrating a certain audience until they remap the keys ingame? And do they assume all browser based games are played on Windows, MacOS, and Linux to keep the javascript OS detection to a minimal? (effectively losing mobile players)


Difficulty aligning isometric tiles I'm trying to render isometric terrain in javascript. Currently, my tiles are being drawn with small gaps between them I want the tiles to line up with no pixel gaps in between My rendering function is like this var screenX (x 60 2) (y 60 2) var screenY (y 30 2) (x 30 2) console.log(screenX, screenY) context.drawImage(img, screenX, screenY, 60, 30) Btw, my image is 30x15. Can you help me with this problem? EDIT var screenX (x 56 2) (y 56 2) var screenY (y 28 2) (x 28 2) console.log(screenX, screenY) context.drawImage(img, screenX, screenY, 60, 30) It works, but I want to find a general solution


Using Racing Wheel force feedback with a JavaScript game I have a Thrustmaster T80 Racing Wheel that I am using while developing an online game with ThreeJS. I have already made it so I can drive the car with the wheel and the game knows when I crash the car. But looking online I couldn't find a way to make the wheel 'rumble' or shake when the car crashes. The wheel does support this on other (downloaded exe) games but it would be amazing if it was possible to achieve in a JS game, but I couldn't find any mention of doing this online.


How To Animate A JavaScript Function I've been making this game where one of the characters, The Bandit, runs away from you mistaking you for a zombie. However, I can't seem to be able to animate the bandit. Is there a way I could use this w3schools example and make it fit with this canvas function? The code for bandit is here or the second site function drawBanditFacingDown() His face ctx.fillStyle " FFDE7A" ctx.fillRect(banditX, banditY, 25, 25) His left eye (your left not his) ctx.fillStyle "black" ctx.fillRect(banditX 5, banditY 5, 5, 8) His right eye (again your right) ctx.fillRect(banditX 15, banditY 5, 5, 8) His bandit thing on his mouth? I don't know what it's called ctx.fillStyle "red" ctx.fillRect(banditX, banditY 15, 25, 10) His shirt ctx.fillStyle "black" ctx.fillRect(banditX 5, banditY 25, 16, 25) His arms His right arm (YOUR RIGHT!!!!) ctx.fillStyle " FFDE7A" ctx.fillRect(banditX 21, banditY 25, 8, 20) His left arm (On your left side) ctx.fillRect(banditX 3, banditY 25, 8, 20) His pants His right pant leg (ur right) ctx.fillStyle " 11226B" ctx.fillRect(banditX 12, banditY 49, 8, 20) his left pant leg ctx.fillRect(banditX 5, banditY 49, 8, 20) ctx.fillStyle "black" ctx.fillRect(banditX 11, banditY 53, 3, 15) his shoes 200 LINES!!!!!! ctx.fillStyle "black" ctx.fillRect(banditX 5, banditY 68, 15, 5)


Interpolation using cubic Bezier curves I am trying to create an interpolate function for an animation library to achieve a tweening effect between frames. I want this to work with Bezier curves. I have created a jsFiddle (here) of my progress so far. I am trying to create a linear tween using this bezier definition p0 new Vector(0,0), Start point p1 new Vector(0,0), Control point 1 p2 new Vector(1,1), Control point 2 p3 new Vector(1,1) End point I have implemented the interpolation function from this tutorial. var u 1 t var tt t t var uu u u var uuu uu u var ttt tt t var p p0.multiply(uuu) p p.add(p1.multiply(3 uu t)) p p.add(p2.multiply(3 u tt)) p p.add(p3.multiply(ttt)) The problem I am having is that when I run the function, the animation does not appear to be linear, but rather like 'ease in out'. Ideally I would like the linear animation to work the same as this CSS transition. Can anybody see why it is not animating in a linear fashion?


Custom lookAt function goes wild I have written a custom lookAt function based on a lot of posts from all over the net, and it works very nice... except when a rotation (which is stored in a quaternion) crosses some 'threshold'. However, it works flawless when the camera's position is on the same horizontal plane as the model I'm lookingAt On the below GIF, all I do is hold a key to lookAt the model together with a left arrow key to move the camera along the right vector My following understanding about how this function should look like (in a brief) 1 .Calculate a quaternion rotation needed to rotate an object from it's facing vector and a target vector. 1.a. Calculate an angle between those vectors by taking their dot product and a perpendicular axis by taking their cross product. 1.b Convert angle axis info to a quaternion using this formula. 2 .Multiply the main quaternion rotation by the quaternion received above. If I'm right, I believe that I may have a bug in my code, but I'm not sure. My code below lookAt function(vec) if (this.position.isEqual(vec)) return this.rotation.multiply(new Quaternion().twoVecToQuat(this.rotation.getForwardVector(), this.position.sub(vec))) MVMatrix.setRotation(this.rotation.quaternionToMatrix()) , And the twoVecToQuat function based on Ogre3D quaternion library twoVecToQuat function(v0, v1) v0.normalize() v1.normalize() var dot v0.dot(v1) If dot 1, vectors are the same if (dot gt 1) return this.makeIdentity() If vectors are opposite if (dot lt (1.0e 06 1)) var fallbackAxis new vec3().make(1, 0, 0) fallbackAxis.crossSelf(this) If collinear, pick another vector if (Math.areScalarsSimilar(fallbackAxis.length(), 0)) fallbackAxis.make(0, 1, 0) fallbackAxis.crossSelf(this) fallbackAxis.normalize() this.axisToQuaternion(Math.PI, fallbackAxis) else var sDot Math.sqrt((1 dot) 2) var invSDot 1 sDot var tempVec v0.cross(v1) this.x tempVec.x invSDot this.y tempVec.y invSDot this.z tempVec.z invSDot this.w sDot 0.5 this.normalize() return this , UPDATE Slin's solutions proved to be working (that one about calculating lookAt matrix), but I still don't know where is the bug in the quaternions library code. Working lookAt function below lookAt function(at) if (this.position.isEqual(at)) return var zAxis this.position.sub(at).normalize() var up upVec() World's up vector instead of camera's up vector will unroll the camera var xAxis up.cross(zAxis).normalize() var yAxis zAxis.cross(xAxis) MVMatrix.make( xAxis.x, xAxis.y, xAxis.z, yAxis.x, yAxis.y, yAxis.z, zAxis.x, zAxis.y, zAxis.z, this.position.x, this.position.y, this.position.z) this.rotation.matrixToQuaternion(MVMatrix) this.copyEulerAngles() ,


How to draw objects that have a smaller Y axis first? In my game there is a large 2D map of various objects. Example. As you see, upon creation objects of the same type (trees for example) are placed correctly, but objects of another type (enemies) are placed on top of the no matter the position. Now, how can I arrange that everything is drawn according to it's position? Another example (the dog should be drawn before the tree, and not on top of it)


Limit rotation to certain angles for transform.rotate I'm working on a small project to learn Blender and Unity, and one issue I recently came across is that while I can have the turret of my tank rotate on the z axis based on mouse movements, I can't for the life of me figure out how to lock it to certain angles. My current approach was to use Mathf.Clamp to limit the range of values that I could pass to the rotate function, but that doesn't seem to have done anything at all, even though when outputting the value Clamp produces, I can tell it doesn't go over my specification. The code I have enum RotationAxes MouseX, MouseY, MouseXandY var axes RotationAxes private var MouseX RotationAxes.MouseX var sensitivityX float 15F var minimumZ float 35 var maximumZ float 35 function Update () if (axes MouseX) yRotation Input.GetAxis("Mouse X") transform.eulerAngles Vector3(0, 0, yRotation) transform.Rotate(0, 0, Mathf.Clamp (Input.GetAxis("Mouse X") sensitivityX, 30, 30)) function Start ()


How to disable touch in Quintus? I'm trying to build card game using the Quintus game engine. I have objects called Card. I can touch and drag it in the screen but I want just to touch and drag it one time but I can't figure out how to disable the touch after I dragged the card and I try to Google it but no luck. My code Q.Sprite.extend("Card", init function(p) this. super(p, asset "Queen OF Hearts.png", x Q.el.width 2, y Q.el.height 120 ) this.on("drag") this.on("touchEnd") , drag function(touch) this.p.dragging true this.p.x touch.origX touch.dx this.p.y touch.origY touch.dy , touchEnd function(touch) this.p.dragging false put a line on the screen if the card pass it put the card in the new position if not put the card in the orginal(old) postion if(touch.origY touch.dy gt Q.el.height 200) define the line that the card should pass if the amount of draged gt the screen line in Q.el.height 200 put the card in the same old postion if is not pass the line this.p.x touch.origX this.p.y touch.origY else put the card if it pass the line in the new postion this.p.x Q.el.width 2 this.p.y Q.el.height 280 ) so in the else statement in the touchEnd I'm trying to do some thing like that this.p.touch false but is not working.


Is it sound to use javascript for cross platform game scripting instead of lua? I might need web clients for my game I have been looking around for clues on the subject but I'm not convinced to commit to javascript as my primary scripting language. Currently I have started with lua. But I fear it will be a limiting choice for my future projects which include web clients for my games. So basically I would like to know if you think it would be a viable solution for handheld devices and consoles. Also, I would be glad to hear about anyone who had much success with javascript in cross platform games failures with javascript scripting engines restrictions within console SDKs that would prevent this type of solution successes using lua in web games


How to color each letter text in Phaser.js? I have a text created with text object (game.add.text) and I would like to color each letter differently if that is possible. If not, how can I achieve this?


To canvas, or not to canvas, when building browser based games? Background I have extensive development background, but the last time I coded a game was many years ago. My Javascript skills are quite limited, and I intend to improve them by building a simple game Tetris, Pac man, or something of that complexity level. Question It seems to me that a fundamental choice I need to make is whether I should render on a lt canvas gt element or not. With a canvas, I have basic tools for rendering points, lines, and more complex things on top of that. Presumably there are, or will be, also various frameworks to help with this. Without a canvas, I could keep my objects in the DOM tree, like a regular webpage, only quite complex, with many overlapping elements. Is one approach better than the other? Are they mutually exclusive? How do I know which to pick?


Collision between free player and tilebased map so I'm working on some sort of platformer in javascript where the map is tilebased but the player can move freely. Now, i have a problem with collision detection response. It's kind of obvious what I'm trying to do, I don't want the player to walk into walls and fall into the ground so i need collision stuff. Basic info The player is the same size as the tiles The tiles are 8x8 The map is stored in an array like this 0, 0, 0, 1, 1, 1, 0, 0, 0 . So if the map was 3x3 there would be a horizontal line in the center. I feel that the system that I'm using is very inefficient and there are some problems with it sides The tiles are 8x8 wide so i divide the players position by 8 to get the current tile the players is occupying. The player.y mapWidth player.x thing gets the tile at that position in the map array I use Math.floor instead of round to get the tile to the left of the player if (map (Math.round(player.y 8) mapWidth) Math.floor(player.x 8) 1) sides.left true else sides.left false if (sides.left) Set the players x position to exactly outside the wall. player.x Math.floor((player.x 8) 1) 8 Now this works fine for walls but when you use it on the ground it works but it glitches on corners. For example if the player half way over an edge it falls through the tile and is pushed to the side. Is there a better way to do this and if not, how do i fix the ground collision?


How do I make an HTML5 canvas tiled map with tiles which have other than squared edges? I'm creating an HTML canvas map and I'm trying to have the edges of the tiles not appear square, as in the tiles merge in to each other. I've scoured the internet for hours but can't seem to find anything. How would I go about doing this? Dropbox link to project I've included the used images so when the project is downloaded and run on the browser, the map should look like the following picture. This is not how I want it to look but how it currently looks. I know it's probably not possible to get this exact effect using a tile based map, and it's not a perfect representation, but here's a general idea of what I want to accomplish. Notice how the corners are no longer squared but have a more rounded look and appear to be blending in with the next color tile. That's my goal. Thanks in advance.


Any idea to be able to make the character still continue the game until no heart left I am newbie I am making a 2d game in unity 3d my code for the character game over is this.. I can get the heart less one heart if game over but turn back to five again I just want to decrease heart whenever character die until it loss all the five heart and my code for the heart is this... function Start () coins PlayerPrefs.GetInt("Coin") moveSpeed 10 anim GetComponent(Animator) MainCode.Hearts 5 function Update () transform.rotation.z 0 if(Input.GetKey(KeyCode.UpArrow)) transform.position.y moveSpeed Time.deltaTime if(transform.position.y lt 5) Application.LoadLevel(Application.loadedLevel) MainCode.Hearts 1 if (MainCode.Hearts lt 0) GameOver() var image GUITexture var Image 01 Texture2D var Image 02 Texture2D var Image 03 Texture2D var Image 04 Texture2D var Image 05 Texture2D var Image 06 Texture2D function Update if(MainCode.Hearts 5) image.texture Image 01 if(MainCode.Hearts 4) image.texture Image 02 if(MainCode.Hearts 3) image.texture Image 03 if(MainCode.Hearts 2) image.texture Image 04 if(MainCode.Hearts 1) image.texture Image 05 however its not working properly any help would be really much appreciated thank you in advance


How to inform pathfinding of solid objects blocking path? I'm sure this has been asked before, but I couldn't find the thread. Let me know if you can locate the duplicate. So, I have a my level is an array of tiles, where a tile can either be solid or walkable. I then use A star to path find my enemies from one location of the floor to another. The issue is that I also have solid entities. As an example, I may spawn 3 breakable vases at a certain location. They can be larger or smaller than a single tile, and they are just objects in the world, not tiles themselves. Because they are not a part of the A star grid (can they? they're larger or smaller than a tile, and their position is not locked to the grid), the path finding is not aware of their existence, since it only operates on its grid. As a result, sometimes the chosen path for the enemy to follow flows through the solid vases, so the enemy just gets stuck at that location. Is there a solution that alleviates this problem? I want the enemies to path around the vases (until they're destroyed, of course), instead of just getting stuck trying to unsuccessfully move through them.


Implementing navigatable achievement menu in javascript I am in the process of learning javascript for game design, and wanted to make a separate achievement page that the user can navigate to that will allow them to check their achievements on various games. (at the moment I am not concerned with implementing localstorage cookies etc, I just want to work on the page for now) So the requirements of my base idea is as follows Able to drag around the viewport page to view all the achievement categories as they will likely not all be in view on smaller screens Able to click on a category to open a small box containing all achievements belonging to that game category Able to mouse over all achievements in the boxes to get text descriptions of what they are OPTIONAL have lines connecting each box on the "overworld" to show users where nearby boxes are if they are off screen At first, I thought I would need canvas to be able to do this. I learned a bit about it and got decently far until I realized that canvas has a lot of restrictions like not being able to do mouseover events unless manually implementing each one. Here is the current progress I was at in doing a test run of learning canvas, but it's not very far var canvas document.getElementById('canvas') var ctx canvas.getContext('2d') canvas.width window.innerWidth canvas.height window.innerHeight function resize() canvas.width window.innerWidth canvas.height window.innerHeight ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.translate(panning.offset.x, panning.offset.y) draw() window.addEventListener("resize", resize) var global scale 1, offset x 0, y 0, , var panning start x null, y null, , offset x 0, y 0, , var canvasCenterWidth (canvas.width 2) var canvasCenterHeight (canvas.height 2) function draw() ctx.beginPath() ctx.rect(canvasCenterWidth, canvasCenterHeight, 100, 100) ctx.fillStyle 'blue' ctx.fill() ctx.beginPath() ctx.arc(350, 250, 50, 0, 2 Math.PI, false) ctx.fillStyle 'red' ctx.fill() draw() canvas.addEventListener("mousedown", startPan) function pan() ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.translate(panning.offset.x, panning.offset.y) draw() function startPan(e) window.addEventListener("mousemove", trackMouse) window.addEventListener("mousemove", pan) window.addEventListener("mouseup", endPan) panning.start.x e.clientX panning.start.y e.clientY function endPan(e) window.removeEventListener("mousemove", trackMouse) window.removeEventListener("mousemove", pan) window.removeEventListener("mouseup", endPan) panning.start.x null panning.start.y null global.offset.x panning.offset.x global.offset.y panning.offset.y function trackMouse(e) var offsetX e.clientX panning.start.x var offsetY e.clientY panning.start.y panning.offset.x global.offset.x offsetX panning.offset.y global.offset.y offsetY body overflow hidden canvas top 0 left 0 position absolute lt canvas id "canvas" gt lt canvas gt So I guess my question is now what is the best way to implement this? Is it feasable to do it with canvas, or should I just scrap that and try to figure out something with div movement? Should I be concerned with performance issues and should that affect how I implement it?


Three.js camera turning leftside right In Three.js I am trying to implement an orbiting camera can be rotated around the x and the y axis. I am using these two functions function rotateX(rot) var x camera.position.x, y camera.position.y, z camera.position.z camera.position.x x Math.cos(rot) z Math.sin(rot) camera.position.z z Math.cos(rot) x Math.sin(rot) camera.lookAt(scene.position) function rotateY(rot) var x camera.position.x, y camera.position.y, z camera.position.z camera.position.z z Math.cos(rot) y Math.sin(rot) camera.position.y y Math.cos(rot) z Math.sin(rot) camera.lookAt(scene.position) Now the x rotation works fine but the y rotation does not. Once I go over the top of the model as in that the camera's z position becomes negative then suddenly the lookAt method rotates the camera by PI amount on the Z axis and suddenly the left side of the model is on the right and vice versa. Now I can fix this by checking for a negative Z and then just fixing the camera's rotation but this then causes a malfunction when using x ad y rotation at the same time, the x then suddenly gets this inverting behavior. How should I go about fixing this?


Changing balls direction in Pong I'm making a Pong game to get started with game developement but I've run into a problem that i can't figure out. When trying to change the balls direction it doesn't change. This is the relevant code function moveBall() this.speed 2.5 this.direction 2 if(this.direction 1) ball.X this.speed else if(this.direction 2) ball.X this.speed function collision() if(ball.X 500) moveBall.direction 2 if(ball.X 300) moveBall.direction 1 Why doesn't it work? I've tried many different ways, and none of them seem to work. The moveBall.direction changes though, since it alerts the new direction once it reaches the defined ball.X position. If someone could help me I would deeply appreciate it. I've included a JSFiddle link. http jsfiddle.net hustlerinc y4wp3


Colouring greyscale images sprites for HTML canvas What is the best method to colour in sprites at runtime using the canvas element and javascript? I know there are various blending modes using globalCompositeOperation, but I don't know how best to utilise this. I'll break my question down into the following Is there an optimum way to export greyscale images so they can be easily re coloured later? (At the moment, the images are created with colour in Photoshop or a similar package and then turned into a greyscale and exported from there before I even touch them) With these greyscale images in place, what method makes colouring them with any colour possible? (They must retain the shading etc) I've tagged this with HTML5 and Javascript, but any advise from other platforms would be helpful. Edit Here's an example greyscale output of the image on the left. I want to be able to restore it to the same colour, but also be able to blend it with other colours for different shades of skin.


Keyboard input conflict in wall jump I'm trying to make a Megaman style wall jump in my 2D platform game with JavaScript. The character can do A,B,C motions when it sticks the wall My problem is that when I trying to jump off the wall(motion C), it goes to motion A or B first, C was not happened. I think the keyboard input was conflict but I have no idea how to handle it. Here is my current code if(key 'right' amp amp key 'jump' ) it doesn't work jump off the wall else if(key 'right' ) leave the wall else if(key 'left' ) stick the wall else release all keys falling down Please, Any help would be appreciated.


Is reobfuscating javascript every time the page is loaded a valid option for a multiplayer game? I am looking for ways to prevent cheating on a multiplayer browser game. I saw this answer where it was mentioned that obfuscation is not an effective technique. My plan is not only to obfuscate the code differently every time the page is loaded but periodically change the protocol that the client uses to communicate with the server. This would mean that even if they were able to deobfuscate the client side code, they would need to update the protocol every time I changed it or they wouldn't be able to communicate with the game servers. I know that this will be difficult to implement, but I believe that I can do it. Would this work? I know that it's impossible to outright prevent cheating, but I believe that this would make it extremely difficult.


How do I play audio with Javascript? I want to add a short audio track to a game of concentration I'm coding. I want the sound to occur when the user has won the game. How do I go about doing this? I would really appreciate the help, thank you.


How to get projectile direction vector in a 2d grid? I am having trouble figuring out how to trace the path of my projectiles in an Asteroids clone. Currently the ship is locked to the center of the screen and can be rotated a full 360 degrees. I know the angle the ship is pointing at any given time, but I am not sure how to calculate the vector that the projectile should use for its trajectory. I know that I can find the correct vector by subtracting the end point from the start point.. but the issue is that I do not know the end point. Theoretically.. the end point is whenever the projectile touches the edge of the screen or some object. This is the current game code https jsfiddle.net m6sxrk8w just using a hardcoded movement vector of x 1, y 1 . Can anyone give some advice on how to dynamically determine the true vector given the current direction of the ship? There must be some simple math I am missing here...


In Phaser, how should I be managing state? I'm quite new to Phaser and JavaScript really confused about state management. Phaser has lots of documentation and info on the net, but everyone seems to be doing it a different way. An example var game new Phaser.Game(800,600, Phaser.AUTO, 'phaser demo', preload preload, create create, update update, render render ) function preload() ... function create() ... function update() ... function render() ... Another window.game new Phaser.Game(800, 600, Phaser.AUTO) all other states are in different files module.exports preload function() ... , create function() ... , update function() ... I would be grateful for a simple overview of properly handling states.


How to solve this card game turn requestes clashing issue So I am developing a poker card game using JS node.js socket.io. It is turn based game. There will be a host and 4 other players.The flow is the players need to make a yes no choice, then the host need to make a yes no choice upon players' move, then players will need to make another yes no choice, then the server will determine who wins. Put simply, 1 Host set up the hand 2 inform all players 3 A player make a move(ticking yes or no) 4 this move will show up on the host's screen 5 the host need to make his her move(ticking yes or no) 6 the host's move show up on players' screen, they make another yes no choice 7 the server determine who wins. The issue lies on step 5. There will be multiple moves waiting for the host to process. Now the current design is all moves are shown by the form of a custom confirm box. It has yes no button. It works perfect when there is only one host and one player. But when there is more than 2 players, there is a serious clashing problem. If player A makes a move, it shows on the host's screen, and before the host ticking anything, player B makes a move and then player B's move (confirm box) will replace player A 's confirm box. In this case the host will not be able to process player A's move and the game cannot finalise. How to get this clashing issue sorted? I hope I am not making this issue sound too complicated but I have been scratching my head.


Game loop with fixed timestep gives strange result So I've read the famous article at http www.koonsolo.com news dewitters gameloop comment page 2 comments which describes different methods of implementing a game loop. I've tried to implement the final method that is described in the article in Javascript (ignoring interpolation for the time being) var Timer pastTime 0, currentTime 0, started false, starts the timer start function() if(!this.started) this.started true this.pastTime new Date().getTime() , gets the time in MILLSECONDS getTime function() return new Date().getTime() this.pastTime , stops the timer but does not reset it (i.e. getTime() can still be called to get the time between start() and end()) end function() if(this.started) this.currentTime new Date().getTime() this.started false return this.currentTime this.pastTime , resets the timer reset function() this.pastTime 0 this.currentTime 0 this.started false var maxFrameSkip 5 var nextTick new Date().getTime() var TICKS PER SECOND 25 var tickTimeMillis 1000 TICKS PER SECOND var ticksPerSecondReal 0 var ticksCounter 0 var timer Object.create(Timer) var loops 0 function gameLoop() loops 0 timer.start() while(new Date().getTime() gt nextTick amp amp loops lt maxFrameSkip) update() ticksCounter nextTick tickTimeMillis loops draw() if(timer.getTime() gt 1000) ticksPerSecondReal ticksCounter ticksCounter 0 timer.reset() console.log(ticksPerSecondReal) window.requestAnimationFrame(gameLoop) gameLoop() So the problem that I'm having is that the console.log(ticksPerSecondReal) should always be giving me 25 because that's the constant ticks per second that I want and have set up. What I end up getting is an alternating number that is 25 and 26. So periodically ( 1 second) it will be 25 and then 26 and then 25 and so on. And sometimes (much less frequently) it will even give a result of 27. It keeps switching back and forth when it should be constant at 25. What is the issue here?


how to join the body of snake in 2D snake game i'm making a snake game in javaScript from scratch. The problem is that the snake looks disjoint(see image). How can I connect the body(rectangles) of the snake? here is the code of drawing snake paintSnake(margin) draws the body of the snake this.snake.forEach((egg) gt console.log(egg) const isSnakeHead egg.cellX this.headCellX amp amp egg.cellY this.headCellY if (!isSnakeHead) this.ctx.fillStyle " 9ef739" this.ctx.fillRect(egg.cellX this.cellSize margin, egg.cellY this.cellSize margin, this.cellSize 2 margin, this.cellSize 2 margin) ) snake head this.ctx.beginPath() this.ctx.lineWidth 4 this.ctx.strokeStyle "red" this.ctx.rect(this.headCellX this.cellSize margin, this.headCellY this.cellSize margin, this.cellSize 2 margin, this.cellSize 2 margin) this.ctx.stroke() let head X this.headCellX this.cellSize margin, Y this.headCellY this.cellSize margin, width this.cellSize, height this.cellSize const args head.X, head.Y, head.height, head.width draw the head of the snake if (this.direction "up") this.ctx.drawImage( snakeHeadUpImg, ...args) else if (this.direction "down") this.ctx.drawImage( snakeHeadDownImg, ...args) else if (this.direction "right") this.ctx.drawImage( snakeHeadRightImg, ...args) else if (this.direction "left") this.ctx.drawImage( snakeHeadLeftImg, ...args) to see the whole code go to https github.com hackasaur snake game blob master main.js i know that the rectangles(body parts) need to be extended in the direction of the next rectangle but how can i achieve this?


Resource loader for an HTML5 and Javascript game I have made a type to shoot game using HTML5, Javascript and Ruby on Rails. Here is the link for the game Tweetraitor I wanted to make a loader for resources (sounds, images) when the game starts. Currently when the game starts the background image takes time to load and it does not look good. This loader should load all the assets those are used later in the game. Code for the game is here Tweetraitor on GitHub In the current version, all the images are loaded using js in an erb file which controls the game logic. Is there a better way to do this?


How do I generate a 2d grid based map without screwing it up? I'm relatively new to the mechanics of game development catching up fast, but there are still some things that escape me. For example generating a fully accessible map on a 2d grid. See the example at http crawl.s z.org. Each floor map starts with dozens of winding labyrinthine passages and randomly drops in points of interest temples, boss lairs, bazaars, etc. I know there's a lot of factors that go into this generating passages that always have at least one exit (no isolated tunnels in the walls), making sure passages have at least a one cell width wall between them and adjacent parallel passages, and dropping points of interest in such a way that they connect to the dungeon. I've taken a shot at it, and it's very easy to ranomly place lines in a 2d matrix that represent passages but they're never guaranteed to connect, and it's not nearly as elegant as the maps at the above example. I suppose my question is, what do I need to know to reproduce the example at crawl.s z.org? I know this is a large question I'd be fine with someone handing me a link to a reference site and telling me to learn it there. I'm just new enough at this that I don't even know what terms to google maybe there are names for different generation processes? Available techologies are JS (jQuery) and PHP, so a solution tailored to one of those would be ideal. Thanks!


Cocos Code IDE unable to find python I am trying to create a new JavaScript project on Cocos Code IDE but every time it immediately give me the error message Unable to find python. Please, click the setting button to set the python path, then python 3.0 or later is not supported. I click the button and I set the path to C Python27 which is the folder of my python installation, and I try again but I get exactly the same error. The version of my python installation is 2.7.8. I am using Windows8.1. EDIT It occurred to me that there is also another error message the python's version must be greater than or equal to 2.7.5 and less than 3.0 But I cannot understand why it does not accept my version(2.7.8).


How can I make my movement continuous? I'm making a game with simple movement code. I don't want the movement to be too complex since it's going to be a small game once it's done. Right now the character moves 10 units at a time, then stops, then 10 units, then stops, and this looks jerky. I'd like the character to move continuously, without stopping in between. I tried lowering the playerSpeed to make it less jerky, but then the character moved too slowly and players got bored. Instead I want the character to move a little every frame, not a big jump with delays in between. Here's what I've tried so far playerSpeed 10 document.addEventListener('keydown', function(e) if(e.key 'w' amp amp playerY gt 5) playerY playerSpeed ctx.clearRect(0, 0, outerWidth, outerHeight) drawProtagonistFacingUp() if(e.key 'd' amp amp playerX lt outerWidth 50) playerX playerSpeed ctx.clearRect(0,0,outerWidth, outerHeight) drawProtagonistFacingRight() if(e.key 's' amp amp playerY lt outerHeight 100) playerY playerSpeed ctx.clearRect(0,0,outerWidth, outerHeight) drawProtagonistFacingDown() if(e.key 'a' amp amp playerX gt 5) playerX playerSpeed ctx.clearRect(0, 0,outerWidth, outerHeight) drawProtagonistFacingLeft() )


How do I make my character jump on a platform? This is the code I've written so far Html lt div id "stage" gt lt div id "splash" class "screen" gt lt h2 gt Land lt h2 gt lt button id "howtobutton" gt Instructions lt button gt lt button id "hsbutton" gt High Score lt button gt lt button id "optionsbutton" gt Options lt button gt lt button id "playbutton" gt Play Game lt button gt lt div gt lt div id "instructions" class "screen" gt lt h2 gt How to Play lt h2 gt lt button class "backtomenu" gt Back to Menu lt button gt lt div gt lt div id "highscores" class "screen" gt lt h2 gt High Scores lt h2 gt (Username), your high score is lt button class "backtomenu" gt Back to Menu lt button gt lt div gt lt div id "options" class "screen" gt lt h2 gt Options lt h2 gt lt button class "backtomenu" gt Back to Menu lt button gt lt div gt lt div id "game" class "screen" gt lt div id "ground" class "platform" gt lt div gt lt div id "score" gt Score lt div gt lt div id "player" gt lt div gt lt button id "btn quit" class "backtomenu" gt Back lt button gt lt div gt CSS div border 1px solid black h2 text align center button display block width 100px margin 10px auto stage width 400px height 400px overflow hidden position relative background image url(http www.hlgjyl888.com data wallpapers 151 WDF 1917288.gif) background size cover splash display block .screen position relative display none width 100 height 100 color white player width 30px height 30px border radius 50 position absolute background color blue bottom 50px top 269px left 100px score position relative top 0px right 5px width 100px btn quit position absolute margin 0 bottom 0px left 0px .platform position absolute background color white .onPlatform background color blue ground top 300px width 400px height 3px JavaScript var gravity 1 var maxheight var timer var jump 32 var velocity 0 var jumppressed false var username prompt("What is your name?") (document).ready(function() (' howtobutton').click(function() showScreen(' instructions') ) (' hsbutton').click(function() showScreen(' highscores') ) (' playbutton').click(function() showScreen(' game') ) (' optionsbutton').click(function() showScreen(' options') ) ('.backtomenu').click(function() showScreen(' splash') ) maxheight Math.round( (" stage").height() (" player").height()) timer setInterval(update, 1000 60) (document).keypress(function(e) console.log(e.which) if (e.which 32) console.log("it works") jump() ) ) function showScreen(screen) ('.screen').hide() (screen).show() function jump() if ( (" player").position().top gt maxheight) console.log("Jump is working") velocity 15 function update() if (velocity 0 amp amp (" player").position().top maxheight) else if (velocity gt 0 amp amp (" player").position().top gt maxheight) console.log(maxheight " through ground" (" player").position().top) (" player").css("top", maxheight "px") velocity 0 else velocity gravity var newPos (" player").position().top velocity "px" (" player").css("top", newPos) However I'm very new to game development, I've been stumped for a while now, I can't figure out a way to control my character movement. Can anyone tell me what's wrong with my code? My character should be jumping on the platform whenever the space key is pressed (that's it).


SailsJS Rotational direction coordinates calculation issue I'm creating a small game to learn how NodeJS amp Sails work (and by extension Waterline, Socket.io, Express, and all their components). I'm using websockets to make the server calculate the coordinates. Everything is handled server side. The client only receives serialized data in order to redraw the whole canvas. For debugging purposes, I decided not to redraw but simply "draw" (leaving the old canvas visible) to show you the result. See below for situation, issue and code. The issue I'm having trouble when calculating coordinates. What I need is a simple forward backwards system, and when pressing left or right keys, change the direction angle so the character can move in the canvas. Kinda like the good'ol Asteroids retro games. The issue is the following The drawn loops you see shouldn't exist. In fact, they should be circles. I drew this by simply pressing either up or down key, combined with one of left or right keys. I think there is an issue in the calculation system... This shouldn't be a performance issue because each tick occurs at the same interval, so even if it was a performance issue, it should only be related to delay when redrawing the canvas, not such an offset in coordinates calculation... Any idea ? Info about code api moves contains a javascript object like this left false, right false, up false, down false It is used to check whether the user is "pressing" associated arrow keys. It is updated each time there is a keyUp or keyDown event client side. user.pick contains the "physical object" to be rendered in the canvas, which contain x, y coordinates, and information about movement speed and rotation speed. Here's the code that handles the coordinates calculation. Change angle if "left" or "right" is pushed if (moves.left moves.right) let PI2 2 PI let angle user.pick.angle if (moves.left) angle user.pick.angleSpeed else if (moves.right) angle user.pick.angleSpeed Use this to avoid having huge integers to manage if (angle lt 0) angle 360 angle if (angle gt 360) angle angle 360 user.pick.angle parseInt(angle) Up and down allow us to move either forwards or backwards. if (moves.up moves.down) let moveRatio moves.up ? 1 1 let angleRadians user.pick.angle (PI 180) let x user.pick.x moveRatio user.pick.speed Math.sin(angleRadians) let y user.pick.y moveRatio user.pick.speed Math.cos(angleRadians) Avoids collisions with canvas walls if (x gt 0 amp amp x lt user.map.width) user.pick.x parseInt(x) if (y gt 0 amp amp y lt user.map.height) user.pick.y parseInt(y)


Javascript How and where to put game initialization data I'm new to JS game programming. In the past, when coding games (in Java), I tend to make separate files for configuration and game data (maps, character stats, etc). This is for separation of code and data. How can I effectively implement this on JS? EDIT This is for browsers only.


Anti cheat Javascript for browser HTML5 game I'm planning on venturing on making a single player action rpg in js html5, and I'd like to prevent cheating. I don't need 100 protection, since it's not going to be a multiplayer game, but I want some level of protection. So what strategies you suggest beyond minify and obfuscation? I wouldn't bother to make some server side simple checking, but I don't want to go the Diablo 3 path keeping all my game state changes on the server side. Since it's going to be a rpg of sorts I came up with the idea of making a stats inspector that checks abrupt changes in their values, but I'm not sure how it consistent and trusty it can be. What about variables and functions escopes? Working on smaller escopes whenever possible is safer, but it's worth the effort? Is there anyway for the javascript to self inspect it's text, like in a checksum? There are browser specific solutions? I wouldn't bother to restrain it for Chrome only in the early builds.


JavaScript character direction delay I am developing a top down game and I'm having trouble with a delay in switching from one character walk direction to another, particularly if the previous direction key is still being pressed by the user. Take the following user interaction User presses up arrow User presses right arrow (up arrow is still pressed) User releases up arrow (right arrow is still pressed). The problem I am experiencing is that there is a delay in the character switching from the "walk up" movement to the "walk right" movement. requestId 0, settimeoutID 0, counter 0, move function(keyCode) var this this Frame per seconds var fps 60 if (this.requestId 0) (function animationLoop() Control the timing of an animation with requestAnimationFrame this.settimeoutID setTimeout(function() this.render() this.requestId requestAnimationFrame(animationLoop, this.move) , 1000 fps) )() , changeAnim function() if (this.counter 10 0) if (this.currentFrame gt 1) this.currentFrame 0 else this.currentFrame , render function() Add some drawing this.counter if (keyCode config.PLAYER DOWN) this.action 'Front' this.newPos.y 1 else if (keyCode config.PLAYER UP) this.action 'Back' this.newPos.y 1 if (keyCode config.PLAYER RIGHT) this.action 'Right' this.newPos.x 1 else if (keyCode config.PLAYER LEFT) this.action 'Left' this.newPos.x 1 this.changeAnim() Draw player logic this.drawPlayer.reDraw(this.playerSprite 1 .Walk this.action this.currentFrame , this.newPos) , onKeyUp function() Cancel the animation request if (this.requestId) clearTimeout(this.settimeoutID) cancelAnimationFrame(this.requestId) Allow a new request to be called this.requestId 0 this.counter 0 this.currentFrame 0 this.drawPlayer.reDraw(this.playerSprite 1 .Walk this.action this.currentFrame , this.newPos) Note The function move gets called every time a new key is being pressed.


Implementing an efficient method of server side checking I'm making a web based action RPG game. I don't want players to cheat, but I also don't want the game to constantly pause to wait for the server to respond. I made it so the game is played on the client side (for responsiveness) and the server does routine checking to validate the game state. But the system is very cumbersome. The server has to calculate every single frame and compare the entire game state to the game state sent from the client. If anything in the game states are different form each other, the server kicks the player off. However, this means the game has to send 30 requests a second, and the server must calculate it all in time. If many people are playing the game, I don't think my one free Heroku dyno can handle that. How do I implement an efficient and elegant way of validating players' moves on the server side?


Collision between free player and tilebased map so I'm working on some sort of platformer in javascript where the map is tilebased but the player can move freely. Now, i have a problem with collision detection response. It's kind of obvious what I'm trying to do, I don't want the player to walk into walls and fall into the ground so i need collision stuff. Basic info The player is the same size as the tiles The tiles are 8x8 The map is stored in an array like this 0, 0, 0, 1, 1, 1, 0, 0, 0 . So if the map was 3x3 there would be a horizontal line in the center. I feel that the system that I'm using is very inefficient and there are some problems with it sides The tiles are 8x8 wide so i divide the players position by 8 to get the current tile the players is occupying. The player.y mapWidth player.x thing gets the tile at that position in the map array I use Math.floor instead of round to get the tile to the left of the player if (map (Math.round(player.y 8) mapWidth) Math.floor(player.x 8) 1) sides.left true else sides.left false if (sides.left) Set the players x position to exactly outside the wall. player.x Math.floor((player.x 8) 1) 8 Now this works fine for walls but when you use it on the ground it works but it glitches on corners. For example if the player half way over an edge it falls through the tile and is pushed to the side. Is there a better way to do this and if not, how do i fix the ground collision?


Using Racing Wheel force feedback with a JavaScript game I have a Thrustmaster T80 Racing Wheel that I am using while developing an online game with ThreeJS. I have already made it so I can drive the car with the wheel and the game knows when I crash the car. But looking online I couldn't find a way to make the wheel 'rumble' or shake when the car crashes. The wheel does support this on other (downloaded exe) games but it would be amazing if it was possible to achieve in a JS game, but I couldn't find any mention of doing this online.


Maintaining relative location of objects across different screen resolutions I'm developing a very simple interactive HTML5 game, in which I need to show a room having multiple objects like a cupboard, table, fan etc. How can I display all of the objects together, so that they remain at same place, on all screen resolutions?


How do I query a server with visible map tiles? In my game, I need to retrieve data of items in the visible tiles based on what tiles are visible in the viewport. I am planning to make a batch AJAX request with the visible tiles, containing image tags like Google Maps. The item information will be in JSON format. What is the best approach for this? I currently have a class that determines the visible columns rows and offsets relative to the visible area shown.


HTML5 check if font has loaded At present I load my font for my game in with font face For instance font face font family 'Orbitron' src url('res orbitron medium.ttf') and then reference it throughout my JS implementation as such ctx.font "12pt Orbitron" where ctx is my 2d context from the canvas. However, I notice a certain lag time while the font is downloaded to the user. Is there a way I can use a default font until it is loaded in? Edit I'll expand the question, because I hadn't taken the first comment into account. What would the proper method of handling this be in the case that a user has disabled custom fonts?


Shifting the camera and setting a new scene when using Box2D My jsFiddle START MOVE CAMERA var p new b2Vec2() p (ball.body.GetWorldCenter().x) physics.scale pos.push(p) var length pos.length var s (pos length 1 pos length 2 ) in pixels if ((halfwidth lt (dw p)) amp amp (p gt halfwidth)) ctx.translate( s, 0) I followed this tutorial, but the ball rendering is acting weird and slow. I can't figure out how this example did it. He used 3 variables (stage,x, y) that are undefined in the code he wrote. Also check out how the camera moves with the player in this ImpactJS demo. I'd like to have that. How can I do this?


How to decide whether a Buff should be a component or a Buff object in an ECS? I'm developing a top down 2D game in Javascript using an Entity Component System architecture and I'm struggling with the question of exactly how to implement temporary buffs permanent passives. For example, let's say we want to give some entities Regeneration, such that they regenerate 5 health per second. One option is to have a BuffsComponent that holds a list of all active buffs. You could create a RegenerationBuff object that inherits from some base Buff class, and then stick that in a list inside the BuffsComponent. Then a BuffsSystem would query all entities with a BuffsComponent every frame, and execute the active effect on each buff. Simple. However, could you not argue that these effects could just be regular old components? That is, why not create a Regeneration component and then have a system that queries for all entities with a Regeneration component, and then update their health in that system? Each approach seems to have its own pros and cons, and I'm not sure if I should have a mix of the two, or fully commit to one. I feel like fully committing to one approach would simplify the architecture and design of the program, so I'm leaning towards that, but I'm not sure which approach to pick. Even if I did have a mix, I'm not sure how to decide on what should be a component versus what should be a buff. The first approach seems more computationally efficient I suppose? Because one potential implementation of such could involve you just iterating through the list of active buffs and calling execute on each one. However, I feel that while it may be more efficient, it may also be less powerful, because with the second solution I can directly query entities with certain buffs, so I could potentially have more complex interactions between entities based on who is holding which buffs. For example, with a Flight buff I would likely desire the ability to directly query entities with such a buff, so the latter solution would be preferable. However, besides the latter solution being potentially slower, it also seems like it could get a bit out of hand. What if I ended up having over 100 different buffs? Adding and removing components to entities is O(1) with my ECS library, but still, it sounds like it could be a bit ridiculous to have hundreds of components for an entity, most of which are just random buffs passives. What should I do?


How to import three.module.js I'm looking at this three.js cubemap example, and it runs fine in my browser when loaded from that page. After much strain to find and download the files it does not run? What am I doing wrong, with this quot module quot stuff? I got it to work by changing lt script type quot module quot gt import as THREE from 'three.module.js' ... Into lt script src quot three.js quot gt lt script gt lt script gt ... Can anyone explain how to properly import three.module.js? Why is this change necessary when I run the project on my machine?


Accounting for drift between ticks What are some solid techniques to account for the gap between processing time and frame update ticks? In other words, the game render loop looks like this Some important points Tick timings are determined by the web api (roughly 16ms consistently) Workers could either be triggered at the start of each tick (first checking if the previous one finished) or run continuously in their own loop. I think running continuously is better if we can account for the gap, so as to not waste time being idle which could lead to skipped frames. Either way the size of the gap will vary between updates. It's not constant note this article is a good reference https gafferongames.com post fix your timestep ... I haven't really tried applying it yet and I'm not sure if it fits the web constraints exactly.


How can I fix sprite vibrating randomly which is moving towards the mouse while using camera.position set to the sprite as the center? So, when I use camera.position.x player.x camera.position.y player.y to set the center of camera to my sprite, the code doesn't work as intended to. It's slightly hard to explain so i made this video(https youtu.be afCamx wB 4) in which I show how it should work and the difference problem when using camera.position The code related to this is function setup() createCanvas(displayWidth,displayHeight) level new Level player createSprite(100,100,10,10) edge createEdgeSprites() player.speed 5 function draw() background(255) level.play() player.rotation Math.atan2(mouseY player.y, mouseX player.x) 180 PI drawSprites() player.collide(edge) this part is from level.play() var run mouseX player.x var rise mouseY player.y var length sqrt((rise rise) (run run)) var unitX run length var unitY rise length player.x unitX player.speed player.y unitY player.speed Also if you notice, when using camera.position, the vibration happens at specific distance of the sprite from the mouse, and the patter is that the distance is 0 right at the center of the canvas and keeps increasing as you move away from the center.


Initial force to achieve orbital velocity I'm attempting to get asteroid to orbit a black hole that is asserting gravity. Some parts currently work, like the black hole asserting gravity, attracting asteroids in and destroying them. And sometimes the asteroids, or smaller chunks end up in orbit around the black hole. But my desire is to have them orbiting at random distances at the start of the game. Gravity First please note, I am certain the math behind a lot of this is off, I'm hacking a concept at the moment and once enough pieces are in place I intent to come back through and apply proper scale and units to everything. Next, it's written in JS but concepts should be fairly universal. function attractBodyToBlackHole(body) var sx body.position 0 var sy body.position 1 var bx blackHoleBody.position 0 var by blackHoleBody.position 1 var angleToBody Math.atan2(sx bx, sy by) var distanceToBody Math.sqrt(Math.pow(sx bx, 2) Math.pow(sy by, 2)) var magGrav 0.8 (distanceToBody 14) if(magGrav lt 0) magGrav 0 body.force 1 magGrav Math.cos(angleToBody) body.force 0 magGrav Math.sin(angleToBody) This function is applied to each object on p2's step, attracting it closer to the black hole. Asteroids function addAsteroid() var bx blackHoleBody.position 0 var by blackHoleBody.position 1 var a Math.random() (Math.PI 2) var dist 3 (Math.random() 3) var x dist Math.cos(a) var y dist Math.sin(a) var vx ? var vy ? var asteroidBody new p2.Body( mass 10, position x,y , velocity vx, vy ) So my question is, how can I calculate velocity x y (or force x y ideally) to get these objects, based on their position, distance and the force of attraction from the black hole?


Creating an Isometric tile map with HTML5 I'm trying to create an isometric tile map using HTML5 Canvas. Everything I've found online points me towards using a pre built engine. I'd like to learn how to do this without using an engine. Is it possible to do this? If so, how? Would I need to look into WebGL?


JavaScript movement of player Okay so I am quite new, I've got the player to move using up, down, right, and left. But what I am trying to do is make the character move with a left click. var Player function(id) var self x 250, y 250, id id, number "" Math.floor(10 Math.random()), pressingRight false, pressingLeft false, pressingUp false, pressingDown false, maxSpd 10, self.updatePosition function() if(self.pressingRight) self.x self.maxSpd if(self.pressingLeft) self.x self.maxSpd if(self.pressingUp) self.y self.maxSpd if(self.pressingDown) self.y self.maxSpd return self That's what I have for the up, down, left, right movement. I've seen a few documents stating the click but just can't seem to implement it into the file.


General directions on developing a server side control system for JS Canvas Action RPG Well, yesterday I asked on anti cheat JS, and confirmed what I kind of already knew that it's just not possible. Now I wanna measure roughly how hard it is to implement a server side checking that is agnostic to client input, that does not mess with the game experience so much. I don't wanna waste to much resource on this matter, since it's going to be initially a single player game, that I may or would like to introduce some kind of ranking, trading system later on. I'd rather deliver better more cool game features instead. I don't wanna have to guarantee super fast server response to keep the game going lag free. I'd rather go with more loose discrete control of key variables and instances. Like store user's action on a fifo buffer on the client, and push that actions to the server gradually. I'd love to see a elegant, generic solution that I could plug into my client game logic root (not having to scatter treatments everywhere in my client js) and have few classes on Node.js server that could handle that without having to mirror describe all of my game entities a second time on the server.