confusion in animating a sprite sheet using craftyjs can anyone help me with this http jsfiddle.net B5UsC 15 you can see that the sprite animation is not rendering correctly and i am guessing that i am not using the exact width of the sprite ,i tried to change the width but also didn't work out THE CODE initialize the sprite Crafty.sprite(52,123,"http i.imgur.com bkYVEe5.png", Ryu 0,0 ) initialize the component Crafty.c("RyuAnimation", init function () this.requires("SpriteAnimation,Keyboard") .addComponent("Ryu") .reel('idle', 1000, 0, 0, 9) this.animate('idle', 1) creating the player player Crafty.e("2D,DOM,Canvas,RyuAnimation") .attr( x 15, y ch 123, w 52, h 123 ) .start(3) i am pretty sure the missing element is hidden somewhere in this code Crafty.sprite(52,123,"http i.imgur.com bkYVEe5.png", Ryu 0,0 ) but help me in figure out the real problem behind this confusion because i have no idea why this error in rendering is occurred


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


What should i use as a board for my game? I'm a beginning programmer and i need to make a game. The rough idea revolves around fleets fighting in turn based battles while you control your factions resources and manpower. The original concept was to make a set of routes which the fleet could follow. A graph of location nodes connected by route edges that looks a bit like this I don't know how to make a map and make set locations on it. On that note, i'm making this is html javascript css. This is a school assignment.


Why do I need a local server for HTML5 game development? I'm new to HTML5 game development. I'm trying to make something using Pixi.js, but when I tried to view it in a browser, I saw a blank page. According to the tutorial I'm following, I need to set up a local server. I'm not sure why I'd need to do that, though. Could you please tell me why I would need a local server to run HTML files on my browser?


How is JS source protected in Chrome games? I was playing a space arcade shooter https moonbreakers.com and tried to see some of the JS and shader code. However, I was unable to find anything but some server communication code. Game code is thus probably run on servers, but the shaders should at least be local, right? And I have understood that even if the server runs the true game state, clients commonly do some physics interpolation etc by themselves. My only guess is that the game gets the code with jQuery and it doesn't show in the page source. Can that code be looked at via a debugger?


Glenn Fiedler's fixed timestep with fake threads I've implemented Glenn Fiedler's Fix Your Timestep! quite a few times in single threaded games. Now I'm facing a different situation I'm trying to do this in JavaScript. I know JS is single threaded, but I plan on using requestAnimationFrame for the rendering part. This leaves me with two independent fake threads simulation and rendering. Timing in these threads is independent too dt for simulation and render is not the same. If I'm not mistaken, simulation should be up to Fiedler's while loop end. After the while loop, accumulator lt dt so I'm left with some unspent time (accumulator) in the simulation thread. The problem comes in the draw interpolation phase const double alpha accumulator dt State state currentState alpha previousState ( 1.0 alpha ) render( state ) In my render callback, I have the current timestamp to which I can subtract the last simulated in physics timestamp to have a dt for the current frame. Should I just forget about this dt and draw using the physics thread's accumulator? It seems weird, since, well, I want to interpolate for the unspent time between simulation and render too, right? Of course, I want simulation and rendering to be completely independent, but I can't get around the fact that in Glenn's implementation the renderer produces time and the simulation consumes it in discrete dt sized chunks. A similar question was asked in Semi Fixed timestep ported to javascript but the question doesn't really get to the point, and answers there point to removing physics from the render thread (which is what I'm trying to do) or just keeping physics in the render callback too (which is what I'm trying to avoid.)


How do I make my game (without performance problems) not stutter? I've made a game that has gameticks every 1 60 seconds. These gameticks take very little time to calculate ( lt 0.5 ms). The game is written in Javascript and uses requestAnimationFrame (rAF). rAF fires roughly a few milliseconds (how many is determined by what the browser thinks is necessary) before (mostly) every frame output to the monitor. The code does the following every rAF get a timestamp figure out how many gameticks should have happened at that timestamp, and (if needed) run enough to catch up render state after latest gametick to screen This works fine most of the time. It runs at a consistent 60 gameticks second, regardless of what the screen is doing (good for syncing multiplayer). It handles any framerate. The game looks smooth except, sometimes, the timestamps happen to be right around the boundary for new gameticks. frame 10 gametick 2.01 (renders gametick 2) frame 11 gametick 2.99 (renders gametick 2) frame 12 gametick 4.01 (renders gametick 4) frame 13 gametick 4.99 (renders gametick 4) frame 14 gametick 6.01 (renders gametick 6) When this happens, it stutters horribly. How do I make it avoid stuttering needlessly?


How can I implement a Boardgame.io project using Webpack? I am following the boardgame.io tutorial, but I do not want to use either of the two implementation options covered in the tutorial (React and Parcel). The tutorial requires a framework or bundling method because the client web application has dependencies on node.js modules which cannot be directly imported into browser scripts.


Should game logic update per second or per frame? I'm trying to wrap my head around how and when to update an entities position. My game loop updates logic at 25 FPS and renders at 50 60 (Depending on the computer hardware). So lets say I'm moving an object from 0 to 75 over a course of 100ms. In my update logic, should I update the position based on a per frame value or a per second value? I was doing the math, and came up with and interesting find. Since the update function updates at a rate of 25 fps, this means that it will be called at 40ms, 80ms and 120ms. And the render function updates faster at a rate of 60 fps (for the sake of argument), which means it will be called at 16, 32, 48, 64, 80, 96, and 112ms So if you line up all of these events on a timeline you'll notice that at the 6th render (96ms) the value of our position would be 72. And on the 7th render, the position would be 75. Then the update function would be called at 120ms and would notice that the value is 75, but the current time is 20ms over what it should be. Now I know that 20ms isn't much, but how do you compensate in collisions, physics, and AI for this? Should I instead update my values per frame instead of per millisecond?


