How to stop an anmation and a loop in relation to a timer? Phaser javascript I am not ajavascript or phaser expert, I just got stuck with this problem. I'll try to explain it. In this game is a 21 second timer in all this which starts AFTER a beginning 3 second animatiton. var maxTime 21 in SECOND There is a wheel (station) that spins over and over (loops) and scales up and down var init station scale 0.5 var scale station 0.40 When the game resets the station (wheel) resets function resetGame() station.scale.setTo(init station scale) station(middle anchor point). station game.add.sprite(750,195,"station") station.anchor.setTo(.75,.75) station.scale.setTo(init station scale) station.animations.add("anim") Init animations station.animations.play("anim",15,true) play Animations "anim" with 30fps, loop true Not to confuse you, but there is a lot going on in this 21 seconds, such as hint (this is hooked up with the station (wheel) hint game.add.sprite(game.world.centerX 50,game.world.centerY 100,"hint") hint.anchor.setTo(0.5) hint.animations.add("anim") hint.animations.play("anim",15,true) hint.visible false Playing a 3 second animation that only plays once at the very beginning of the game (including if game resets) also starting .play ("anim",15, true) (above (station wheel) code and looping it) after that 3 second animation console.log("FINISH ANIMATION and ADD TIMER") TIMER is referring to the 21 second timer timerEvent game.time.events.add(Phaser.Timer.SECOND maxTime, moveToEndGame, this) (also the 21 second timer) function moveToEndGame() console.log("TIMER END") var twn game.add.tween(bg).to( alpha 0 ,tween speed,"Linear",true) twn.onComplete.addOnce(function() flagGameover true ,this) if(!flagGameover amp amp !star.visible amp amp idx bullet lt bullet array.length) initBullet() else if(flagGameover) console.log("GOTO GAMEOVER") window.location ".. EndGame.html" Everything works up until the end of the 21 second timer, but station wheel keeps spinning creating an 'infinite loop" So there is nothing to stop the 'loop in the station" after the 21 second timer finishes. Coder left out a line that would do that? Some line of code needs to be added to that last block of code (or somewhere else?)to stop the loop on the station timed with the end of the 21 second timer. I think???? Or some kind of javascript kill switch i.e. stop all javascript then go to endgame.html Anyone know the answer?


Collision detection not working in Phaser 3 I am new to phaser. So I started working on a game but I am stuck at implementing collision detection. I want to do it between a static group(dot) and a Sprite(obs). function create() dot this.physics.add.staticGroup(dotx, doty, 'dot') dot.create(dotx, doty, 'dot') obs this.physics.add.sprite(obsX, obsY, 'obs') this.physics.add.collider(obs, ball, alert, null, this)


How to get the address of a nearby square on a chess board? I'm making a chess game from scratch and I got stuck. So far I have all my figures placed, I have the positions set, I've already done the collision detection and everything. When I click the figure that is in position A1 for example, I want to make two green rectangles at positions A2 and A3, and they will be used to make the figure move. Is there a method for to add 1 to the string "A1" to form the string "A2" or something? Because thats all I really need right now. Also if there's a more clever way to make the positions please let me know. As an example, here is how I currently look up my display positions using the A1, A2 etc. location codes let positions A1 10, 710 ,B1 110, 710 ,C1 210, 710 ,D1 310, 710 ,E1 410, 710 ,F1 510, 710 ,G1 610, 710 ,H1 710, 710 , A2 10, 610 ,B2 110, 610 ,C2 210, 610 ,D2 310, 610 ,E2 410, 610 ,F2 510, 610 ,G2 610, 610 ,H2 710, 610 , A3 10, 510 ,B3 110, 510 ,C3 210, 510 ,D3 310, 510 ,E3 410, 510 ,F3 510, 510 ,G3 610, 510 ,H3 710, 510 , A4 10, 410 ,B4 110, 410 ,C4 210, 410 ,D4 310, 410 ,E4 410, 410 ,F4 510, 410 ,G4 610, 410 ,H4 710, 410 , A5 10, 310 ,B5 110, 310 ,C5 210, 310 ,D5 310, 310 ,E5 410, 310 ,F5 510, 310 ,G5 610, 310 ,H5 710, 310 , A6 10, 210 ,B6 110, 210 ,C6 210, 210 ,D6 310, 210 ,E6 410, 210 ,F6 510, 210 ,G6 610, 210 ,H6 710, 210 , A7 10, 110 ,B7 110, 110 ,C7 210, 110 ,D7 310, 110 ,E7 410, 110 ,F7 510, 110 ,G7 610, 110 ,H7 710, 110 , A8 10, 10 , B8 110, 10 , C8 210, 10 , D8 310, 10 , E8 410, 10 , F8 510, 10 , G8 610, 10 , H8 710, 10 , the 0 of the arrays is x and the 1 is y, and that's also how I placed the figures.


Is it a bad idea to store functions inside components in ECS? Say I have three entities Player, Spikes, and Zombie. All of them are just rectangles and they can collide with each other. All of them have the BoxCollision component. So, the BoxCollison system would look something like this function detectCollisions () for each entity with box collision check if they collide then do something The issue is, the sole purpose of the BoxCollision component is to detect collision, and that's it. Where should I put the game rules, such as quot if the Player collided with Spikes, diminish its health quot or quot if the Zombie collided with Spikes, instantly kill the Zombie quot ? I came up with the idea that each Entity should have its onCollision function. Programming languages such as Javascript and F have high order functions, so I can easily pass functions around. So when assembling my Player entity, I could do something like function onPlayerCollision (player) return function (entity) if (entity.tag 'Zombie') player.getComponent('Health').hp 1 else if (entity.tag 'Spikes') player.getComponent('Health').hp 5 const player new Entity() player.addComponent('Health', hp 100 ) player.addComponent('BoxCollision', onCollision onPlayerCollision(player) notice I store a reference to a function here, so now the BoxCollision component will execute this passing the entity the player has collided with function detectCollisions () for each entity with box collision check if they collide onCollision(entity) onPlayerCollision is a curried closure function that receives a player, and then returns a new function that wants another Entity. Are there any flaws with this? Is it okay for components to store references to functions? What are other ways of avoiding game rules in components? Events? Thanks!


What is better for the overall performance and feel of the game one setInterval performing all the work, or many of them doing individual tasks? This question is, I suppose, not limited to Javascript, but it is the language I use to create my game, so I'll use it as an example. For now, I have structured my HTML5 game like this var fps 60 var game new Game() setInterval(game.update, 1000 fps) And game.update looks like this this.update function() this.parseInput() this.logic() this.physics() this.draw() This seems a bit inefficient, maybe I don't need to do all of those things at once. An obvious alternative would be to have more intervals performing individual tasks, but is it worth it? var fps 60 var game new Game() setInterval(game.draw, 1000 fps) setInterval(game.physics, 1000 a) where "a" is some constant, performing the same function as "fps" ... With which approach should I go and why? Is there a better alternative? Also, in case the second approach is the best, how frequently should I perform the tasks?


Game AI move towards player while avoiding an obstacle I'm trying to move enemy towards player, while enemy also tries to avoid an obstacle if it's in its path. Here's a simple illustration of what I want to do What I've tried Making circular collision around the obstacle. It works but that makes the enemy impossible to hit. I think going with an A pathfinding algorithm might be a bit overkill especially since it's designed for multiple obstacles, where in my case there is only the mouse and wall collision concerned. Moving the enemy towards the player, while also moving away from the obstacle at a slower speed. This works better because you can actually hit the enemy, but also slows down enemy if obstacle if it's in its path. My questions Is there a better way to go about doing this? Anything you would've done differently with my code to either improve or optimize? Here's the code I have currently in my game logic and a fully working example on jsFiddle. Calculate vector between player and target var toPlayerX playerPosX enemyPosX var toPlayerY playerPosY enemyPosY Calculate vector between mouse and target var toMouseX mousePosX enemyPosX var toMouseY mousePosY enemyPosY Calculate distance between player and enemy, mouse and enemy var toPlayerLength Math.sqrt(toPlayerX toPlayerX toPlayerY toPlayerY) var toMouseLength Math.sqrt(toMouseX toMouseX toMouseY toMouseY) Normalize vector player toPlayerX toPlayerX toPlayerLength toPlayerY toPlayerY toPlayerLength Normalize vector mouse toMouseX toMouseX toMouseLength toMouseY toMouseY toMouseLength Move enemy torwards player enemyPosX toPlayerX speed enemyPosY toPlayerY speed Move enemy away from obstacle (a bit slower than towards player) enemyPosX toMouseX (speed 0.4) enemyPosY toMouseY (speed 0.4)


setting a time delay between two frame when animation a sprite sheet this is my jsfiddle http jsfiddle.net Z7a5h As you can see the animation of the sprite sheet when the player is not moving is too fast so i was trying to make it slow by declaring two variable lastRenderTime 0,RenderRate 50000 but my code is not working and it seem i have a misunderstanding of the algorithm i am using so can anyone lay me a hand to how can i fix it ? if (!this.IsWaiting) this.IsWaiting true this.Pos 1 (this.Pos 1) 3 else var now Date.now() if (now this.lastRenderTime lt this.RenderRate) this.IsWaiting false this.lastRenderTime now


Error with Cocos2d JS when using Skeletal animation from Cocos Studio Here is the JavaScript code var size cc.winSize ccs.ArmatureDataManager.getInstance().addArmatureFileInfo(res.skeleton) The error comes from the following line var armature ccs.Armature.create("Skeleton") armature.getAnimation().play("hit") armature.x size.width 2 armature.y size.height 2 this.addChild(armature) And at runtime I get this error Assert failed AnimationData not exist! I know that error is from the specified line, but I'm very confused as to how I can solve it. I have tried many different methods, but unfortunately those didn't work. In the resources, I load all the image files and JSON files which made by Cocos Studio, and the file path and name are correct. What could be causing this error?


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.


Are javascript MVC model implementations too slow for games? I wanted to implement a game in javascript with an MVC design pattern, with each entity's state stored in a model. So for example, In an update loop we iterate over all models and apply the velocity attribute to the position attribute of the model. A view associated with each entity model would then receive a position changed event, and update the representation of the entity. This would happen independently of the views render method being called in a requestAnimationFrame callback. What I found though, through a possibly naive implementation, is that setting attributes of a model is simply too slow. As much as I prefer the architecture of this code, the framerate was significantly lower. Should I give up on using MVC for frequently updated attributes like position? Below, I've included some code to test aspects of setting attributes of an object. The most minimal model like behaviour, in which an attribute is set only when the new value differs from the current, and a quot changed quot update event is triggered, is about 10x slower than just setting attributes directly. Output gt test(1000, 100, 10) object key 163 ms object key if changed 172 ms object key if changed amp emit backbone event 953 ms Backbone.Model 4043 ms eventsBackboneCount 100000 var test function(creations, iterations, keyCount) var eventsBackbone .extend( , Backbone.Events) var eventsBackboneCount 0 eventsBackbone.on('all', function() eventsBackboneCount eventsBackboneCount 1 ) var looper function(label, create, set) var start (new Date()).getTime() var data for(var i 0 i lt creations i ) data i create(i) for(var j 0 j lt iterations j ) for(var i 0 i lt creations i ) var key '' (j keyCount) set(data i , key, Math.random()) var end (new Date()).getTime() console.log('' label ' ' (end start) ' ms') return data looper( 'object key ', function(id) return , function(datum, key, value) datum key value ) looper( 'object key if changed', function(id) return , function(datum, key, value) if(datum key ! value) datum key value ) looper( 'object key if changed amp emit backbone event', function(id) return id id , function(datum, key, value) if(datum key ! value) datum key value eventsBackbone.trigger('changed ' datum.id, datum, key) ) looper( 'Backbone.Model', function(id) return new Backbone.Model( ) , function(datum, key, value) datum.set(key, value) ) console.log('eventsBackboneCount ' eventsBackboneCount)


Using copyrighted sprites Possible Duplicate How closely can a game resemble another game without legal problems I was thinking about making a pacman clone, I know there is a similar question here Using Copyrighted Images , but I know i can't use the original art from the game because it belongs to Namco, so if I design a character that has the shape of the slice circle it will look exactly like pacman, maybe if I use green instead of yellow? Also if the game plays like the original pacman, it is wrong? I just want to make the game as a personal project and and publish it in my site without getting in trouble


Calling function every n second javascript game I making a game and I want to call a function that runs every random second to spawn something every time. I've seen some posts that said to use the setInterval() function to keep track of the time but I don't know where to implement it because I'm using the requestAnimationFrame() to loop the game. I also tried to implement it in the update function of the classes but it doesn't seem to work. This is my main with the loop import Game from ' src game.js' let canvas document.getElementById('main') let ctx canvas.getContext('2d') const WIDTH SCREEN 800 const HEIGTH SCREEN 600 let game new Game(WIDTH SCREEN, HEIGTH SCREEN) game.start() function loop() ctx.clearRect(0, 0, WIDTH SCREEN, HEIGTH SCREEN) game.update(ctx) requestAnimationFrame(loop) window.addEventListener( quot keydown quot , (event) gt game.controller.keyListener(event)) window.addEventListener( quot keyup quot , (event) gt game.controller.keyListener(event)) requestAnimationFrame(loop)


Quaternions how to limit axis? Is there any possibility to limit quaternions to move only in x amp y axis (like in Eulers yaw and pitch, without rolling)? I's there any equation or something similar to do this? Some example Movement should behave like this http 360.art.pl experimental 1 But when I build my player on quaternions it have no limits and I don't know how to fix it http 360.art.pl experimental 2


Separate shaders from HTML file in WebGL I'm ramping up on WebGL and was wondering what is the best way to specify my vertex and fragment shaders. Looking at some tutorials, the shaders are embedded directly in the HTML. (And referenced via an ID.) For example lt script id "shader 1 fs" type "x shader x fragment" gt precision highp float void main(void) ... lt script gt lt script id "shader 1 vs" type "x shader x vertex" gt attribute vec3 aVertexPosition uniform mat4 uMVMatrix ... My question is, is it possible to have my shaders referenced in a separate file? (Ideally as plain text.) I presume this is straight forward in JavaScript. Is there essentially a way to do this var shaderText LoadRemoteFileOnSever(' shaders shader 1.txt')


How to play multiple sounds at once without reloading data? I am making an HTML5 game, which involves one audio being played multiple times at once. I searched this issue up and found this https stackoverflow.com questions 25654558 html5 js play same sound multiple times at the same time It seemed to help, except later a question came up If I do cloneNode(), will it copy the sound AND the currently loaded audio data, or will it have to reload the data? Is there a better way to play multiple sounds while making sure no data needs to be reloaded?


Saving data in the local computer with cocos2d js Making a game with cocos2d js, is there a reliable way to create saved data in my local computer? I see that there is cc.sys.localStorage but it is removed if the user clears the browser's cache or when they simply use another browser.


How can I ensure reasonably spaced out enemies I have a simple javascript game and I'm initializing their positions on the y axis using random numbers. How can I ensure that they are reasonably spaced apart? My simple algorithm is y (Math.random() 1000 600) However I frequently get enemies almost directly on top of each other. This is a huge problem for the game, since it's a word game and the enemies have text on their center, that if overlapped makes them impossible to kill since you can't see the words. Any advice would be appreciated! I'm pretty new to making games in general so this has all been a learning experience for me!


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.


Resizing the map in HTML5 canvas Say I have a big map for my HTML5 game. And it is drawn with an image repeatedly. I want my map to be able to resize and respond to player's behaviors. Now I can resize my map, I just multiply a scale to my maps coordinates (map.x and map.y) and the pattern image will become smaller. However I have two problems that I don't know how to resolve. Let's see what I have got so far. My Sprite class use paintX and paintY to represent the drawing position. And they are defined as followed get paintX() return map.scale this.x frame.x get paintY() return map.scale this.y frame.y where frame is the view that follows my player when my player moves. In my game my player stays at the middle of the screen and the screen will move with my player. So when the map resizes the player's position will also change but it will stay in the middle of the screen. In Frame class its x and y coordinates will change when the scale is updated. init(config) const self this this. x config.x this. y config.y map.on('scale changed', () gt self. x map.scale self. x self. y map.scale self. y ) get x() return this. x set x(val) this. x val get y() return this. y set y(val) this. y val The Problems 1 I have thousands of sprites on the map. After resizing the map some sprites still stay in the same location but they are supposed to render at a scaled location. ( I use very large scale change to test so the change is like 0.2 to 0.3 just to see the result more clearly) 2 If I use very small scale change number such as 0.01 I can still see the change but I can also see some hiccups refreshing the map, then it renders OK again, but overtime it becomes messy and presents problem 1. Without scaling none of these problems exists. I am scratching my head to find a solution for this resizing problem. Is there a standard and not so complicated solution for this map resizing problem?


Questions for QueryAABB I'm currently having trouble getting my head around QueryAABB, and hope to find some answers here. The LowerBound of an AABB the upper left corner (and vice versa). Why is that and what idea is behind that? When exactly does an object count as inside the AABB and is therefor found by a query?


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?


mat3x4 in webGL shaders I am porting the IQM bone animation format to Javascript and have run into a problem... The vertex shader is failing to compile and the only error message I get out is 'mat3x4' syntax error on the first occurance of mat3x4 in the file. Its the very data type name itself that is unsupported, it seems. This happens on all machines I have access to for testing, which have a variety of Intel and ATI cards and run Linux with Firefox. (Chrome is not available.) If I change all mat3x4 to, say, mat3 then my shader compiles fine. does webGL support mat3x4? (I can find nothing via Google) how can I work around this? How can I package the bones into mat4, for example, and keep the code working correctly?


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


Equalling the rotation of an image with its object. Box2dweb I have some hard time making the rotation of an image equal to the rotation object that the image belongs to. Simply put it, I don't know how to do it properly but i am not asking for a how to guide but for some tips hint and or infos that i am not aware of... I was able to align perfectly the image with the object, and so if the object moves in a linear fashion the image is at all times on top of the object and everything is smooth and perfect. But how is it possible to make the rotation of the image be the same as of the object it belongs to. No matter what i tried it is always somewhat off or the rotation of the image behaves weird when in the end the object stops rotating. I tried using using GetAngle(), GetAngularVelocity(), combinations of both, but never succeeded. function Draw and Rotate() for (b world.GetBodyList() b b b.GetNext()) var angle ((b.GetAngle() 180) (Math.PI)) SCALE var angle vel ((b.GetAngularVelocity() 180) (Math.PI)) SCALE var pos b.GetPosition() console.log((angle)) if (b.GetUserData() "bo img") ctx.save() save the ctx state prior changing it.This method pushes the current state onto the stack. ctx.translate(pos.x SCALE , pos.y SCALE ) ctx.rotate(angle) ctx.drawImage(box img, (box img.width 2), (box img.height 2)) ctx.restore() restoring ctx state.This method pops the TOP state on the stack, restoring the context to that state. this is the part that deals only with one body and its image. If someone needs some more clarification please ask....