In a browser, is it best to use one huge spritesheet or many (10000) different PNG's? I'm creating a game in jQuery, where I use about 10000 32x32 tiles. Until now, I have been using them all separately (no sprite sheet). An average map uses about 2000 tiles (sometimes re used PNG's but all separate divs) and the performance ranges from stable (Chrome) to a bit laggy (Firefox). Each of these divs are positioned absolutely using CSS. They do not need to be updated every tick, just when a new map is loaded. Would it be better for performance to use spritesheet methods for the divs using CSS background positioning, like gameQuery does? Thank you in advance!


Converting cartesian geo coordinates to isometric (real world map to game map) I need to create an automated method to convert real cartesian, geo coordinate data (such as roads and parks), into isometric coordinates as a game map view for use in HTML5 Canvas. Here is an image of what I mean Example Image Taking into account heavy map distortion in the process to fit they isometric layout. Is this even remotely possible?


Creating smooth lighting transitions using tiles in HTML5 JavaScript game I am trying to implement a lighting effect in an HTML5 JavaScript game using tile replacement. What I have now is kind of working, but the transitions do not look smooth natural enough as the light source moves around. Here's where I am now Right now I have a background map that has a light shadow spectrum PNG tilesheet applied to it going from darkest tile to completely transparent. By default the darkest tile is drawn across the entire level on launch, covering all other layers etc. I am using my predetermined tile sizes (40 x 40px) to calculate the position of each tile and store its x and y coordinates in an array. I am then spawning a transparent 40 x 40px "grid block" entity at each position in the array The engine I'm using (ImpactJS) then allows me to calculate the distance from my light source entity to every instance of this grid block entity. I can then replace the tile underneath each of those grid block tiles with a tile of the appropriate transparency. Currently I'm doing the calculation like this in each instance of the grid block entity that is spawned on the map var dist this.distanceTo( ig.game.player ) var percentage 100 dist 960 if (percentage lt 2) Spawns tile 64 of the shadow spectrum tilesheet at the specified position ig.game.backgroundMaps 2 .setTile( this.pos.x, this.pos.y, 64 ) else if (percentage lt 4) ig.game.backgroundMaps 2 .setTile( this.pos.x, this.pos.y, 63 ) else if (percentage lt 6) ig.game.backgroundMaps 2 .setTile( this.pos.x, this.pos.y, 62 ) etc... The problem is that like I said, this type of calculation does not make the light source look very natural. Tile switching looks too sharp whereas ideally they would fade in and out smoothly using the spectrum tilesheet (I copied the tilesheet from another game that manages to do this, so I know it's not a problem with the tile shades. I'm just not sure how the other game is doing it). I'm thinking that perhaps my method of using percentages to switch out tiles could be replaced with a better more dynamic proximity forumla of some sort that would allow for smoother transitions? Might anyone have any ideas for what I can do to improve the visuals here, or a better way of calculating proximity with the information I'm collecting about each tile? (PS I'm reposting this from Stack Overflow at someone's suggestion, sorry about the duplicate!)


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


How to use Cocos2dJS to connect to a Socket.IO server? How can I connect to a nodejs socket.io server from a cocos2djs game? I've google all the way to no avail. I tried this but it does not work socket io.connect('http 192.168.254.102 7714') if ( socket undefined ) cc.log("Could not connect to socket.io") else socket.on('connect', function() socket.emit('join', username 'Android Application' ) ) I read in the docs that there's a module called SocketIO for doing that, but there's not enough info on how to use it. Thanks in advance.


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


How can I create and animate 2D skeletons for HTML5 Javascript games? I'm trying to make a 2D fighting game in HTML5(somewhat like street fighter). So basically there are two players, one AI and one Human. The players need to have animations for the body movements. Also, there needs to be some collision detection system. I'm using createjs for coding but to design models objects animations, I need some other software. So I'm looking for a software that can easily make custom animation of 2d objects. The objects structure(skeleton etc.) will be same once defined but need to be defined once. Can export the animations and models in a js readable format(preferably json) Collision detection can be done easily after the exported format is loaded in a game engine. For point 1, I'm looking for some generic skeleton based animation. Sprite sheet based animations will be difficult for collision detection.


Fastest way to render isometric world with moving entities? I've got an isometric diamond shaped world. The world consists of isometric planes like rooms. The walls and floors of the rooms and all obstacles and items in the rooms are isometric entities. So I have a list with each existing object in the world. Each object has its own coordinates. x, y, and z. x is from top to right bottom, y is from top to left bottom, z is straight up into the air. Each object has also an isometric width and height as property. Now I have to render the world correctly. I'm quite sure the only hard step is to sort each object by its depth, and this isn't that hard when nothing changes in the world. But of course everything changes... I want to figure out a sorting system which is very fast, so it doesn't do too much unnecessary work. I ended up with multiple articles, saying a pigeonhole sort is the way to go. But is this really the right solution? And doesn't this cause rendering glitches? I also read that I should use topological sorting. (https en.wikipedia.org wiki Topological sorting).


Electing a host with WEBRTC This is similar to Host Migration (P2P) with RTMFP and AS3 I have a webRTC chat room, initially used Twilio and switching to skyway, the situation is that I have a bunch of peers with data broadcast and there is a firebase datastore with the game state. I want to elect a host and deal with the host dropping. Currently all the peers just running the same code, so I was thinking I could have the one with the lowest uid propose being the host and then get accepted. How can I make this robust to race conditions?


Cocos2d JS Getting vector reflection I'm working on a small Breakout clone using Cocos2D JS, without the use of a physics engine. One of the things that baffles me was how the ball bounces. My friend came up with this inputVector 2(normalVector inputVector) I have no idea how to translate that in code. So I tried with this g Ball.position this.velocityComputer(cc.p(g Ball.x, g Ball.y), cc.p(this.x, this.y)) velocityComputer function(inVector, thisNVector) var prodVec cc.pDot(inVector, thisNVector) var retVec inVector (2 (prodVec inVector)) cc.log(retVec) cc.log(blockNVec) return retVec , But g Ball doesn't change directions, and retVec simply logs NaN. Any suggestions? Thanks.


Node.js V8 as a Platform for High End Local PC Game Development? As a Web UI dev rapidly expanding into more wide open generalist territory, the more I learn about how its done in other languages, the more I love JS for architectural and basic messaging event driven concerns. For the record I am most certainly not a full blown game dev (although I did once write for a major gaming mag which is like saying I pretended to be friends with game devs on TV, although you guys were always my favorite folks to talk to). Anyway, since it's fairly easy to bind C and C to JavaScript via Node (or perhaps more specifically V8), how reasonable would it be to assume you could write a decent 3D engine that exposed outcomes of things like collision calculations as events to the JS with the intention of getting the dynamic first class function party language benefits (assuming you see such things as benefits I do) to higher level architecture and AI logic concerns without a crippling loss in performance? Node, as I understand it, basically exposes a C event loop to JavaScript handled by V8. The JS is single threaded, meaning any attempt to do anything calculation IO intensive with the JS would be foolish, but you get the advantage of not really having to sweat threads, queuing etc... since you're ideally never trying to muck with the same data at the same time. Most code would of course be heavily event callback driven. All the file I O concerns and other processor intensive stuff is basically C or C under the hood telling you when its done. Not to mention handling UI concerns directly out of the JavaScript via a webkit layer slapped on top of everything. I'd be delighted to hear why you love hate the idea but the core question is is it feasible and why not? And no, I seriously doubt my own ability to do this all by myself, although plugging an existing 3D engine in might not be outside of the realm of possibility but I'd still be learning a lot of new stuff to make that happen I'm sure.


HTML5 as application for tablets? I'm looking at creating a tablet application (iPad, Nexus, Surface...). I've heard it's possible to create it using HTML5 canvas. I was wondering if it was limited to canvas, if div input table can also be used. Can a normal HTML page be used as an application for the Apple, Microsoft, Android store?


Three.js how to rotate sphere without moving light (using OrbitControls)? Okay, I think the problem that I'm having is that when I create my DirectionalLight with three.js, when I then rotate my object with OrbitControls the entire scene is rotating, not just the sphere I have in the middle of it ( the only object I have in my scene ). I want to make it so that I can rotate my sphere with my mouse like OrbitControls does, but not have the camera move. Or have the light not move with the camera? Here's a gif of my scene so far that might better explain my dilemma I want the light to be.. y'know.. more like the sun, coming from one point in space and shining at (0,0,0) in my scene, while still being able to rotate the sphere independently. Am I using OrbitControls wrong here? Here is what I have to get to the point I have in the gif above var width section.offsetWidth, height section.offsetHeight var topOfElement section.getBoundingClientRect().top height var bottomOfElement section.getBoundingClientRect().bottom const scene new THREE.Scene() const camera new THREE.PerspectiveCamera(75, width height, 0.1, 1000) camera.position.z 10 camera.position.x 2.5 const controls new THREE.OrbitControls( camera, renderer.domElement ) controls.enableZoom false controls.maxPolarAngle Math.PI const renderer new THREE.WebGLRenderer( alpha true ) renderer.setClearColor( 0x000000, 0 ) renderer.setSize(width, height) section.appendChild(renderer.domElement) const onEverythingLoaded () gt render() const loadingManager new THREE.LoadingManager(onEverythingLoaded) const loader new THREE.TextureLoader(loadingManager) const earthGeomerty new THREE.SphereGeometry( 5.5, 32, 32 ) const earthDiffuse loader.load('assets drought earth texture.png') const earthSpec loader.load('assets drought earth texture bump.png') const material new THREE.MeshPhongMaterial( specular 0xffffff, map earthDiffuse, specularMap earthSpec, normalScale new THREE.Vector2( 1, 1 ), shininess 30, transparent true, depthTest true, depthWrite false, polygonOffset true, polygonOffsetFactor 4, wireframe false ) const sphere new THREE.Mesh( earthGeomerty, material ) const ambientLight new THREE.AmbientLight( 0x667777 ) const directionalLight new THREE.DirectionalLight( 0xffffdd, 2 ) directionalLight.position.set( 4, 0, 0 ) scene.add( sphere ) scene.add( ambientLight ) scene.add( directionalLight ) const render () gt animationFrame requestAnimationFrame( render ) sphere.rotation.y 0.001 renderer.render( scene, camera ) For further clarification, I want to have my light work like this while still being able to rotate the earth with my mouse like with OrbitControls. But the light doesn't move. Is OrbitControls the wrong tool here? Any documentation helpful links would be appreciated I am so, so lost. (I cross posted this from stackoverflow because I thought maybe the people over here would know more about this, hope that's ok!) Update After much fussing about with the OrbitControls functions I realised that what I'm trying to do isn't what OrbitControls is for, because quot orbiting quot isn't what I'm trying to do I'm trying to rotate the actual sphere with my mouse, which is entirely different. Welp.


How do I make a message based communication system between objects? Just as I was told here, I need to make some kind of communication between objects in my game. Mainly, for achievements. How do I do this? My idea was to make every object have an array attached to itself called "messages", and then, when something happens, a message gets pushed there. At the end, I would have a big loop, where I would check messages that each object got, remove them, and act accordingly. I could also have a global array called "messages", and then I would iterate through it, and fire off events in different objects that the messages were sent to (in this case, a message would contain both a message, and some kind of an object ID), and then remove them. Is there a better way? Keep in mind that I'm working in Javascript. I forgot to mention, we're talking about serverside Javascript running on Node.js, not in a browser.


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)


Calculate travel time on road map with semaphores I have a road map with intersections. At intersections there are semaphores. For each semaphore I generate a red light time and green light time which are represented with syntax R T1, G T2 , for example 119 185 250 A B R 6, G 4 C R 5, G 5 D I want to calculate a car travel time from A D. Now I do this with this pseudo code function get travel time(semaphores configuration) time 0 for( i 1 i lt path.length i ) prev node path i 1 next node path i ) cost cost between(prev node, next node) time (cost movement speed) movement speed 50px per second light times get light times(path i , semaphore configurations) lights cycle get lights cycle(light times) Eg R,R,R,G,G,G,G , where R 3, G 4 lights sum light times.green time light times.red light Lights cycle time light lights cycle cost lights sum if( light "R" ) time light times.red light return time So for distance 119 between A and B travel time is, 119 50 2.38s ( exactly mesaured time is between 2.5s and 2.6s), then we add time if we came at a red light when at B. If we came at a red light is calculated with lines lights cycle get lights cycle(light times) Eg R,R,R,G,G,G,G , where R 3, G 4 lights sum light times.green time light times.red light light lights cycle cost lights sum if( light "R" ) time light times.red light This pseudo code doesn't calculate exactly the same times as they are mesaured, but the calculations are very close to them. Any idea how I would calculate this?