How to Prevent Entities Snapping Through Platforms I am using crafty.js to make a platformer. I assigned the main player entity the default jumping controls and movement with .twoway() and used .checkHits() against the obstacles ("obs") the player will jump on. The problem is that when the player jumps, if the top of the player entity hits the bottom of the obstacle, the player entity "snaps" to the top. How do I make it so that this movement does not happen? The intended effect is that the player entity will only land on the obstacle if the player entity lands on the top. Here is the code window.onload function() Crafty.init(600, 400) Crafty.background(' 07A6FF') obstacle platform entities 'obs' means obstacle var obs Crafty.e('obs, 2D, DOM, Collision, Color') .attr( x 100, y 250, w 400, h 45 ) .color(' E88D0C') var obs2 Crafty.e('obs, 2D, DOM, Collision, Color') .attr( x 200, y 150, w 45, h 45 ) .color(' E88D0C') player entity var player Crafty.e('player, 2D, DOM, Color, Collision, Twoway, Gravity, Jumper') .attr( x 50, y 50, w 60, h 40 ) .color(' 0035AB') .twoway(200, 150) .checkHits('obs') .gravityConst(200) .gravity('obs') lt script src "https github.com craftyjs Crafty releases download 0.7.1 crafty.js" gt lt script gt


How can I scale zoom to a point in canvas in the game? I am using html5 canvas to build a MMO game. When I scale my background by default it scales to (0, 0) which is the top left corner of the background. If I have other sprites on the screen they all will look like they are shifting to the bottom right a little bit. Suppose my sprite(player) is at (x,y) of the map and it is placed center on the canvas.How can I make the background scale or zoom to (x,y) instead of (0,0)? Its world position is (x,y) but its screen position is always (canvas.width 2, canvas.height 2). I think in this way the sprites around my player wouldn't shift their position to unexpected places. But I don't know how to do this.


How can I repeat only a portion of an image in Javascript? So I'm trying to repeat a portion of my spritesheet as a background. So far, I have attempted this var canvas (" board") 0 , ctx canvas.getContext("2d"), sprite new Image() sprite.src "spritesheet.png" sprite.onload function() ctx.fillStyle ctx.createPattern(spriteBg, "repeat") ctx.fillRect(0, 25, 500, 500) As you can see, it repeat the whole image, not just a part of it, and I just can't figure out how to do that last part.


HTML5 Jump and Run Game Performance issues we're developing a HTML5 Javascript jump and run game and therefore we have developed our own gameframework. It consists of following most important structures Stage Scene Layer divs ObjectEntites Rectangle Sprite canvas In the gameloop things get moved by calculating an offset value e.g. if we place a coin and this coin moves through the screen, it gets a new offset in each gameloop call. The dirty area of the coin is cleared in the canvas and the coin is repainted. We pay attention that we just draw at int values (no floating point). Unfortunately we have some performance issues now and can't figure out why our macbook pro's are running hot while playing the game. Are the drawing operations so crucial? We have layered Canvas, so just moving stuff gets repainted and even not the whole canvas but just dirty areas get cleared. IStat shows following values while playing the game Memory module A1 and Heatsink B get up to 60 and the rpm Value of the Fans increases up to 3000 4000. In firefox we see these values And chrome shows us this, where we also see how cpu increases Do you have any idea how to check performance of our game, how to find bottlenecks or general tips? We have searched for canvas performance, used firebug profiler... We'd be grateful for any advice!


How can I clear explosions in my function? Hi I have a function to place bombs, and a for loop that places explosions on the tiles where possible. My problem is that I can't remove the explosions after a while. I've tried everything I can come up with so now I turn here as a last resort. The function looks like this function Bomb() var placebomb false if(placeBomb amp amp player.bombs ! 0) map player.Y player.X .object 2 var bombX player.X var bombY player.Y placeBomb false player.bombs setTimeout(explode, 3000) function explode() var explodeNorth true var explodeEast true var explodeSouth true var explodeWest true map bombY bombX .explosion 1 delete map bombY bombX .object for(i 0 i lt player.bombRadius i ) if(explodeNorth amp amp map bombY i bombX ) if(!map bombY i bombX .wall) if(!map bombY i bombX .object) map bombY i bombX .explosion 1 else var explodeNorth false delete map bombY i bombX .object map bombY i bombX .explosion 1 else var explodeNorth false if(explodeEast amp amp map bombY bombX i ) if(!map bombY bombX i .wall) if(!map bombY bombX i .object) map bombY bombX i .explosion 1 else var explodeEast false delete map bombY bombX i .object map bombY bombX i .explosion 1 else var explodeEast false if(explodeSouth amp amp map bombY i bombX ) if(!map bombY i bombX .wall) if(!map bombY i bombX .object) map bombY i bombX .explosion 1 else var explodeSouth false delete map bombY i bombX .object map bombY i bombX .explosion 1 else var explodeSouth false if(explodeWest amp amp map bombY bombX i ) if(!map bombY bombX i .wall) if(!map bombY bombX i .object) map bombY bombX i .explosion 1 else var explodeWest false delete map bombY bombX i .object map bombY bombX i .explosion 1 else var explodeWest false player.bombs If anyone can think of a good way to remove the explosion after a delay please help.


How do I implement side scrolling in a javascript platformer? I'm building a side scrolling platformer with Javascript and the canvas element for a school project. I have the character all sorted out. He runs left and right, and has a different sprite set for standing still. The game has gravity, and I can jump. Now what I can't get my head around is how to implement side scrolling. The game world will be tile based. Each tile will be 20x20 pixels. When the character gets to the edge of the screen, it should scroll with the character to explore the level further. Can anyone point me in the right direction to a resource that explains how to programmatically do this? Language specific to Javascript would be good, but anything would be a help.


Structure game database to store player info and items Recently I started developing my tiny html5 multiplayer game made in Node.js, Express.js, MongoDB(Mongoose), Socket.io and using Phaser.js. I am quite new to these frameworks and especially new to database structuring management. My struggle comes when I think about how can I structure the database to store things as player username, password and general preferences (basic user info) and then things as player equipment such as items and currency. I can figure out how to do the code part but what I do not know how to handle is the process I should follow. I thought of the structure like so Users Document " id" "randId", "username" "ArthurConan", "password" "aquamarine12345", "credits" 20, "equipment" "name" "Sword of the Forsaken", "equiped" true, "slot" "weapon", "id" "itemId", , "name" "Meteor Katana", "equiped" false, "id" "itemId" Items Document " id" "itemId", "name" "Sword of the Forsaken", "atk" 1400, "value" 500 , " id" "itemId", "name" "Meteor Katana", "atk" 200, "value" 50 As I am using MongoDB the structure would be more or less similar to that. With the code above then I would do the following Player Registers and his basic info(username, password, ...) is added to the database and he will also get one weapon to start with. Player adventures into my world and gathers credits and equipment. Those items are stored in his inventory. Player can equip use sell destroy upgrade some of those items. Upgraded items will have its stats upgraded based on preset stats. As a side note I would like you to know I am not the best at explaining myself, I hope you understand what I am trying to achieve. Also any suggestions are appreciated, have a good day )


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)


using delta timing is causing shake I am using delta timing to account for potential drop in frame rate. Only trouble being when I do this, I can notice an ever so slight wobble. I checked out the following JSFiddle coming from a tutorial on the subject and I can even see the wobble there, specifically on the 30fps example. http jsfiddle.net straker bLBjn my code is var delta now 0, last 0, difference 0, time 1000 60 var d function(val) return val delta.time delta.difference Then further down at the game loop delta.last Date.now() animate() function animate() delta.now Date.now() delta.difference delta.now delta.last delta.last delta.now update a sprite platform.x d(10) requestAnimationFrame( animate ) How can I keep the animation smooth?


Online board game engines I would like to create an online implementation of a board game. What engines could I use to write the game and make it easily accessible to as many people as possible? I would like it to be as widely accessible as possible, so it would be best if the user interface would run in a browser, not in a separately downloaded app. Likewise, it should be cross platform, not limited to a single platform pure JavaScript HTML would be best, as that would allow it to be usable on the iPad as well, though Flash or Java may be acceptable. Silverlight doesn't have the market penetration (I don't have it installed, for instance) and XNA is far too limited. Other features that would be nice would be good chat and social features (or integration with other chat or social network systems), leaderderboard or tournament systems, and easy integration of bots to provide AI opponents in case there aren't enough human players around. Game timers, to keep people moving at a reasonable rate, would also be good. Saving game records, and allowing people to replay and review records for study, would be nice too, though I'm not expecting much as those types of features tend to only show up in purpose built engines for games like chess or Go. Being free open source software would be a big plus, so I could extend it myself, though closed or hosted solutions might be acceptable if they provide enough of the above features or provide some means for extending them. Are there any such systems that meet my needs? Or any that are close even if not exactly matching? Some similar systems, that don't quite meet my needs, would include Yahoo Games, which is web based, but I can't write my own games for it (or any of many similar servers in that category). Volity, which is built on SVG and XMPP. It's open source, designed to be an open standard, has support for bots, etc, but it requires a separate client download, and seems not to be actively developed or used any more. SuperDuperGames, which is an open source, online system for doing turn based (play by mail style) games. That is, it's not live or real time, but instead you submit your moves, and wait for someone to submit theirs, within the next day or so. It's an active community, but I want something where I can play games live, not over the course of weeks or months.


Approaches for storing grid like information I am drawing this simple grid on my NodeJS server var grid for(var x 0 x lt 20 x ) grid x for(var y 0 y lt 20 y ) grid x y 0 console.log(grid) The outcome looks like this I know, pretty right?! 0 is supposed to indicate FREE, thus if a player requests to move to a field with 0, he will! The problems come when I want to add more then just Free Occupied, for instance I would like to give each Array Element an ID number for the Client Updates, or certain features on the field to be stored. I tried to assign something N, something2 N But thought it looked rather performance expensive in the long run. (On a big Grid) I read about using a single Object for several elements, but I cannot find this any more.. Should I perhaps use an Array of Objects, or an Additional Array inside each X,Y element? Any performance convenience anything goes tips are welcome D Edit Thank you for the ideas so far, I was now thinking to perhaps using Strings. Storing Variable A "," Variable B and then later using the .split to use the information. Any thoughts on this?