Mouse input and structure in JS I am creating a simple concept where I have a small menu to choose a tool from and then I can click and drag to build. For example, I click on the rails tool and then I can click and move the mouse to create a rail segment. I'm coding it something like this(missing some variables for temp values and objects) var toolSelected false if I click the rails button, it changes to 'rails' renderer.domElement.addEventListener('mousedown', function(event) here I check which is the tool selected if(toolSelected 'rails') create rail object starting in event coordinates ) renderer.domElement.addEventListener('mousemove', function(event) here I check which is the tool selected if(toolSelected 'rails') pass the mouse movement to the rail object to update end coordinates position so I can drag and see the potential rail ) renderer.domElement.addEventListener('mouseup', function(event) here I check which is the tool selected if(toolSelected 'rails') indicate that the rail should be finished and build it with the mouse up coordinates ) The question is, is there a better or recommended way to structure these mouse events? Or do I have to, under each mouse event, check which tool is selected and perform the appropriate actions?


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.


What Javascript game engines are out there, other than Impact? Does anybody know of a decent (meaning preferably free )) alternative to Impact? Any suggestions are very much appreciated!


How do I make my game (without performance problems) not stutter? I've made a game that has gameticks every 1 60 seconds. These gameticks take very little time to calculate ( lt 0.5 ms). The game is written in Javascript and uses requestAnimationFrame (rAF). rAF fires roughly a few milliseconds (how many is determined by what the browser thinks is necessary) before (mostly) every frame output to the monitor. The code does the following every rAF get a timestamp figure out how many gameticks should have happened at that timestamp, and (if needed) run enough to catch up render state after latest gametick to screen This works fine most of the time. It runs at a consistent 60 gameticks second, regardless of what the screen is doing (good for syncing multiplayer). It handles any framerate. The game looks smooth except, sometimes, the timestamps happen to be right around the boundary for new gameticks. frame 10 gametick 2.01 (renders gametick 2) frame 11 gametick 2.99 (renders gametick 2) frame 12 gametick 4.01 (renders gametick 4) frame 13 gametick 4.99 (renders gametick 4) frame 14 gametick 6.01 (renders gametick 6) When this happens, it stutters horribly. How do I make it avoid stuttering needlessly?


Canvas tile grid, hover effects, single tilesheet, etc I'm currently in the process of building both the client and server side of an HTML5, canvas, and WebSocket game. This is what I have thus far for the client http jsfiddle.net dDmTf 20 Current obstacles The hover effect has no idea what to put back after the mouse leaves. Currently it's just drawing a "void" tile, but I can't figure out how to redraw a single tile without redrawing the whole map. How would I go about storing multiple layers within the map variable? I was considering just using a multi dimensional array for each layer (similar to what you see as the current array), and just iterating through it, but is that really an efficient way of doing it? Currently the "borders" encroach on one another. I'm not sure what I'm doing wrong? If you hover over and off of the bordering "tree" tiles, you'll notice how it removes part of the neighboring tiles border. This shouldn't need to happen. Outside of the map, what would be an elegant way of adding Players to the render scene? I've seen a few places that recommend you use multiple canvas's, would you recommend that since they'll probably be moving much more? In addition to that, how can I confine player movement to the grid, similar to how in the pokemon gameboy games, when you tap the left arrow, you always move one "space" that direction. It's not a halfway type deal. Camera. What would be a good way about adding a "camera" to the equation, so the viewport can pan around a larger map area? Obstacles. In the newer version of the map, you'll notice an empty obstacles array. Assuming players get added well, what do you think would be good for adding movement obstacles? Side note The tile sheet being used for the jsfiddle display is only for development. I'll be replacing it as things progress in the engine. If you guys have any pointers for my JavaScript, feel free. As I'm more or less learning advanced usage as I go, I'm sure I'm doing plenty of things wrong. Note I will continue to update this post as the engine improves, but updating the jsfiddle link and updating the obstacles list by striking things that have been solved, or adding additions. Edit Updated link from http jsfiddle.net dDmTf 7 to http jsfiddle.net dDmTf 17 this handles the "hover" problem, and it's been striked out. Edit Updated link from http jsfiddle.net dDmTf 17 to http jsfiddle.net dDmTf 19 fixes the out of bounds issue with the tiles Edit Updated link from http jsfiddle.net dDmTf 19 to http jsfiddle.net dDmTf 20 adds multiple layers to the equation


How to avoid cost comparison each and every frame? I'm toying around with a ticker(incremental game) for JavaScript. The basic idea is that you have buttons that represent buildings, each building provides a certain amount of resource per 'tick'. Each building can cost an arbitrary amount of resource types and amounts (a farm can cost wood, food and labor for example). The game is intended to have several dozens of buildings, units, technologies etc. I would like to disable the buttons of buildings that you can't currently afford. My concern I prefer not to loop over every item and every cost within it to see if we have enough to build it every single tick (a tick is 50ms ). Is there a 'smart' way that I missed that solves this issue without brute force? EDIT I decided to approve the answer that basically says "Just ignore the problem". The reasoning behind it is as follows Tests indicated that while the theoretical problem is interesting, it's of little consequence in a reality, the performance hit is extremely minimal. This website is about solving problems, and as "sam hocevar" suggested, The answer needs to be as clear as possible(and the reason behind it). While the answers are clever and very interesting to read as a theoretical background , they all address the "number of checks", while some answers reduce that number by some fraction, non actually mitigate the amount by any performance altering number. Following on 3, It seems that if you've come to a point where you need to implement any of the suggested, over engineered, solutions to save performance, It seems that the gain from those solutions will be so minimal that performance will still be an issue even after implementation, making the entire game model not viable anyway. TL DR If it doesn't work by ignoring the problem, it probably won't work with over tweaking it either.


Where is the Aves game engine? The Aves game engine made a splash last spring summer, with very impressive demo videos. I went back to check on them, and it looks like their site has long since died. Google also doesn't seem to know anything new about them. Where can I find news about Aves? Is the project dead?


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


Are there any alternative JS ports of Box2D? I have been thinking about creating a top down 2D car game for HTML5. For my first game I wrote the physics and collisions my self but for this one I would like to use some ready made library. I found out Box2D and its JS port. http box2d js.sourceforge.net It seems to be quite old port, made in 2008. Is it lacking many features of current Box2D or does it have major issues with it? And are there any alternatives for it?


Optimize field of vision algorithm in a grid tiled map I am trying to implement Field of View algorithm in my game and I followed the great tutorial here sight and light and here is what I got so far As you can see it works fine for me ) And then I try to use this algorithm in a tiled map. It also works fine but just a little bit slow so I am now trying to find a way to optimize the algorithm. Some information might help to optimize The tiled map is Orthogonal All the tiles have the same size 32 32 and are square Tiles marked 0 means empty marked as 1 means a obstacle I have used Connected Component Labelling algorithm for a preprocess All the obstacles have been merged into several regions I know all the vertices position in each regions Something like this Say I have 9 connected regions ( 9 polygons ) and 40 vertices in total. Based on the algorithm in the above link, there will be ray cast 40 3 ( 3 ray cast per vertices in angle 0.00001) edges 40 edge ray cast intersection test 40 40 3 4800 I think there should be a way to reduce the ray cast count and the edges count that I need to do the intersection calculation in a above situation but just could not figure out a good solution. Any suggestion will be appreciated, thanks )


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


How do I add a PIXI container into a Phaser Game? How do I add a PIXI container into a Phaser Game? I have a game made ONLY with PIXI. but now i would like to port it to a Phaser. All my game content happens inside a pixi container "screenContainer". I tried to add a pixi container like this. var created function() screenContainer new PIXI.DisplayObjectContainer() var sprite m.game.add.existing(screenContainer) var.game new Phaser.Game(gameWidth, gameHeight, Phaser.AUTO, "divId", create created ) but it stops here "phaser.js" line 33067 The core update as called by World. method Phaser.Group update protected Phaser.Group.prototype.update function () var i this.children.length while (i ) this.children i .update() UPDATE IS UNDEFINED because Pixi.Container, does not have "update" method. Is there any other way to add a pixi container inside a phaser game?


making Circle button in phaser im trying to make a circle button with tap event i used hitArea property from sprite class and using pixi Circle class i did that this.sprite game.add.sprite(50,50,"cursors") this.sprite.anchor.set(0.5,0.5) this.sprite.hitArea new PIXI.Circle(50,50,84) this.sprite.inputEnabled true this.sprite.events.onInputDown.add(function() console.log("clicked") ) it is not working at all so i tried removing this.sprite.anchor.set(0.5,0.5) input is work fine when there is no hit Area so what should i do note phaser version is 2.2.2


How do I store game data with cookies? Im working on a game right now, but I was wondering how I would store the game data in cookies(in javascript) where you can load it up, and resume the last spot you were at. I was looking at some other websites like w3schools, but I didn't really understand it


Randomised Path from A to B for cursor movement simulation I'm trying to simulate the movement of the mousecursor, by creating a path from point A to B that has random variation. The algorithm I'm using at the moment is very basic, and is limited in that it's only really good for creating a path where X and Y distance from the start are the same, forming a square The code looks something like this function calcualtePath(from, to) var pathNodes while (from.x ! to.x from.y ! to.y) var newTransition x from.x, y from.y if (Rand(1, 3) ! 1 amp amp newTransition.x gt to.x) newTransition.x else if (Rand(1, 3) ! 1 amp amp newTransition.x lt to.x) newTransition.x if (Rand(1, 3) ! 1 amp amp newTransition.y gt to.y) newTransition.y else if (Rand(1, 3) ! 1 amp amp newTransition.y lt to.y) newTransition.y pathNodes.push(newTransition) from newTransition return pathNodes I'd like some assistance in creating is a relatively fast algorithm that creates a randomised path between point A and B, that has a more curve like path and isn't limited like the one above. Ideally something a bit like this, with a pronounced curve


Algorithms for positioning rectangles evenly spaced with unknown connecting lines I'm new to game development, but I'm trying to figure out a good algorithm for positioning rectangles (of any width and height) in a given surface area, and connecting them with any variation of lines. Two rectangles will never have more than one line connecting them. Where would I begin working on a problem like this? This is only a 2 dimensional surface. I read about graph theory, and it seems like this is a close representation of that. The rectangles would be considered a node, and the lines connecting them would be considered an edge in graph theory.


How to protect source code when game is developed in HTML5 Javascript Possible Duplicate How do you prevent your JavaScript HTML5 web game from being copied or altered? If a game client is developed in Javascript, the source code can be found in browser. It's dangerous, because it's easy to hack the game, and patent can't be protected. Are there any good ways to avoid this, e.g Javascript can be compiled to binary file then browser load and run the compiled javascript?


TypeScript Space Shooter movement I'm trying to create a simple space shooter game using typescript and i've got kind of stuck at checking the movement.The thing is that if i only press one key it works fine but if i press 2 keys at the same time it won't check for collisions with margins.Do i have to check for every case if i press multiple buttons or there's another way to do it? Here's the code update(canvas) if (Game.keysPressed KeyBindings.LEFT ) this.xVel 1 if (this.x lt 20) this.xVel 0 else if (Game.keysPressed KeyBindings.RIGHT ) this.xVel 1 if (this.x this.width gt canvas.width 20) this.xVel 0 else if (Game.keysPressed KeyBindings.UP ) this.yVel 1 if (this.y this.height lt 500) this.yVel 0 else if (Game.keysPressed KeyBindings.DOWN ) this.yVel 1 if (this.y this.height gt 880) this.yVel 0 else this.xVel 0 this.yVel 0 this.x this.xVel this.speed this.y this.yVel this.speed Thanks for helping!


2d animation on html5 canvas using a vector and speed Im moving a starship from one location to the other. In creating a vector, normalize and magnitude it. Lets assume my vector looks like this Vector x 156, y 90, m 180.0000000546, nx 0.8661855860486004, ny 0.49972245348957717, The way im animating the ships movement currently is if (! action.animated) if (action.type "move") if (game.ships i .actions j .v.m gt 0) v is the Vector above ! game.ships i .x action.v.nx game.ships i .y action.v.ny game.ships i .actions j .v.m else game.ships i .actions j .animated true So basicly, im using requestanimationframe and a loop to move the starship by what equals 1 magnitude 1 unit length (px) per frame. So far it is working (but for the fact that the vessel animates one more magnitude than it should). However, assuming i have two starships and one has a vector magnitude of 180 while the other has a magnitude of 200 and im animating both at the same time, how can i create an animation that will move the faster starships quicker, i.e. both starships should begin moving and end moving in the same frame ?


Perlin noise terrain issue when scrolling I am generating a terrain in Javascript canvas using this js project for the Perlin noise. I have an array of points, and when one point leaves the left hand side of the window, it is removed, and a new point is added to the right. For the first few points (before any point moves out of the LHS of the window), it works fine, but once I start removing points from the start of the array and adding them to the end the Perlin stops working. JSFiddle Does anyone know why this would happen?


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.


Why is my spritesheet displaying all messed up in game? I'm having an issue I don't quite understand, where my spritesheet is looping strangely and not showing the full sprite I want, even though I feel like I'm specifying it correctly. My code is in phaser.js. Example https imgur.com a xJ95Qbj My code for it is as follows this.load.spritesheet('dude', 'assets bunny.png', frameWidth 32 , frameHeight 42 ) this.anims.create( key 'left', frames this.anims.generateFrameNumbers('dude', start 56, end 64 ), frameRate 5, repeat 1 ) this.anims.create( key 'turn', frames key 'dude', frame 4 , frameRate 20 ) this.anims.create( key 'right', frames this.anims.generateFrameNumbers('dude', start 40, end 48 ), frameRate 5, repeat 1 ) Look fine on the 'turn' frame, but not so fine on movement. For reference, here's the spritesheet I'm attempting to use https imgur.com Rzi5i7Z


Stop music in crafty.js How do I stop a looping music file from playing in crafty.js? I want the music to stop playing once a gameover condition has been reached.


jquery ondrag map load only what has not been viewed When a person mouse down, moves the mouse, and mouses up the system gets the different in the mouse down coord and the mouse up coords and loads in the new map items. However, the problem is it loads them every time so I want a way to track what has been loaded without too much work on checking or storing checks. Most promising. Came up with while typing this. Section the screen into 250x250 sectors and check if that sector has been loaded. Keep track of each corner of the screen and see if there is an area of those that have not loaded. Keep a record of the corners of the screen. When mouse up coords are greater then load the different. Problem is if they are at coord 10,000 then it will load from 10k to 10k positive and that is a lot of items to load. Check every item on the page to see if it is loaded. If I do this I might as well reload the whole page. If anyone has some suggestions feel free to pass them on.


Implementations for storing entities in an ECS system I'm restructuring my model of entities, components and systems, where entities are const createEntity (name, components) gt ( id genUniqueId(), name name, components components ) And I came across a question, and would like to hear someone's experience about it. The question is what are the advantages and disadvantages of each of the following implementation approaches 1 Implement all entities in a single global object, and traverse this object by applying the systems in each entity, example const entities for(let key in entities) for(let system of systems) system(entities key ) 2 Create several global variables for each group that the systems serve, example const players const monsters const clouds for(let key in players) systems 'input' (players key ) for(let key in monsters) systems 'simpleAI' (monsters key ) for(let key in clouds) systems 'wind' (clouds key ) 3 Create local variables within the systems to store the entities, and functions for each system to add and remove entities from their internal objects, example const windSystem () gt const clouds for(let key in clouds) ... const addEntityInWindSystem () gt ... const delEntityInWindSystem () gt ... My intention with the question is just to look for other solutions or even understandings about the cons and advantages that each implementation can bring me during development.


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