Timers and performance for mobile JS I'm using the Three.js JavaScript library to do some things in WebGL, and I wonder how the graphic aspects of timers are done on mobile. I was creating numbers with geometries and just replacing them when needed. This was fine on desktop (or so I think, lol). Recently, I've been playing around with mobile and the previous method is far too slow.


Drawing adding shape objects with the mouse on html canvas I've started with the canvas paint tutorial from link which worked fine with a few problems that can be fixed later. I've been checking a lot of posts on drawing shapes on the canvas but they all use draw functions in a gameloop or intervals but I do not want to use draw() in an interval or gameloop for now, I just need to update the content on userinput. I am trying to create a drawing software that paints objects instead of just bitmaps. I've been debugging for a while now and can't find the problem I have problems accessing the objects in the pointsArr array. I was only able to add rectangles to the screen by using contextVar.strokeRect(50,50,50,50) directly with the mouseDownVarso far. Yes I know that the addFilledCircleFunc creats rectangles, for now I just want everything to work properly. to do add gameloop and draw with gameloop? stroke line in resize fix collission check detection objects functions to draw detection objects implement resize? Varibale declration var canvasVar document.getElementById('canvasHtmlElement') var contextVar canvasVar.getContext('2d') var pointRadiusVar 10 var mouseButtonHeld false var pointsArrPosition 0 Arrays var pointsArr Varibale declration end canvas setup canvasVar.width window.innerWidth canvasVar.height window.innerHeight canvas setup end resize fix window.onresize function() var tempImageVar contextVar.getImageData(0,0, canvasVar.width, canvasVar.height) canvasVar.width window.innerWidth canvasVar.height window.innerHeight contextVar.putImageData(tempImageVar, 0,0) resize fix end contextVar.lineWidth pointRadiusVar 2 Line Width functions Objects function pointObject () this.x 0 this.y 0 this.w 10 default width and height? this.h 10 this.fill ' 444444' this.stroke stroke "skyblue" this.strokewidth strokewidth 2 function addFilledCircleFunc(x, y, w, h, fill) var filledCircle new pointObject filledCircle.x x filledCircle.y y filledCircle.w w filledCircle.h h filledCircle.fill fill pointsArr.push(filledCircle) Objects end create circle on mouse clicked point while mousebutton is held var addPointToCanvasVar function (e) if(mouseButtonHeld) addFilledCircleFunc(e.clientX, e.clientY, 10, 10, ' 444444') old drawing code contextVar.lineTo(e.clientX, e.clientY) contextVar.stroke() contextVar.beginPath() contextVar.arc(e.clientX, e.clientY, pointRadiusVar, 0, Math.PI 2) contextVar.fill() contextVar.beginPath() contextVar.moveTo(e.clientX, e.clientY) MAKE SURE that lines work when drawn over the edge of the canvas function clearPathIfMouseCursorLeavesCanvasFunc(e) contextVar.beginPath() clears the path so buttonpresses dont connect the line mouseButtonHeld false end mouse Up Down Switch var mouseDownVar function(e) alert("mouseDown") contextVar.strokeRect(e.clientX, e.clientY,50,50) draw() mouseButtonHeld true addPointToCanvasVar(e) add point on first click, not just when mousebutton is held var mouseUpVar function() alert("mouseUp") mouseButtonHeld false contextVar.beginPath() clears the path so buttonpresses dont connect the line mouse Up Down Switch end functions end listeners canvasVar.addEventListener('mousemove', addPointToCanvasVar) canvasVar.addEventListener('mouseup', mouseUpVar) canvasVar.addEventListener('mousedown', mouseDownVar) canvasVar.addEventListener ('mouseout', clearPathIfMouseCursorLeavesCanvasFunc) listeners end draw function function draw() alert('drawing') contextVar.strokeRect(pointsArr pointsArrPosition .x,pointsArr pointsArrPosition .y,pointsArr pointsArrPosition .w,pointsArr pointsArrPosition .h) pointsArrPosition draw function end


Mouse position to grid position not working I have a function which converts my mouse position to grid position in the game but it is not working properly... its slightly off. I have two functions one which converts from grid to screen position (this particular one, works fine) and the code is function mapToScreen(gridX,gridY,screen) var grid 64 var x (gridX gridY) (grid 2) x screen.offsetX camera scroll offset X axis x grid 2 centre of the iso tile on X axis var y (gridX gridY) (grid 4) y screen.offsetY camera scroll offset Y axis y grid 4 centre of the iso tile on Y axis return x,y So my function to do the opposite looks like this function screenToMap(pixelX,pixelY,screen) var grid 64 pixelX screen.offsetX pixelX grid 2 pixelY screen.offsetY pixelY grid 4 var gridX Math.floor((pixelX (grid 2) pixelY (grid 4)) 2) var gridY Math.floor((pixelY (grid 4) (pixelX (grid 2))) 2) return gridX, gridY The problem is as shown below in the image, it doesn't return the correct number. The first corner tile should be 0,0 . Also notice the co ordinate doesn't change correctly with the tile border. I don't know how to solve that either.


How can I detect mouse events on sprites in a canvas? I'm making an HTML 5 game. I want mouse clicks on sprites drawn in a canvas element cause events that my code can react to. At the moment, I'm doing it by checking through all of my sprites in a for loop on each click. Is there a way to do that by adding an event listener to a sprite so it would respond just like that? Are Javascript's custom events useful in this situation? I know it's possible with KinectJS, but I don't have any experience with it and really I'd like to learn how to do this myself without the help of a library.


Shop and Inventory System I'm creating a JavaScript game, and I'm getting stuck. When the player obtains X amount of gold, a middle column appears (you've unlocked the shop, yay!), and when you obtain more gold than an item costs, it will appear (except special conditions where it requires more than just gold of course). Right now, I'm stuck on the base foundation of the system, and I would like to hear some suggestions before I move on. function shop() this.items effect function() engine.player.revive(true) , "price" 100, "name" "Heal" The shop holds an array of item objects, some will be holdable, some will be instant use (currently working on instant use). Now, here's how the item is called in my elements.js file addShopItem function(gold) console.log(engine.shop.items.length) for (var i 0 i lt engine.shop.items.length i ) if (engine.shop.items i "price" lt gold) document.getElementById("items").innerHTML " lt br gt " engine.shop.items i .name , Which is called by going raiding (irrelevant, won't post that code, it's going to change to the engine's trigger function with flags based on the item object. Now my question is Is this a good way to handle an dynamic shop system? What's the best way to link this to a player object? (My initial guess is an object inventory inside the parent?


how to replace vertex buffer in webGL I want to replace a vertex buffer with another completely different vertex buffer, different size and values, it will not get replaced every frame. gl.deleteBuffer(vertexBuffer) vertexBuffer gl.createBuffer() gl.bindBuffer(gl.ARRAY BUFFER, vertexBuffer) gl.bufferData(gl.ARRAY BUFFER, vArray, gl.STATIC DRAW) I am using that code to replace it, I don't think it is the correct way because I am getting GL ERROR GL INVALID OPERATION glDrawArrays attempt to render with no buffer attached to enabled attribute 1 I don't know if this is related to the error but I am rendering using the vertex buffer when I replace it.


Loading chunks of the terrain relative to the player's position I'm making a small voxel based multiplayer WebGL game with a Node.JS server which handles player positions and sends terrain chunk data to the clients. This is an example of how I'm currently sending the chunks var viewDistance 6 for (var x playerPosX viewDistance x lt playerPosX viewDistance x ) for (var z playerPosZ viewDistance z lt playerPosZ viewDistance z ) for (var y playerPosY viewDistance y lt playerPosY viewDistance y ) client.send( getChunk(x, y, z) ) This simply loads and sends the chunks within the view distance, however I'm looking for a way to prioritize sending the chunks nearest to the player first. Obviously it's no good loading chunks that are far away before loading the one the player is standing on. Assuming playerPosX, playerPosZ and playerPosY store the positions of the player and client.send( getChunk(x, y, z) ) will send the chunk, does any one have any ideas how I would do this? Thanks.


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.


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 access files in Chrome So, I am making a game like html file that needs to load a few assets. I have a loading animation which uses the timing of the loading files to create a progress bar. This all goes fine. The files all load, and the app launches. However, none of the files can access each other as they are all in different script tags. And I cannot merge them because the JS is never actually put into the html. So what I need to do is to access the local file system (it uses the file prototype) and read the file, then stick the text into a script tag. However, all of the examples I have found on the web throw this error Xhtmlrequests can only access (list of protocols not including file) What I need is a JS way to access the files with no input from the user (other than opening the application). How can this be done?


How to handle transparent pixels in a spritesheet I am trying to correctly handle transparent pixels. I have a spritesheet that gave me the following The green body is the ground physics body and the gray body around the sprite is the sprite's physics body calculated with the bounds of the sprite. I plan on having images for the ground body of the same size, and wanted the sprite's feet to touch the ground. I was able to achieve this by repacking the images in a new spritesheet with TexturePacker, without any transparent pixels However, now my problem is other animations, like crouch for example As you can see, the sprite's feet are once again off the ground. Doing this animation in the game looks silly because the sprite crouches by lifting his feet off the ground body. The output metadata in JSON from TexturePacker looks like this "filename" "Crouch soldier crouch 1.png", "frame" "x" 712,"y" 867,"w" 353,"h" 425 , "rotated" false, "trimmed" true, "spriteSourceSize" "x" 49,"y" 42,"w" 353,"h" 425 , "sourceSize" "w" 433,"h" 500 , "pivot" "x" 0.5,"y" 0.5 , ... This is a problem for several of my animations with this and other sprites. Repacking with TexturePacker allows me to remove the transparent pixels and have a more accurate physics body (which was really the goal, I'd like the most accurate collision detection once I start having projectiles) but now the animations look funny. How is something like this handled in game development?