How do I make the background color fade into a different color after hovering it? I was trying to make the starter inputs for my text rpg change the background color in a fade effect with JQuery, but I cant figure out what i did wrong. Heres the part im focusing on lt script gt (document).ready(function() Intro Inputs (' Header Intro input') Intro Inputs.hover(function() (this).animate( 'background color' ' 2E8AE5' , 'slow') ) ) lt script gt If anyone could help me out with the mistake i made i would greatly appreciate it! (The problem was that it wouldnt fade the colors in)


UV Texture coordinates out of 0,1 (WebGL) I'm creating a 3D game with WebGL and i'm using Wavefront Objects as a base model format. I recently found some models, their texture coordinates of which are out of the typical 0,1 range and i really don't know how to handle them (in code). I know of course this is a known issue, texture coordinates can be outside of 0,1 and the solution is to use GL REPEAT wrap mode. But this is no solution to me since i have a lot of non powered by 2 textures and i need to use CLAMP TO EDGE wrap mode (the solution to non pow 2 textures). I tried to bypass this issue by coding, so to convert 0 ,1 ranges into 0,1 but with not much of success (although somewhat). Here's what i did I looped "vt" entries (from my parser) and the cases i'm checking are these (pseudo) U,V texture coordinates as they come from file if (U lt 0) U U Math.abs( Math.floor(U) ) if (U gt 1) U U Math.floor(U) if (V gt 0) V Math.ceil(V) V if (V lt 0) V Math.abs( Math.floor(V) V ) The above fragment will take a U,V of unknown range and will convert it into 0,1 , taking also care the WebGL texture coordination system (0,0 buttom left for WebGL but 0,1 for Wavefront, the 3rd case above) The numbers are calculated correctly but the result is not the expected and i'm afraid there is a misunderstanding by my side on how the GL REPEAT mode works. So my question(s) Can this be solved by code, so i can use CLAMP TO EDGE? In case there's no way, is there any program than can take a model of REPEAT ed coordinates and produce one in 0,1 range? I'm already using Blender but could not find a setting for this in exporter.


How to prevent (most) cheating (server side) in my JavaScript, Node JS, socket.io MORPG? I'm working on a fairly simple JavaScript Node JS socket.io (M)MORPG where multiple people play in the same world. This is actually working, but cheating is insanely easy at the moment. My goal is not to stop people from cheating client side, I know this is impossible. My goal is to have the server know when someone is cheating and do something about it. What I really want to know is how well a Node JS server would be able to handle the constant anti cheat checking. People can just adjust the client side JS code and the server currently doesn't do too much checking. So a player could just change his X amp Y coordinate and teleport around the map at will. It would be fairly simple to implement basic checks that don't allow crazy cheats. But I'd like a real way to prevent this. One possibility is to keep track of all player data on the server and make sure nothing weird is happening client side by constantly comparing the data the server has. My issue with this is that I have a lot of collision checking and my world will become rather big. I'm not sure how good of an idea it is to do all of this collision checking server side as well. Sure it would work for one or two players, but what about 10? 50? 200? Especially with all of these players bouncing off walls, shooting bullets, hitting monsters, getting hit by monsters, colliding with monsters, ... As far as I know, the only way to actually prevent cheating is by making the server check all movement and wall bullet monster collisions. Are there any other options? Like using an anti cheat engine of some sort? I know games like MapleStory have that, but I have no idea how they work or how affordable that would be? Or will doing all the collision checks server side be fine? At some point, like around 50 100 players, I could set up a second server instance to limit the amount of players on each server. Ofcourse I would also only check collisions near the player, so not map wide for each player. Any help advice on this is appreciated. Here's a link to my game that will make my questions less abstract. It's far from finished and the world is still very small, but it should give a good idea of what I'm asking http 185.115.218.199 3000


How to use local storage So I have this game and I would like to have a save function. Here is my code below function SaveData() localStorage.setItem('save', score) localStorage.setItem('save', btoa(JSON.stringify(score))) function LoadData() score window.localStorage.getItem('save') document.getElementById('demo').innerHTML score window.onload function() LoadData() When it loads it does not use the storage or it says Not a Number (NaN)


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)


Image won't scale after click Despite being a long time developer I've never played with JavaScript libraries or any sort of graphics development. With my son we're trying to create something interesting and are using createjs easeljs as our vehicle of choice. That said, we are going through a number of tutorials and can't determine why this isn't working. The ball image does display but the on click method code does not cause the image to scale. The onBallClick method is being called so we suspect the reference is simply wrong somehow. var preload new createjs.LoadQueue() var stage new createjs.Stage("demoCanvas") function loadImage() preload.addEventListener("fileload", handleFileComplete) preload.loadFile( id "ball", src "assets ball.png" ) function handleFileComplete(event) document.body.appendChild(event.result) event.result.addEventListener("click", onBallClick) function onBallClick(event) var ballImage preload.getResult("ball") var bitmap new createjs.Bitmap(ballImage) bitmap.scaleX 0.5 stage.update() There are no errors in the developer console so we're trying to determine what is the correct reference to the bitmap. We tried to do createjs.Bitmap(event.result) in handleFileComplete but event.result has a type of Node so we're not sure what to do with that but it doesn't appear useful for purposes of the createjs.Bitmap() statement.


Object is moving more than it should I have the following code for Food exports.Food function(x, y) this.MOVE X FROM POSITION 10 this.ACCELERATION 0.05 this.image this.firstX x this.firstY y this.x x this.y y this.width 10 this.height 10 this.velocity x 0, y 0 this.acceleration x this.ACCELERATION, y 0 this.render function(ctx) if (typeof this.image ! undefined) ctx.drawImage(this.image, this.x this.width 2, this.y this.height 2) return this this.update function() this.velocity.x this.acceleration.x this.velocity.y this.acceleration.y this.x this.velocity.x this.y this.velocity.y if (this.x gt this.firstX this.MOVE X FROM POSITION) this.acceleration.x this.ACCELERATION else if (this.x lt this.firstX this.MOVE X FROM POSITION) this.acceleration.x this.ACCELERATION ... and so on I want the food to move 10 steps from it's first location one side and 10 steps the other side. The problem is that if the script is running longer it becomes to move far more than 10 steps from it's original position. PS update function is called in the loop every 30 times per second Where could be the problem? Thank You in advance EDIT Here is actually a demonstration of my problem https jsfiddle.net 02jbmxnw 1


Select Neighboring X or Y Tiles I have a randomly generated set of tiles, and I am trying to select neighboring x or y tiles to perform functions on them based on if they are a certain value of tile, like so var IsometricMap new Object() IsometricMap.tiles "images dirt.png", "images dirtHigh.png", 0 "images grass.png", 1 "images water.png", 2 "images waterBeachCornerEast.png", 3 "images waterBeachCornerNorth.png", 4 "images waterBeachCornerSouth.png", 5 "images waterBeachCornerWest.png", 6 "images waterBeachEast.png", 7 "images waterBeachNorth.png", 8 "images waterBeachSouth.png", 9 "images waterBeachWest.png" var blockcount 10 let generate row gt Array(blockcount).fill().map( gt Math.floor(Math.random() 3)) IsometricMap.map Array(blockcount).fill().map(generate row) console.log(IsometricMap.map) for(let x 0 x lt IsometricMap.map.length x ) for(let y 0 y lt IsometricMap.map.length y ) if ((IsometricMap.map x 1 y ) 2) IF THE TILE IS WATER, DO ALL THIS alert("SUCCESSFULLY SELECTED THE " IsometricMap.map x 1 y " TILE") DONE WITH WATER TILES So far this is not yielding any results, its as if it cant find the tile I am trying to specify. Is there something wrong with my scope here?


Phaser 3 How to trigger an event every 1 second? I have just started learning Phaser 3 and making a simple idle game, where you would gain x resources per second. What is the best recommended way to do something like this? The two main ways I have found so far are delayedCall this.time.delayedCall(1000, onEvent, null, this) addEvent this.time.addEvent( delay 1000, callback onEvent, callbackScope this ) But I read that Phaser update rendering is in lockstep and runs at 60fps. So if the game were to drop in FPS, then other things like movement, physics etc. would slow down, but would the timers still fire every second? ie you could end up gaining more resources then you should have as the game is running. Would it not be better to do a modulus 60 frame count, and invoke any per second logic in that manner?


Why does my value increase a ton when the tab switches from inactive to active? I basically have a lerp function similar to this one Client interpolation for 100 serverside game when a new server update is received, the update frequency is added to a variable (msAhead) and the delta is subtracted from it every client frame. But when I do it the variable msAhead increases a lot when the tab is switches from inactive to active. Here is my code msAhead updateFrequency when new update is received. (function loop(now) var now Date.now() delta now Time Time now msAhead delta console.log(msAhead) requestAnimationFrame(loop) )(0) How can I fix my issue?


How to add zombie arms to enemies in HTML canvas I'm making a game with HTML canvas (not WEBGL). I have zombies that go to the center of the screen, but for now they are just circles. I want to give them two arms, like the arms players have in surviv.io. I have looked at this question Moving an object in a circular path. I don't know what trigonometry to use to calculate the angle. Here is my code var canvas document.querySelector(' canvas') var context canvas.getContext('2d') function Enemy(x, y) this.x x this.y y this.r 5 this.color hsl( Math.floor(Math.random() 360) ,50 ,50 ) this.vx 0 this.vy 0 this.draw () gt this.x this.vx this.y this.vy context.beginPath() context.fillStyle this.color context.arc(this.x, this.y, this.r, 0, Math.PI 2) context.fill() var enemy new Enemy(0, 0) function loop() requestAnimationFrame(loop) context.fillStyle 'rgba(0,0,0,0.2)' context.fillRect(0, 0, canvas.width, canvas.height) var angle Math.atan2(canvas.height 2 enemy.y, canvas.width 2 enemy.x) enemy.vx Math.cos(angle) enemy.vy Math.sin(angle) enemy.draw() requestAnimationFrame(loop) lt canvas id 'canvas' gt I want the arms facing the center, and I want them to move when the enemy changes direction.


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?


Staggered Isometric Map In Javascript I'm trying to create a staggered isometric map in Javascript. var x, y, row, column, top, left, width window.innerWidth, height window.innerHeight, tile width 64, height 32 row Math.ceil(width tile.width) how many rows will be in map column Math.ceil(height tile.height) how many columns will be in map for (x 0 x lt row x ) for (y 0 y lt column y ) top y tile.height (y 2 0 ? 0 tile.height 2) left x tile.width (y 2 0 ? 0 tile.width 2) (' lt div gt ').addClass('tile').css( width tile.width, height tile.height, top top, left left ).appendTo('body') My formula doesn't work for vertical axis. It creates something like this. http postimage.org image ekfnlbgoh How can I make it work? I need it to be something like this. http legendofmazzeroth.wikidot.com staggered isometric maps Here is the latest code row Math.ceil(height (tile.height 2)) column Math.ceil(width tile.width) for (y 0 y lt row y ) for (x 0 x lt column x ) top y (tile.height 2) (tile.height 2) left x tile.width (y 2 0 ? 0 tile.width 2) (tile.height 2) (' lt div gt ').addClass('tile').css( width tile.width, height tile.height, top top, left left ).appendTo('body') By the way, thanks to you that column row mistake has been fixed.


Need help in getting sequential impulse method working i have made a very very simple physics system based on sequential impulse method with single contacts only and no angular rotation at all. Contact points are calculated using separating axis theorem. Unfortunatly with small gravity my test simulation is stable, but with increasing gravity it gets more and more unstable. My player and my moving elevator just goes crazy... The solver is basically the same as box2d, but without any angular rotation at all so no need for clipped contact points. It does the following Integrating the external forces (gravity, player input) Calculating all contact points using SAT for each unique body pair. Solving movement iteratively by applying impulses so it just touches the surface (restitution is set to zero) Integrating the new velocity to get a new position Re calculate contact distances Solving position errors iteratively by applying impulses to the position by using baumgarte stabilization method All the solver code is nearly a port of box2d Box2D Dynamics b2ContactSolver.cpp. Even the coefficients are set to the same values and the world uses meters as units. Does someone know this stuff and could help me to learn this properly please? Since months i am fighting with this kind of physics programming and has always issues ( Unfortunatly i dont have any algebra knowledge, even though i understand the most of it. Here is the short code in a javascript environment http jsbin.com xoqiquxoyo 1


Optimizing isometric drawing function I need help optimizing my Draw() function to draw only what is visible in the viewport. Currently I'm drawing the whole Map array in a diamond shape. How can I make my function store only what is visible? Here is an image explaining it better Black tiles are X axis, White tiles Y axis. Green tiles are what I would like the function to store, and the Orange rectangle is the viewport. I'll include the relevant part of my code aswell for(i 0 i lt Map.length i ) for (j 0 j lt Map i .length j ) tileX (i j) (tile.width 2) tileX (canvas.width 2 ) (tile.width 2) tileY (i j) (tile.height 2) tileY (canvas.height 2 ) c.drawImage(tile, tileX, tileY) I've been trying to figure out how to solve this, but since I'm no genius I can't. Help appreciated.


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


"Painting" elements in html5 canvas I'm making a game in coffeescript (although for the sake of this problem that's probably not all that relevant) and html5's canvas. It's a game that involves a paint cannon, that fires circular particles of paint that can paint elements of the level and the player. The problem is I'm not sure how to accomplish the painting. The diagram below illustrates what I'm trying to accomplish Using canvas, the particles are drawn using context.arc(), the players using drawRect.arc() and the floor can be an arbitrary polygon with drawing code as follows drawingContext.beginPath() tV b2Math.AddVV(pos, b2Math.MulMV(body.GetTransform().R, vertices 0 )) drawingContext.moveTo(tV.x, tV.y) for i in 1.. vertices.length 1 v b2Math.AddVV(pos, b2Math.MulMV(body.GetTransform().R, vertices i )) drawingContext.lineTo(v.x, v.y) drawingContext.lineTo(tV.x, tV.y) drawingContext.closePath() drawingContext.stroke() drawingContext.fill() It would be too intensive to keep track of all the circles that should be painted on to objects and would soon bog down, with potentially 60 clipped circles per second being added to be drawn on top of objects. The original thought was to stack two canvases on top of each other, so then we could draw the levels once and then when ever necessary just draw the paint splat over them once and forget about it (changing the composition mode to source atop to get appropriate clipping), and since we're not redrawing it would stay there. However, this won't work on moving objects (like players) (that can also rotate and change size relative to the camera). I'm not sure how to do it, since all objects are made up of solid colour to start with there's no texture data or anything we can modify.


jquery ondrag map load only what has not been viewed When a person mouse down, moves the mouse, and mouses up the system gets the different in the mouse down coord and the mouse up coords and loads in the new map items. However, the problem is it loads them every time so I want a way to track what has been loaded without too much work on checking or storing checks. Most promising. Came up with while typing this. Section the screen into 250x250 sectors and check if that sector has been loaded. Keep track of each corner of the screen and see if there is an area of those that have not loaded. Keep a record of the corners of the screen. When mouse up coords are greater then load the different. Problem is if they are at coord 10,000 then it will load from 10k to 10k positive and that is a lot of items to load. Check every item on the page to see if it is loaded. If I do this I might as well reload the whole page. If anyone has some suggestions feel free to pass them on.


HTML5 game fps render lag I am currently creating a flappyBird like HTML5 game using Proccessing.js You can see current work here http files.tips4design.com flappySlothRelease The problem is that even though the FPS is 60 (or constant) there is an obvious shuttering in rendering. I have read a lot of game loop articles to solve this issue, but neither with Processing.js draw loop, browser's requestAnimFrame nor constant delta time the problem was solved. Now I use the variable deltaTime approach and Processing.js default draw() loop. delta now lastTime ... position position velocity delta I have been stuck for two days with this problem, and ca not really figure out how to fix the shuttering. Any help would be greatly appreciated! Thank you!


Testing HTML5 canvas games on low resource computers I've made a game in HTML5 amp JS and want to test it on varying types of user setups as I've heard it doesn't perform too well on older MacBooks. How can I accomplish this? I'm thinking of something like browserstack.com but for GPU, CPU and memory testing.