JavaScript 2D Top down Tile Collision Detection I am developing a small Top down Game (Much like the old Zelda Games) and I'm having an issue in terms of Collision detection (The actual theory itself rather than assigning Tiles as solid, etc.) I have a function called "checkTileCollision" which takes two parameters, X and Y, and is called through the Player's Move function. X and Y are the location of the player AFTER they have moved, as it's suppose to check the position the player is moving to for a solid Tile(s), and if it finds any, returns true to stop movement. My Player is larger than a Tile (For examples sake, let's say each Tile is 32x32 and the Player is 26x60) and I need to know an efficient way to detect whether or not the player is attempting to step on to a Solid tile. The Player doesn't move on the Grid and is free moving, so X and Y are true positions and not Tile co ordinates. Please note I am aware of things such as Box2D but I'm wanting to do this without the use of third party libraries. Any help is appreciated!


How do I get an attribute of a function? function randArray(arrayName) arln arrayName.length arst arrayName Math.floor(Math.random() arln) return arst create function() starts physics engine game.physics.startSystem(Phaser.Physics.ARCADE) player game.add.sprite(width 2, height 2, 'player') randSpawnItem game.add.sprite(10, 10, randArray(randItem)) randSpawnItem2 game.add.sprite(50, 50, randArray(randItem)) So the randArray function works, and there is nothing wrong with the create. I'm using Phaser, and I'm trying to spawn items randomly (kind of like in Binding of Issac.) I forsee a problem in the future, when I'm detecting for collison, I need to know what item spawned to give the right kind of item to the player. How would I get that third attribute of randSpawnItem or randSpawnItem2, or is there another way to go at this completely? Sorry if that's a noobie question! Didn't know how to word it and didn't find it anywhere else. Thanks in advance for your time.


How to save and update modifications done by the player in my procedurally generated JavaScript game? I am making a game and I need the world to be generated and saved. I used Perlin noise to generate the terrain (and other stuff like trees), but cannot figure out the best way to save and recall actions done by the player, e.i. if a tree is cut down or a mineshaft is used I want that entity to either be updated or deleted. How could I accomplish this? More info I am making this in JavaScript and eventually want to implement Node.js to implement multiplayer features in the future. The player also has a very limited view and this is a 2D top down kind of game. I am also making this basically from scratch. Any and all help is appreciated!


HTML5 Canvas Drawing with Floats I'm trying to implement a game where you have car moving along a line in HTML5 Canvas. Using a little bit of trigonometrie I managed to get the right x and y coordinates to add to the coordinates of my image each frame to get to the end of the "line". Now the problem is, the image I use for the car starts to stutter in the process of rendering. The problem has to be the values I'm adding. (first I thought the problem would be the render loop but when using the render loop from paul irish the same problem occurs) My question is, how can I use floats in context.drawImage(img,...) smoothly? What I tried was rounding the values where the image should move to (e.g. context.drawImage(img, Math.round(car.x), Math.round(car.y))) but this doesn't work also. simple code example to demonstrate the issue (using a simpler loop, but like I said, the problem isn't the loop) How it looks Here is the whole thing var canvas document.getElementById("canvasID") var context canvas.getContext("2d") var car new Car(20,10) var carImg new Image() carImg.src "https i.stack.imgur.com L2XQW.png" function Car(x,y) this.x x this.y y Car.prototype.advancePosition function(x,y) this.x lerp(car.x, car.x x, 1) this.y lerp(car.y, car.y y, 1) function update() car.advancePosition(0.91,0.4) function lerp (start, end, amt) return (1 amt) start amt end function render() context.beginPath() context.clearRect(0,0, canvas.width, canvas.height) context.drawImage(carImg, car.x, car.y) context.closePath() window.requestAnimFrame (function(callback) return window.requestAnimationFrame window.webkitRequestAnimationFrame window.mozRequestAnimationFrame window.oRequestAnimationFrame window.msRequestAnimationFrame function(callback) window.setTimeout(callback, 1000 100) )() (function mainLoop() requestAnimFrame(mainLoop) render() update() )() canvasID z index 1 background eee display block vertical align middle margin 0 auto z index 1 webkit box sizing border box moz box sizing border box box sizing border box position absolute webkit transform translateZ(1) lt html gt lt head gt lt meta charset "utf 8" gt lt meta name "viewport" content "width device width, initial scale 1.0, user scalable no" gt lt link rel "stylesheet" type "text css" href "style.css" gt lt title gt test lt title gt lt head gt lt body gt lt div class "canvas wrapper" gt lt canvas id "canvasID" width "500" height "450" gt Canvas not supported, please update your browser lt canvas gt lt div gt lt script src "main.js" gt lt script gt lt body gt lt html gt I would be happy if someone could help me out Thanks edit Tried the suggestions from the comments but nothing worked.


Line strokes also adding borders to other shapes? When you run the project, you can see that the first circles have a black border around them. When I remove the Game.drawLines(), the circles don't have the border around them anymore. Any help is appreciated!


HTML5 game obfuscation HTML5 games have viewable source code. Is there a way to make them like swf file? How to hide the game algorithm? What do you think of the Firefox JavaScript Deobfuscator Plugin and obfuscation?


Best resources for Canvas Html 5 development I am at a competition at work for who can make the best canvas game. Theme is a top down shooter... Winner gets dinner for free. Anyways I have been looking around looking for some good resources on game deving on the canvas. Any body got any good ones?


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?


Rotate arrow on canvas I need to draw a flow dynamically based on some user choices. In that flow I want to draw the choices (blue circles with number) and the directions of that choices (line and arrow). For example node 1 to node 2. JSFiddle Example To draw the direction I draw a arrow in the end of the line but I can't make the arrow rotate around itself. JS code (document).ready(function () drawOnCanvas() ) function drawOnCanvas() var canvas document.getElementById('myCanvas') if (canvas.getContext) var ctx canvas.getContext("2d") var circle1 x 75, y 75, r 15 var circle2 x 225, y 50, r 15 var arrow h 5, w 10 drawCircle(ctx, circle1, "1") drawCircle(ctx, circle2, "2") var ptCircle1 getPointOnCircle(circle1.r, circle1, circle2) var ptCircle2 getPointOnCircle(circle2.r, circle2, circle1) var ptArrow getPointOnCircle(circle2.r arrow.w, circle2, circle1) drawLine(ctx, ptCircle1, ptCircle2) drawArrow(ctx, arrow, ptArrow, ptCircle2) function drawArrow(canvasContext, arrow, ptArrow, endPt) var angleInDegrees getAngleBetweenPoints(ptArrow, endPt) canvasContext.beginPath() first save the untranslated unrotated context canvasContext.save() move the rotation point to the center of the rect canvasContext.translate(ptArrow.x, ptArrow.y) rotate the rect canvasContext.rotate(angleInDegrees) canvasContext.moveTo(endPt.x, endPt.y) canvasContext.lineTo(endPt.x arrow.w, endPt.y arrow.h) canvasContext.lineTo(endPt.x arrow.w, endPt.y arrow.h) canvasContext.closePath() canvasContext.fillStyle "rgb(72,72,72)" canvasContext.stroke() canvasContext.fill() restore the context to its untranslated unrotated state canvasContext.restore() function drawCircle(canvasContext, circle, text) canvasContext.beginPath() come a ou reinicia o desenho de algo canvasContext.fillStyle "rgb(43,166,203)" canvasContext.arc(circle.x, circle.y, circle.r, 0, 2 Math.PI, false) cria arcos canvasContext.fill() atribui estilos drawText(canvasContext, circle, text) function drawText(canvasContext, circle, text) canvasContext.font '8pt Calibri' canvasContext.fillStyle 'white' canvasContext.textAlign 'center' canvasContext.fillText(text, circle.x, circle.y 3) function drawLine(canvasContext, startPt, endPt) canvasContext.moveTo(startPt.x, startPt.y) canvasContext.lineTo(endPt.x, endPt.y) canvasContext.stroke() function getPointOnCircle(radius, originPt, endPt) var angleInDegrees getAngleBetweenPoints(originPt, endPt) Convert from degrees to radians via multiplication by PI 180 var x radius Math.cos(angleInDegrees Math.PI 180) originPt.x var y radius Math.sin(angleInDegrees Math.PI 180) originPt.y return x x, y y function getAngleBetweenPoints(originPt, endPt) var interPt x endPt.x originPt.x, y endPt.y originPt.y return Math.atan2(interPt.y, interPt.x) 180 Math.PI I think the problem is in drawArrow() method in the lines canvasContext.translate(ptArrow.x, ptArrow.y) canvasContext.rotate(angleInDegrees) I already tried every possible values for the rotation and the translation but arrow still don't rotate properly around itself. Can anyone help me?


In an asynchronous server environment where player input and timed events modify data is using an in memory array problematic? So let's say I have a server running on node.js, and there is an array of player objects... At an interval, all of these player objects are looped and processed for events and changes that are based on time, such as fuel or food consumption and movement. However players can also trigger things from the client that could modify player data as well. Now what I'm trying to determine is if I am going to run into any problems with timing, such as if we are mid loop and somebody changes something and it throws some other calculation off balance. Will I need to implement some kind of locking mechanism I can use as needed or is there a better way to hold this data in memory?


Limiting Framerate and Input So I have been learning HTML5 canvas recently and ran into a bit of a snag. I created a proof of concept that builds a block based 2d map that you can move a character inside of using arrow keys. This works well because everything is free moving (character moves 1 pixel per frame, so the movement is fluid and looks good). I am trying to fork off of this code to create another concept that forces grid based movement (like in a typical roguelike). I have updated my movement code to move in chunks equal to tile size.. but the issue is that the refresh rate is so fast that it just seems like the character is moving at super speed. Here is a snippet of my code that handles animations function gameLoop() ctx.clearRect(player.x,player.y,PLAYER SIZE,PLAYER SIZE) getInput() ctx.fillStyle ' 000000' player.draw(ctx) window.requestAnimationFrame(gameLoop) Is using requestAnimationFrame() for this sort of movement not a good idea? Is it better to just setInterval() for this sort of thing? I found a article via Google that talks about using variables for time, delta, fps, etc to limit the framerate... but Im not sure I understand how to do that in conjunction with requestAnimationFrame(). Should I somehow hold my gameLoop() from hitting requestAnimationFrame() until some time interval is hit? That seems like it would just be a waste because I would need to force a loop of some kind... doesnt seem too elegant


setting a time delay between two frame when animation a sprite sheet this is my jsfiddle http jsfiddle.net Z7a5h As you can see the animation of the sprite sheet when the player is not moving is too fast so i was trying to make it slow by declaring two variable lastRenderTime 0,RenderRate 50000 but my code is not working and it seem i have a misunderstanding of the algorithm i am using so can anyone lay me a hand to how can i fix it ? if (!this.IsWaiting) this.IsWaiting true this.Pos 1 (this.Pos 1) 3 else var now Date.now() if (now this.lastRenderTime lt this.RenderRate) this.IsWaiting false this.lastRenderTime now


How can I delete an object when it's not stored in an array? I have a boss appearing in my game, but since it's only one character I didn't put it in an array. Now I'm trying to make disappear if its health is less or equal to 0 but I don't know how to do that. Is there a way to remove the object? I only know how to remove a property of an object. Here's the boss object function Boss1(x, y) this.sprite boss1Sprite this.x x this.y y this.imgWidth 160 this.imgHeight 224 this.frameWidth this.imgWidth 4 this.frameHeight this.imgHeight 4 this.health 1500 this.directionMode 1 this.currentFrame 0 this.SPEED 1 this.delta 1 this.updateFrame function () this.currentFrame 0.2 this.showHealth function () ctx.fillStyle "red" ctx.fillRect(this.x,this.y 10,(this.health 100) 3.3,5) ctx.strokeRect(this.x, this.y 10, (100 100) 50, 5) this.show function () this.updateFrame() this.walkingMode Math.floor(this.currentFrame) 4 ctx.drawImage(this.sprite, this.walkingMode this.frameWidth, this.directionMode this.frameHeight, this.frameWidth, this.frameHeight, this.x, this.y, this.frameWidth, this.frameHeight) target hero position this this.move function () this.dx hero.x this.x this.dy hero.y this.y this.length Math.sqrt(this.dx this.dx this.dy this.dy) if (this.length) this.dx this.dx this.length this.dy this.dy this.length this.x this.dx this.delta this.SPEED this.y this.dy this.delta this.SPEED enemy wave object function random(min, max) return Math.random() (max min) min function Enemy(x, y) this.sprite enemySprite this.x x this.y y this.imgWidth 128 this.imgHeight 192 this.frameWidth this.imgWidth 4 this.frameHeight this.imgHeight 4 this.toDelete false this.dx random(1, 3) this.enemiesHealth 100 this.directionMode 1 this.currentFrame 0 this.updateFrame function() this.currentFrame 0.2 this.showHealth function () ctx.fillStyle "red" ctx.fillRect(this.x,this.y 10,(this.enemiesHealth 100) 50,5) ctx.strokeRect(this.x, this.y 10, (100 100) 50, 5) this.show function() this.updateFrame() this.walkingMode Math.floor(this.currentFrame) 4 ctx.drawImage(this.sprite,this.walkingMode this.frameWidth, this.directionMode this.frameHeight, this.frameWidth, this.frameHeight, this.x, this.y, this.frameWidth, this.frameHeight ) this.move function() this.x this.x this.dx this.deletion function() this.toDelete true this is when the boss is spawning the game loop function draw() bullets bullets.filter((bullet) gt bullet.x lt viewLimit) enemies enemies.filter((enemy) gt enemy.x gt viewLimit1) while (enemies.length lt enemiesPerTick amp amp kills lt 5) var enemy new Enemy(canvas.width, random(0, canvas.height 60)) enemies.push(enemy) for (var v 0 v lt enemies.length v ) enemies v .showHealth() ctx.clearRect(0, 0, canvas.width, canvas.height) hero.show() hero.update() hero.showHealth() for (var i 0 i lt bullets.length i ) bullets i .show() bullets i .move() for (var j 0 j lt enemies.length j ) enemies j .show() enemies j .move() for (var t 0 t lt enemies.length t ) enemies t .showHealth() collision() drawScore() if (enemies.length 0) boss1.show() boss1.move() boss1.showHealth() requestAnimationFrame(draw) console.log(enemies, bullets) draw()


How can I get a 4x4 matrix from a bullet quaternion? I'm trying to make a game using JavaScript with Ammo.js ( an implementation of bullet ) and Sylvester to do my matrix maths. The problem is I don't know how to turn the WXYZ that bullet gives into the 4x4 matrix Sylvester needs. If there is a way to just get Bullet Physics to give me the 4x4 matrix please tell me! I am completely lost here.


Why can't i change the background color in Phaser? what is wrong with my code? i'm using game.stage.backgroundColor but the screen remains black. main.js var demo demo demo.game new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '') demo.game.state.add('state1', demo.state1) demo.game.state.add('state2', demo.state2) demo.game.state.start('state1') state1.js var demo demo demo.state1 function() demo.state1.prototype preload function() , create function() game.stage.backgroundColor " 4488AA" , update function()


Tile Map Coordinates I am have now this code http jsfiddle.net DK67k 2 In here is 2D tile map and when you click on tile you get coordinates on alert. But for get precises coordinate you need click on top left tile(tiles is 16x16) and if I click on bottom right tile I am get second tile coordinates. Maybe anyone have idea how to fix this?


Implement Fast Inverse Square Root in Javascript? The Fast Inverse Square Root from Quake III seems to use a floating point trick. As I understand, floating point representation can have some different implementations. So is it possible to implement the Fast Inverse Square Root in Javascript? Would it return the same result? float Q rsqrt(float number) long i float x2, y const float threehalfs 1.5F x2 number 0.5F y number i ( long ) amp y i 0x5f3759df ( i gt gt 1 ) y ( float ) amp i y y ( threehalfs ( x2 y y ) ) return y