Client interpolation for 100 serverside game I'm developing an online browser MMO 2d war game. And I'm having some issues with the interpolation. The server sends updated positions to the clients every 90 ms. I've managed to make it smooth, and it works very well on low latency, but if the latency is high, everything skates around like its on ice (OVERLY SMOOTH). I would like to achieve normal movement (visually), and I don't care about input lag, as 3 400 ms input lag doesn't matter for this game. This is how I'm doing it now (simplified for readability) The "Server" object is the one processing the updates send by the server, and "animate()" is the gameloop. var Server msAhead 0, Time Date.now(), SetData function (data) Set date.now() to calculate ms since last update var now Date.now() calculates ms since last update var ms now this.Time sets new time (for calculating ms next update) this.Time now Keeps track of how many milliseconds the server is ahead (position vice) this.msAhead ms Attatch a reference with the players new position to each player .each(data "players" , function (id, data) Players id .target data ) var Time function animate() Sets time if first call if (!Time) Time Date.now() Sets new time and calculate ms between frames, sets deltatime var now Date.now() var ms now Time var delta ms 0.001 reset info for next frame Time now Calculate and normalize lerp var lerp ms Server.msAhead update the "msAhead" so we know that we are closer to our target position Server.msAhead ms normalize lerp (it can be off on the first frames since time isn't set yet, or is heavy spikes occur) if (lerp gt 1) lerp 1 if (lerp lt 0) lerp 0 Update player positions lerping towards the target position set by the server object .each(Players, function (id, player) player.position Lerp(player.position, player.target.position, lerp) ) Request next animationframe requestAnimationFrame(animate) EDIT I can simulate my goal on high latency by doing var now Date.now() 300 in the animation loop. But that will crash (stop updating) low latency players, since the client will think its ahead of the server, and lerp will become negative (zero).


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.


Rotating a view of a chunked 2d tilemap I'm working on a top down (oblique) tile based engine. I would like for the tiles to have a definable height in the world, with Characters being occluded by them, etc. This has led to a desire to be able to "rotate" the view of the world, even though I'm using all hand drawn graphics and blitting. Therefor, I need to rotate the actual world itself, or change how the Camera traverses these arrays. How can, or should, I create individual rotations of 90 degrees, when I have multi dimensional arrays? Is it faster to actually rotate the array, to access it differently, or to create pre computed accessor(?) arrays, something like how my chunks work? How can I rotate an individual chunk, or set of chunks? Currently I establish my tile grid like this (tile height not included) function Surface(WIDTH, HEIGHT) WIDTH Math.max(WIDTH (WIDTH TPC), TPC) HEIGHT Math.max(HEIGHT (HEIGHT TPC), TPC) this.tiles this.chunks Establish tiles for(var x 0 x lt WIDTH x ) var col , ch x Math.floor(x TPC) if(!this.chunks ch x ) this.chunks.push( ) for(var y 0 y lt HEIGHT y ) var tile new Tile(x, y), ch y Math.floor(y TPC) if(!this.chunks ch x ch y ) this.chunks ch x .push( ) this.chunks ch x ch y .push(tile) col.push(tile) this.tiles.push(col) Even some basic advice on my data struct would be much appreciated.


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)


Using a setTimeout to Jump I am trying to make a jump function. I am making a game in html5 canvas with Javascript. I have gotten the player to move. When making the jump function I decided to use a timeout to reverse the coordinates back to the original after a set time. The error is after the character moves up he does not return to the original position the character just stays there, and then upon clicking the jump (arrow key) again the player goes the other way e.g (down). class Character constructor() this.x 50 this.y 400 this.posX 0 this.posY 0 this.width this.height this.hitPoints 1 this.directionFace "right" this.jump false this.jumpHeight 23 move(e) this.x this.posX this.y this.posY if (e.keyCode 37) console.log('left') this.posX 10 else if (e.keyCode 38) console.log("UP") if (!this.jumping) this.posY this.jumpHeight this.jumping true setTimeout(function() this.posY this.jumpHeight this.jumping false , 500) else if (e.keyCode 39) console.log("right") this.posX 10 e.preventDefault()


How do I protect sending scores from HTML5 games to my server On backend I am using java. I have a game in HTML5 when user completes it I sends an Ajax call to save the score to database. Now, someone can easily use tools like Fiddler and firebug to modify this ajax request and send a much better score to the server. How do I make sure that user cannot manipulate scores !


Unity 5 Animation attaching I have created the walking and idle animation for my fps player. I've added a JavaScript script to access it, but when I run it and press button(w), it stops and says that the animation is not attached to the object. When I drag the walking idle animation and drop to that object, it creates an animation controller. Again I run it, still same error. I can't find where to attach the animation Here's my script function Update () if(Input.GetKeyDown("w")) GetComponent. lt Animation gt ().Play("walk anim2", PlayMode.StopAll) if(Input.GetKeyUp("w")) GetComponent. lt Animation gt ().Play("idle anim2", PlayMode.StopAll) Where do I need to attach the animation?


Should I refer to browser based games as HTML5 games or Javascript games? First of all, I know that there are alternatives to both HTML5 and Javascript, but I worded the question so generally ("browser based") because if I had said "HTML5" or "Javascript" games that would already imply an answer to the question. When writing wiki posts or discussing, I usually call these games "HTML5 Javascript" games. They are written in Javascript, using the new HTML5 technology. What is the proper way to call them HTML5 or Javascript games? I see that most people opt for HTML5, why?