UV texture mapping with perspective correct interpolation I am working on a software rasterizer for educational purposes and I am having issues with the texturing. The problem is, only one face of the cube gets correctly textured. The rest are stretched edges You can see the running program online here. I have used cartesian coordinates, and all I do is interpolate the uv values along the scanlines. The general formula I use for interpolating the uv coordinates is pretty much the one I use for the z buffering interpolation and looks like this (in this case for horizontal scanlines) u Slope (right.u left.u) (triangleRight x triangleLeft x) v Slope (right.v left.v) (triangleRight x triangleLeft x) ... new u left.u ((currentX onScanLine triangleLeft x) u Slope) new v left.v ((currentX onScanLine triangleLeft x) v Slope) Then, when I add each point to the pixel buffer, I restore z and uv z (1 z) uv.u Math.round(uv.u z 100) 100 because my texture is 100x100px uv.v Math.round(uv.v z 100) Then I turn the u v indexes into one index in order to fetch the correct pixel from the image data (which is a 1 dimensional px array) var index texture.width uv.u uv.v and the rest is unimportant imagedata index .RGBA bla bla The interpolation formula is correct considering the consistency of the texture (including the straight stripes). I must get some sleep now, but before I get into further dissecting of every single value to see what goes wrong, Can someone more experienced guess why might this be happening, just by looking at the cube? "I have no idea what I'm doing" (it's my first time implementing a rasterizer). Did I miss an important stage? Thanks for any insight. PS My UV values are as follows u 0, v 0 , u 0, v 0.5 , u 0.5, v 0.5 , u 0.5, v 0 , u 0, v 0 , u 0, v 0.5 , u 0.5, v 0.5 , u 0.5, v 0 EDIT The uv values were to blame, and pixel 50 being in the second zone, as Victor pointed out. My new uv values u 0, v 0 , u 0, v 1 , u 1, v 1 , u 1, v 0 , u 1, v 0 , u 1, v 1 , u 0, v 1 , u 0, v 0 To some extent this was "a bug in my code", but also I had overlooked an important part of the process the uv values should not just be assigned to the 8 corners of the cube.


Chrome Angry Birds engine? Was Chrome AngryBirds game made using html5 canvas? And if yes what kind of engine did they use?


Confused about Max Vertex Uniform Vector limit While coding my WebGL app I've encountered an interesting phenomena On my first PC (with GPU Radeon HD 5850), BrowserLeaks (link) tells me that in my browser Google Chrome Version 36.0.1985.143m the Max Vertex Uniform Vectors value equals 1024 which is true, when I try to create inside the shader an attribute array bigger than 1024, the browser throws an error too many uniforms, which f.e. in my case let's me draw about 85 simple cubes in a single draw call. Meanwhile on my other PC (with GPU Intel X3100) with Opera Next Version 12.15 installed, where BrowserLeaks shows a value 4096 next to the Max Vertex Uniform Vectors field, I can init an array of size 250 000 and even bigger, I can draw 20 000 cubes in a single draw call and everything works fine (except a very low framerate). So now my question is Why those numbers varies so much, why in the second case the upper limit value does not seem to be valid? How would I find the true upper limit value (and read it inside my WebGL app at the runtime)? EDIT Ok, I've found out how to get this parameter inside a WebGL app gl.getParameter(gl.MAX VERTEX UNIFORM VECTORS), but the question now is how would I adapt it to shaders...


Which free HTML5 based game engine meets these requirements? I am experienced with traditional JS and HTML but new to HTML5. I want to develop games in HTML5 so that it can work on all devices and browsers, including IE. Additionally, I require the following features Physics Engine Animation Some AI Vector drawing and manipulation Better user player controls, et cetera I know there are many options, but just want some one that can give most flexibility... so I want some thing that can also be compiled to achieve maximum functionality. One that is in my mind is GameKit but please tell what you guys would suggest that meets my requirements.


My sprite is not listening to any keyboard keys First time ever creating html canvas game. Once I finally got my sprite ant tiles drawn on the canvas, now I want to make my sprite interactive. Unfortunately, for some reason it is not working. I get a message in console when the certain key is pressed but the sprite is not changing its position. I wonder why? The code var canvas document.getElementById("canvas") var context canvas.getContext("2d") var mapArray 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 var StyleSheet function(image, width, height) this.image image this.width width this.height height this.draw function(image, sx, sy, swidth, sheight, x, y, width, height) context.drawImage(image, sx, sy, swidth, sheight,x, y, width, height) this.drawimage function(image, x, y, width, height) context.drawImage(image, x, y, width, height) Initial Sprite Position var boatPosX 230 var boatPosY 200 var Loader function(src) this.image new Image() this.image.src src this.image.onload function() var sprite new StyleSheet(background, 36, 36) var ship new StyleSheet(boat, 90, 100) for (let i 0 i lt mapArray.length i ) for (let j 0 j lt mapArray i .length j ) if (mapArray i j 0) sprite.draw(background, 190, 230, 26, 26, i sprite.width, j sprite.height, sprite.width, sprite.height) if (mapArray i j 1) sprite.draw(background, 30, 30, 26, 26, i sprite.width, j sprite.height, sprite.width, sprite.height) if (mapArray i j 2) sprite.draw(background, 200, 20, 26, 26, i sprite.width, j sprite.height, sprite.width, sprite.height) ship.drawimage(boat, boatPosX, boatPosY, 50, 50) return this.image Sprite controls function move(e) if (e.keyCode 39) boatPosX 2 console.log("works") if (e.keyCode 37) boatPosX 2 document.onkeydown move var background new Loader("ground.png") var boat new Loader("ship.png") console.log(background)


Rectangles clear each other when moving on canvas I am having this problem after moving rectangles, they seem to delete one another. Most probably it is a problem with clearRect(...) method. This is the clean function I am using clean function(element) All default values clean all the screen if(typeof element.x 'undefined') element.x 0 if(typeof element.y 'undefined') element.y 0 if(typeof element.width 'undefined') element.width canvas.width if(typeof element.height 'undefined') element.height canvas.height In case values are entered if(element.type 'rectangle') ctx.clearRect(element.x,element.y,element.width,element.height) This is the rendering rect function(element) Check if color is defined if(typeof element.color 'undefined') element.color 'black' else ctx.fillStyle element.color Draw the rectangle ctx.fillRect(element.x,element.y,element.width,element.height)


JavaScript rendering Canvas or DIV? I am planning on developing a multiplayer RPG (kinda like RuneScape, but don't worry, with a different gameplay) and i want to do this in the browser. Now before saying things like "A MMORPG is hard to make" or "Others tryied that too" please keep in mind that i am not dreaming at a huge game, it's just an idea that i want to see "breathing". The reason i choose JavaScript and HTML5 over other technologies is that i have some experience in web development (which of course includes a deep understanding of JS). I've looked over some libraries (or so called engines) on the web and i've found some that might have what i need. My question is What is the best way to render this kind of game in the browser, also could you suggest me the library that you think is the most suitable for this kind of job?


Javascript Audio solution still has issues. Flash works but... requires flash (an issue for iOS). What do you use in Javascript for audio?


Lighting effects with 2D sprites I would like to know how to best achieve lighting effects with 2D. I guess the only way is to make sprites of the area to be lit in specific colors? Say I have a streetlamp, and around this place sprites to make it appear lit? Is there a better way? Edit Found a good screenshot of what I'm looking for http www.saltgames.com wp content uploads 2009 11 multipleLights.png


How do I write a simple 2 player server? I've recently started learning JavaScript and HTML and developed simple 2 player game such as tick tack toe, battleship, and dots amp boxes. However, these 2P games can only be played on one computer (i.e. the 2 players must sit together). I want them to be able to play with a friend on a different computer. Would anyone have a general, simple working example of a web game server?


How to implement map scrolling inertia formulae I'm looking for a mathematical formulae to calculate map scrolling inertia. Basically I have an HTML5 Canvas displaying part of a map and I capture the mousedown mousemove mouseup to calculate my new offset. And when I scroll the map I want the map to continue scrolling for a few moments after the user stopped dragging the cursor. I do have a sample implementation but I'm not really satisfied with it. I'd be looking for a nice clean math formulae to achieve this. I'd like my map to behave for example like in Civ 5 when you scroll the map around. Here is part of my implementation (working jsfiddle https jsfiddle.net CowWarrior dkxnj5d8 1 ) mouseup stopMapDrag function (e) var movementX (e.pageX this.startX) var movementY (e.pageY this.startY) this.mapOffsetX parseInt(this.mapOffsetX) movementX this.mapOffsetY parseInt(this.mapOffsetY) movementY this.isDragging false this.displayMap() calculate last vector ui.vectorX parseInt(e.pageX ui.absStartX) ui.vectorY parseInt(e.pageY ui.absStartY) show inertia setTimeout(function() ui.dragInertia(2) , 30) console.log("(vectorX " ui.vectorX ", vectorY " ui.vectorY ")") (' canViewport').css('cursor', 'default') , need to find a good formulae for inertia dragInertia function (factor) var movementX parseInt(ui.vectorX factor) var movementY parseInt(ui.vectorY factor) ui.mapOffsetX parseInt(ui.mapOffsetX movementX) ui.mapOffsetY parseInt(ui.mapOffsetY movementY) ui.displayMap() if (factor lt 8) setTimeout(function() ui.dragInertia(factor 1.2) , 30) ,


Why my canvas isn't showing anything after I put code in the loop for tile map? My canvas stop showing anything when I want to display a tile 25 times. No errors. Here is the code var canvas document.getElementById("canvas") var context canvas.getContext("2d") var StyleSheet function(image, width, height) this.image image this.width width this.height height this.draw function(image, sx, sy, swidth, sheight, x, y, width, height) image.onload function() context.drawImage(image, sx, sy, swidth, sheight,x, y, width, height) var Loader function(src) this.image new Image() this.image.src src this.image.onload function() var sprite new StyleSheet(background, 16, 16) for (i 0 i lt 25 i ) for (j 0 j lt 25 j ) sprite.draw(background, 30, 30, 36, 36, i 36, j 36, 36, 36) return this.image var background new Loader("https opengameart.org sites default files PathAndObjects.png") console.log(background)


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


How to get the center of a rotated rectangle regardless of point of rotation I need help working out the centre coordinate of a rotated rectangle regardless of the point of rotation (i.e. the rectangle doesn't rotate around its center). I do not know the coordinates of the corners, so it's not a simple case of dividing those. It's easier to show than tell, so here's example 1 http gametest.mobi rotate index.php?f point1.js amp d tests Click to start stop the rotation. In this example I've got my sprite with the rotation point set to the bottom right corner of it. If you click you'll see it rotate around that. I need to find a way to work out the coordinates of the center of the rectangle (represented by the middle red cross hairs.) Here is another example, this one is set to rotate at 0.3 x 0.8 into the rectangle http gametest.mobi rotate index.php?f point3.js amp d tests You can see I added the circle into each demo, this is positioned on the sprites x y coordinate and the radius was calculated from the distance of the center of the rectangle to the rotation origin. I can visually see the correlation between the point of rotation and the circle, and I can see it tracks the centre of the rectangle beautifully on the circles perimeter! But I'm falling at the last hurdle in trying to calculate the actual value, so desperately need a fresh set of eyes on it please.


Eliminate isolated cave in procedural cave generation I've got an algorithm that generates a cave procedurally, the map is modeled in the data as a 2d array of 0s (empty space) and 1s (wall). The algorithm works just fine, but I've got quite some isolated small caves on the scene, which I would like to avoid. That's how the map looks that gets generated. Is there some efficient algorithm to remove the black holes in the white wall sections? I was thinking of something like For every closed cave, check if there is a bigger cave and if so, close it. But that seems insanely inefficient since I'd have to loop over the map a lot in order to do this for all small caves.


Get speed from vector using box2d and javascript I need to find the speed of an object in a game. The game is made in HTML5 with jquery and jquery.box2d. For this I can use these methods GetLinearVelocity().x GetLinearVelocity().y I'm then trying to calculate the speed from this piece of code, but get some values that doesn't make sense when I console.log it. This is my code var heroVelX game.currentHero.GetLinearVelocity().x var heroVelY game.currentHero.GetLinearVelocity().y var speed Math.sqrt(heroVelX 2 heroVelY 2) console.log(speed) Some of the values in console.log are numbers, but most of them are NaN (Not A Number), which confuses me? Can someone help me solve this? The goal I want to achieve, is to see when the speed(of object .currenHero) drop below a certain value, so I can excute a new state in the game.


Fix latency when sending state I have a multiplayer game done with Phaser, which runs in the browser and on a node.js server. The server is authoritative, every 50ms or so it sends the game state object to all clients. The clients receive the state and update all instances accordingly. The game runs at 60fps, and the physics and AI are the same on clients on server, so if there is no user interaction the game will evolve exactly the same (the next frame on the server will be equal to the next one on the client). This should make sync much easier, but I have a problem When the client receives the state from the server, the state is no longer up to date (as there is the latency between server and client). Here is a drawing Server State1 State2 State3 State4 State5 ................................................ V Client State1 State2 State3 State4 State5State3 So, when the client receives State3, it is no longer usable as it has already been at State3. This makes the game always rewind a few frames when it receives the update from the server. How can I solve this, taking in account that the same game engine runs on both client and server (so prediction is much easier). I would try "rendering the game in the past" as I have seen in other cases, but I do not really think I can break Phaser physics render loop connection.


Moving a div with hotkeys using easing in and out I'm working on replicating Tagpro using AngularJS and Firebase as a learning project. I want this ball to move using ease in and out like in the youtube video below. My code http codepen.io clouddueling pen vCpuf http tagpro.koalabeast.com https www.youtube.com watch?v cyAeDTmG8GI At least my method goes in the right direction but is super glitchy. Does anyone have an example of the algorithm that makes this happen? Code sample? Here is a weird graph of the movement I'm trying to achieve Sorry if this is a duplicate I came from stackoverflow.


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?


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?


Adapting tilemap algorithm to support isometric tilemap I'm using Phaser to build an isometric game. The framework doesn't have support for isometric tilemaps yet, so I'm starting to write a PR for it to support. What I currently have, loading an isometric tilemap on the current Phaser.Tilemap object, is this As you can see, the tiles are wrongly positioned because of the simple 2D tile positioning approach the framework currently uses. The class that actually makes the parsing of the JSON map and converts it into a tilemap is Phaser.TilemapParser, specifically at line 185. What I need is some help on where to start adapting this parser or any other part of the code in order for it to support isometric tilemaps. I don't know exactly where to start extending this parser or even writing a new parser just for isometric tilemaps. Also, I know the calculations are different for positioning isometric tiles, and I want to know too where that change should go here, as I didn't find that either.


How can I scale zoom to a point in canvas in the game? I am using html5 canvas to build a MMO game. When I scale my background by default it scales to (0, 0) which is the top left corner of the background. If I have other sprites on the screen they all will look like they are shifting to the bottom right a little bit. Suppose my sprite(player) is at (x,y) of the map and it is placed center on the canvas.How can I make the background scale or zoom to (x,y) instead of (0,0)? Its world position is (x,y) but its screen position is always (canvas.width 2, canvas.height 2). I think in this way the sprites around my player wouldn't shift their position to unexpected places. But I don't know how to do this.


How can I get a 4x4 matrix from a bullet quaternion? I'm trying to make a game using JavaScript with Ammo.js ( an implementation of bullet ) and Sylvester to do my matrix maths. The problem is I don't know how to turn the WXYZ that bullet gives into the 4x4 matrix Sylvester needs. If there is a way to just get Bullet Physics to give me the 4x4 matrix please tell me! I am completely lost here.


Buffer System For Items I am going to reference this image of what I want to accomplish in JavaScript. This is the Diablo buffer system. This question may be a bit advanced (or possibly not even allowed). But I was wondering how you might go about implementing this type of system in a JavaScript game. Currently to implement such a system in JavaScript escapes me, and I am turning to SO to get some suggestions, ideas, and hopefully some insight in how I could accomplish this without being to costly on the CPU. Some thoughts of mine for implementing such a system would be to Create DIVS within a DIV that hold each position of the inventory Go through each item you own in a container and see which DIV it belongs to Make said item images the DIVs image This type of system might possibly work if ALL items were 1x1, but for this example its not going to work out. I am at a complete lost of ideas how to even accomplish this. Although, maybe rendering directly to the canvas and checking mouse cords could work, there would more than likely be A HUGE annoyance when checking if other items are overlapping each other (meaning you cant place the item down, and possibly switching item with the cursor item ). That said, what am I left with? Do I need to makeshift my own hack system with messy code, or is there some source out there (that I don't know about) that has replicated this type of system in their own game. I would be very grateful to get some replies on how you might go about doing this, and will accept answers that can logically explain how you might implement such a system (code is not required). P.S. Id like to use pure JavaScript, and nothing else (even though it might be "reinventing the wheel", I also like to learn).


How can I ensure reasonably spaced out enemies I have a simple javascript game and I'm initializing their positions on the y axis using random numbers. How can I ensure that they are reasonably spaced apart? My simple algorithm is y (Math.random() 1000 600) However I frequently get enemies almost directly on top of each other. This is a huge problem for the game, since it's a word game and the enemies have text on their center, that if overlapped makes them impossible to kill since you can't see the words. Any advice would be appreciated! I'm pretty new to making games in general so this has all been a learning experience for me!


Javascript Audio solution still has issues. Flash works but... requires flash (an issue for iOS). What do you use in Javascript for audio?


Get points on a line between two points I'm making a simple space game in JavaScript, but now I've hit a wall regarding vectors. The game view is top down on a 2d grid. When the user clicks on the grid, the space ship will fly to that spot. So, if I have two sets of points x 100.2, y 100.6 the ship x 20.5, y 55.95 the clicked coordinates If the game loop ticks at 60 iterations per second, and the desired ship velocity is 0.05 points per tick (3 points per second), how do I calculate the new set of coordinates for the ship for each tick of the game loop? p.s. I do not want to account for inertia, or multiple vectors affecting the ship, I just want the ship to stop whatever it is doing (i.e. flying one way) and move to the clicked coordinates at a static speed.


Click on an isometric plane and obtain normal coordinates I have photos distributed as cells. When I click, I get the corresponding row and column. console.log("Col " X "Row " Y) When applying an isometric view conversion like this ctx.translate(0, 300) ctx.scale(1, 0.5) ctx.rotate( 45 Math.PI 180) I do not know what mathematical formula applies to get the coordinates correctly. Based on feedback so far, I've been able to get this far. The x coordinate seems to work fine, but the y coordinate not. Isometrico() function Isometrico() ctx.translate(0, 300) ctx.scale(1, 0.5) var radianes 45 Math.PI 180 ctx.rotate(radianes) document.addEventListener("mousedown", function(e) CorIsometrico( e.offsetX, e.offsetY) ) function CorIsometrico(xI,yI) RESPUESTA yI yI 300 yI yI 2 xI xI Math.cos(45) yI Math.sin(45) I yI Math.sin(45) yI Math.cos(45) console.log("Coor Isometricas " xI " " yI) Edit Each cell is 50x50. Having 10 columns and 50 rows, the information of each cell would look like this 1 50 50 2 100 50 3 150 50 ... 49 450 250 50 500 250 Maximum Y value 250. xI xI Math.cos(45 180 Math.PI) yI Math.sin(45 180 Math.PI) yI yI Math.sin(45 180 Math.PI) yI Math.cos(45 180 Math.PI) yI yI 2 yI yI 300 Click in X 1 Y 1 138.5929291125633 531.5575746753798 Click in X 1 Y 5 198.69700551341987 90.3229432149742 Y exceeds the maximum value. Edit2 var xI2 xIMath.cos(45 180 Math.PI) yIMath.sin(45 180 Math.PI) var yI2 xIMath.sin(45 180 Math.PI) yIMath.cos(45 180 Math.PI) yI2 yI 2 yI2 yI 300 xI2 xI2 150 console.log("Coor Isometricas " xI2 " " yI2 ) x coor 100 to 400 px if x 150 y coor 0 to 155. Been thinking that the problem is not necessary on isometry. What I'm looking for can be simplified to get the coordinates of a 2d plane by having it rotated X degrees


How can I tweak this A search pathfinding algorithm to handle different terrain movement values? I'm creating a 2D map based action game with similar interaction design as Diablo II. In other words, the player clicks around a map to move their player. I just finished player movement and am moving on to pathfinding. In the game, enemies should charge the player's character. There are also five different terrain types that give different movement bonuses. I want the AI to take advantage of these terrain bonuses as they try to reach the player. I was told to check out the A search algorithm (http en.wikipedia.org wiki A search algorithm). I'm doing this game in HTML5 and JavaScript, and found a version in JavaScript http www.briangrinstead.com blog astar search algorithm in javascript I'm trying to figure out how to tweak it though. Below are my ideas about what I need to change. What else do I need to worry about? When I create a graph, I will need to initialize the 2D array I pass in passed on with a traversal of a map that corresponds to the different terrain types. in graph.js "GraphNodeType" definition needs to be modified to handle the 5 terrain types. There will be no walls. in astar.js The g and h scoring will need to be modified. How should I do this? in astar.js isWall() should probably be removed. My game doesn't have walls. in astar.js I'm not sure what this is. I think it indicates a node that isn't valid to be processed. When would this happen, though? At a high level, how do I change this algorithm from "oh, is there a wall there?" to "will this terrain get me to the player faster than the terrain around me?" Because of time, I'm also debating reusing my Bresenham algorithm for the enemies. Unfortunately, the different terrain movement bonuses won't be used by the AI, which will make the game suck. I'd really like to have this in for the prototype, but I'm not a developer by trade nor am I a computer scientist. D If you know of any code that does what I'm looking for, please share! Sanity check tips for this are also appreciated.


In regards to real time turn based games, where should the turn handler be? I'm currently developing a pool like browser game. I'm stuck on where should I handle the turn changing, timer, etc. Currently, turn timer (i.e. 15 seconds left to do action, then turn will change) is handled by the server. But the changing of turns itself is handled by the client (the browser itself). Now in my current setup, whenever a player leaves window focus, the game gets out of sync. Should I migrate the turn change handling to the server instead?