Shadows in html5 canvas game I'd like to ask for reference. I met an article about how to cast shadows in games. I'm using html5 canvas (currently without webgl) with javascript for my projects. The article mentioned above is located at http willyg302.wordpress.com 2012 11 04 2d visibility . I was thinking if this method is possible to employ with canvas (without webgl) and javascript? More precisely, I have few shapes drawn on canvas some of them are complex made by arc and similar methods. Thus I don't have a simpel way how to describe one shape with an equation where I can store only a few parametrs (i.e. circle is described as centerX, centerY, radius with these I can easily draw it but with more complex shapes I don't have such information) therefore I thought about storing the whole canvas data by pixels with context.getImageData.data, then using method described in the article (polar transformation, ..., back to cartesian system) and putting the whole scene into canvas with canvas.putImageData method. But before actually applying this I'd like to ask if it's even possible with canvas (no webgl) and javascript to create shadows dynamically (light source moving across the screen) this way without heavy fps loss (I can imagine this method works pretty good for still objects but the moment when I need to do it each time a light source moves I'm not sure if javascript canvas can handle this in reasonable time, especially when I found information that putImageData and getImageData are quite slow)? Or if anyone has tried to create dynamic shadows in different way in html5 js I'd appreciate your suggestions about these as well (I do it currently in similar way as is described in http ncase.me sight and light , though I'm experiencing some troubles with concave shapes ( ). This is getting awfully long, I hope I explained myself well enough. Thank you very much for any advice you can share and I'm sorry that my post grew so large, although I'm asking just one question. EDIT Forgot to mention, I'm looking only for 2d solution.


Throw ball distance and force I have a question, I need a formula to calculate the distance and a force based on the speed that drags the finger up on the phone. And is there any way I can get a look? And also shows the trajectory of the ball with lines ... An example is the Pokemon Go, see the image (the user presses the ball and drags the finger upwards). Are there any examples so that I can study?


How to display a tile map from a 2D array in JavaScript? I have stored my map, but the problem I am having is displaying it. My map is 100x100 tiles which are 40x40px. I have my loop running through the array but I'm having difficulty selecting the portion of the map image to relate to the tiles. This is the code which selects the portion of the image on each iteration var sx Math.floor(tileId 8 tileWidth) source x var sy Math.floor(tileId 8 tileHeight) source y I'm using Canvas and keep getting this error message INDEX SIZE ERR DOM Exception 1 Index or size was negative, or greater than the allowed value. I'm guessing the remainder or division by 8 is wrong, this is something I picked up from the net, but what exactly does that integer need to be? Thanks


How can I mimic an isometric perspective using square tiles? Can an isometric perspective be mimicked with traditional square tiles? Can't the effects of the 45 degree overhead view simply be "drawn in" to the square? How would this work? Picture this the tiles themselves are square (not diamond) but all objects placed on them (sprites, terrain objects like trees, buildings, etc) are drawn from isometric view as if they were on diamonds. This might be a silly question to ask, but I'm having difficulty understanding isometric perspective.


How do I keep a PHP server running forever? I'm making a web game RTS, it's mostly create units, manage resources, attack with army, and level up factories. I have created the basics of the game using Javascript, PHP, and MySQL databases. I use the database to store player credentials and stats, and PHP as a server side logic (like retrieve the right player and attack with X units). On the client side I use HTML CSS and javascript. My problem is that I need to keep adding resources based on the factories level (ex. 10 gold every min, when mine factory lvl.1). The only answers that I have found, is to modify the PHP file to run an infinite loop and keep connecting to the database to add those resources 24 7. I think the server also needs to handle attack travel (when units arrive at the enemy castle and the fight is over) and some other logic, but I don't have physical access to the server, and keep connecting to the database to add resources doesn't seem a good idea. I'm willing to make a server using other languages, or use other way to store data that keeps changing, so I can avoid multiple connections to the database. If you know a better way to do it, or something that can put me on tracks I will appreciate it.


Open Source HTML JS game(s) with license that would allow embedding in my app? I'm working on an educational app for kids. At the end of the sign up process, the kids must wait for a confirmation from their parents in order to gain access to the app. While they wait for this to happen, we want to let the kid play a simple game as a way to keep their interest up. Is there a marketplace or repository for games with such a license that we could either purchase (affordably) or use for free in our own app?


How To Upload JavaScript Games To Steam So I've been making this game called The Necromancer and (quick note, I am still working on the game. Also, I know this sounds similar to this question, but my question is for the general process) I wanted to publish on the Steam Store. However, I don't know what the process is, as in what you do to get your game posted on Steam. Also, how would I get a few files, and somehow put it in a virtual package that I can give to Steam. I just feel rather confused on the subject. Thank you for your time


Use JS to grab values from a dynamic Lua Table ((BACKGROUND I'm modding a game that runs using Lua and the Source2 Engine (Dota). Gameplay logic uses Lua and HUD uses JS)) I used Lua to create a global table. For instance global itemRollsManager itemID id 19, buff1 quot modifier bonus range quot , ability quot tusk ice shards quot Now I need to grab that info and display it in the HUD using JS. I've successfully grabbed the itemID inside JS, but now I need to grab that table and those values while the game is running. How do I do this? Is it even possible with just JS and Lua?


Implementing Achievement System in Javascript I understand that for more complex achievements, specific code can't be avoided, but for simple ones like (player clicked 100 times) or (player earned 30 bajillion cookies) or (player played for 1 hour) it should be as simple as abstracting the achievements to something like a list of properties values and having some event handler. My problem is that since I'm using Javascript and there's no really clean way to do pointers, how am I supposed to create an achievement class that can be iterated through procedurally? Ideally I'd like something like this Achievement class function Achievement(name, property, value, text, points) this.name name this.property property this.value value this.text text And then I'd add an achievement like so achievements.push(new Achievement("Clicktastic", amp numClicks, 1000, "You clicked 1000 times!") And have some kind of function bound to a Window.setInterval that was constantly looping through all achievements and for these simple types doing something like for (var i 0 i lt achievements.length i ) if ( achievements i .property gt achievements i .value) deal with earning achievement I'm just using some C style pointer dereferencing notation here. Basic idea is that I'm not sure how to create a generic achievement that can arbitrarily care about specific properties without pointers.


Security concerns related to HTML 5 games I would like to know if people could modify an HTML 5 game's code to harm either the server or other players whom visit the page. More specifically, whether someone could modify a simple game that doesn't have things like high scores, global stats, log in, etc. to harm other users and or the server the game is hosted on. Is this only a concern for games that retrieve data to be stored on the server itself?


How to reduce the total time spent checking against my world bounds? I'm making a game engine and currently I use a function for checking a new position after movement to prevent game objects from escaping the world const boundary function (min, max) return Math.min( Math.max(this, min), max ) I've noticed that it consumes around 9 10 of my game loop (testing with 4500 objects). Is there a better way to handle this? Do I generally need to make my world finite? To clear this up, this is not an object object collision detection question. For that I have a grid, and this grid is based on the size of the world, which is why I check that objects don't escape the world size limits.


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


How to make a snake game where each snake tile follows it's connected tile I want to make a basic snake game. It has a head and a series of tails that occupy a tile in a grid. The first tail in the series is adjacent to the head. and each tail that comes after is adjacent to the previous tail. Head can move in four directions and the first tail moves to head's previous position, and each other tail moves to the previous position of the previous tail, as they follow each other. How can I model this as data, and update it for movement. I've tried this but that's a little doesn't work. p x 0, y 0, tails function init tail(dx,dy) return x 0, y 0, dx dx, dy dy end Initialization add(p.tails, init tail(0,1)) add(p.tails, init tail(0,1)) add(p.tails, init tail(0,1)) local last p for tail in all(p.tails) do local tx last.x tail.dx local ty last.y tail.dy tail.x tx tail.y ty last tail end Movement local last p for tail in all(p.tails) do tail.dx last.dx tail.dy last.dy local tx last.x last.dx tail.dx local ty last.y last.dy tail.dy tail.x tx tail.y ty last tail end This is what I have so far


How do I make sure everyone sees the same distance across different resolutions? Hello game dev community. I have recently got into making games in a browser window, and me and a friend ran into a common problem. Let's say I have a game like diep.io, where users can control their tank and move across a large grid. Each player can only see a certain distance, even if they moved the window to a larger monitor, like from 1080p to a 4K monitor. I've created a game in HTML5 canvas, but the problem is that it depends on the browser's window.innerWidth and innerHeight properties. I can tell that this is an issue, because if I drew a grid, one player on a 1080p monitor could only see x distance but a player on a 4K monitor with a larger width and height could see x 2 distance (or how much larger it actually is), meaning that the player on a 4K monitor has an advantage, by seeing players in a larger distance. How exactly could I tackle this problem? My friend has the same issue, and I hope this answers it.


Canvas tile grid, hover effects, single tilesheet, etc I'm currently in the process of building both the client and server side of an HTML5, canvas, and WebSocket game. This is what I have thus far for the client http jsfiddle.net dDmTf 20 Current obstacles The hover effect has no idea what to put back after the mouse leaves. Currently it's just drawing a "void" tile, but I can't figure out how to redraw a single tile without redrawing the whole map. How would I go about storing multiple layers within the map variable? I was considering just using a multi dimensional array for each layer (similar to what you see as the current array), and just iterating through it, but is that really an efficient way of doing it? Currently the "borders" encroach on one another. I'm not sure what I'm doing wrong? If you hover over and off of the bordering "tree" tiles, you'll notice how it removes part of the neighboring tiles border. This shouldn't need to happen. Outside of the map, what would be an elegant way of adding Players to the render scene? I've seen a few places that recommend you use multiple canvas's, would you recommend that since they'll probably be moving much more? In addition to that, how can I confine player movement to the grid, similar to how in the pokemon gameboy games, when you tap the left arrow, you always move one "space" that direction. It's not a halfway type deal. Camera. What would be a good way about adding a "camera" to the equation, so the viewport can pan around a larger map area? Obstacles. In the newer version of the map, you'll notice an empty obstacles array. Assuming players get added well, what do you think would be good for adding movement obstacles? Side note The tile sheet being used for the jsfiddle display is only for development. I'll be replacing it as things progress in the engine. If you guys have any pointers for my JavaScript, feel free. As I'm more or less learning advanced usage as I go, I'm sure I'm doing plenty of things wrong. Note I will continue to update this post as the engine improves, but updating the jsfiddle link and updating the obstacles list by striking things that have been solved, or adding additions. Edit Updated link from http jsfiddle.net dDmTf 7 to http jsfiddle.net dDmTf 17 this handles the "hover" problem, and it's been striked out. Edit Updated link from http jsfiddle.net dDmTf 17 to http jsfiddle.net dDmTf 19 fixes the out of bounds issue with the tiles Edit Updated link from http jsfiddle.net dDmTf 19 to http jsfiddle.net dDmTf 20 adds multiple layers to the equation


I can't clear the paint image in my Canvas I'm trying to make the Mario move, but somehow it leaves traces behind, can anybody help??? var canvas document.getElementById("screen") var ctx canvas.getContext("2d") var mario var marioSprite var tiles var speedX 1 marioSprite Specification mario target picture specification X amp Y, Width amp Height px 276, py 44, pwidth 16, pheight 16, drawing on Canvas specification X amp Y, Width amp Height cx 16, cy 116, cwidth 16, cheight 16, draw Mario in Canvas function drawMarioSprite() marioSprite new Image() marioSprite.src 'file C Users MASTONO ALI Desktop img characters.gif' marioSprite.addEventListener('load', e gt ctx.drawImage(marioSprite, mario.px, mario.py, mario.pwidth, mario.pheight, mario.cx, mario.cy, mario.cwidth, mario.cheight) ) this.position function() this.mario.cx speedX position() drawMarioSprite() end drawTiles and tilesLoop function drawTiles() tiles new Image() tiles.src 'file C Users MASTONO ALI Desktop img tiles.png' tiles.addEventListener('load', e gt tilesLoop() ) function tilesLoop() for (let x 0 x lt 25 x ) for (let y 11 y lt 13 y ) ctx.drawImage(tiles, 0, 0, 26, 26, x 12, y 12, 20, 20) drawTiles() end function draw() drawMarioSprite() drawTiles() window.requestAnimationFrame(draw) window.requestAnimationFrame(draw) thank you