Search the Community
Showing results for tags 'gameloop'.
-
I've been working on a base repo for pixel art games. The issue I've been running into is stutter when rendering sprites. Specifically I've seen this run buttery smooth on my laptop with a refresh rate of 144hz, but on 60hz monitors it seems to stutter. The game loop looks sensible to me, but I'm not sure what else to try at this point. Any help would be much appreciated. You can find the branch I'm working on here. The specific file of interest is game.ts. You can also see a live demo of it running on netlify.
-
i am trying to figure out why assets sometimes “double” when character moves quickly. i think it’s probably a problem in gameLoop() or draw() but i can’t figure out where. i want the player to move whenever the user presses a key, but the monster movement is on a timer (1x per second, or less depending on difficulty level). the requestAnimationFrame(renderViewport) call is inside draw(). draw() is called whenever character moves, but gameloop() only runs 1x/second (or per .5 second, etc) for monster movement, and there is a draw() call in there too. is there a better way to do this? front end: anti-fascist-heroine-addiction.surge.sh code: https://github.com/rifkegribenes/anti-fascist-heroine-addiction
-
- react
- requestanimationframe
-
(and 2 more)
Tagged with:
-
I've implemented `Timer` class for high accuracy timing (for example for update logic/game-loop, sending ping each 15 seconds by WebRTC etc.) setTimeout/setInterval fires once per second when tab is inactive, so how to gain accuracy timing? We could set up `setTimeout/setInterval` in WebWorker, because in WebWorkers when tab is inactive, `setTimeout/setInterval` still fires with it's own interval/delay. We could then send message `postmessage/onmessage` from WebWorker to Main Thread on each `setTimeout/setInterval` fire calls as a tick. For some time this idea was working and was brilliant, but when I'm looking now (latest chrome version) this isn't working anymore because of `postmessage`, now `postmessage` delivers event with delay when tab is inactive.. Looks like Chrome Dev Team noticed this feautre, and they've fixed it.. but it wasn't a bug? gaah.. or maybe I have something wrong in the code: https://jsfiddle.net/mfzmotb1/16/ Timer = function Timer(callback, interval) { var id = Timer.prototype.__idCounter++; Timer.prototype.__hash[id] = callback; this.started = false; this.package = JSON.stringify({ id: id, interval: interval }); } Timer.prototype.__workerScript = function() { var __hash = {}; onmessage = function(ev) { var data = JSON.parse(ev.data); if ( __hash[data.id] === undefined ) { __hash[data.id] = { id: data.id, lastTime: performance.now(), interval: data.interval, step: 0 } } else delete __hash[data.id]; } function loop(start) { if ( !start ) for ( var id in __hash ) step(__hash[id]); setTimeout(loop, 0); } loop(true); function step(unit) { while ( performance.now() - unit.lastTime >= unit.interval ) { unit.lastTime += unit.interval; unit.step++; var now = Date.now(); console.log("ww", unit.step, "-", now/1000); postMessage(JSON.stringify({id: unit.id, time: now, step: unit.step})); } } } Timer.prototype.__idCounter = 0; Timer.prototype.__hash = {}; Timer.prototype.__worker = new Worker(URL.createObjectURL(new Blob(['('+Timer.prototype.__workerScript.toString()+')()'], {type: 'application/javascript'}))); Timer.prototype.__worker.onmessage = function(ev) { var data = JSON.parse(ev.data); Timer.prototype.__hash[data.id](data.time, data.step); } Timer.prototype.start = function(){ if ( !this.started ) { Timer.prototype.__worker.postMessage(this.package); this.started = true; } } Timer.prototype.stop = function(){ if ( this.started ) { Timer.prototype.__worker.postMessage(this.package); this.started = false; } } var timer = new Timer(function(wwTime, step) { var now = Date.now(); console.log("m_", step, "-", wwTime/1000, now/1000, (now-wwTime)/1000); }, 100); console.log("starting in 2sec, so you have time to switch tabs"); setTimeout(function() { timer.start(); }, 2000); Basically this code produce new class called `Timer`, there is WebWorker based on one function body `Timer.prototype.__workerScript` <- this fn's body happens in WebWorker. One WebWorker handles all instances of Timer, each instance is for one timer. Any ideas how to fix it? Here goes output: Some tips: ww - console.log called from webworker m_ - console.log called from main thread 1,2,3 - number of timer step Tab Active: starting in 2sec ww 1 - 1485111848.697 //webworker tick time in seconds m_ 1 - 1485111848.697 1485111848.707 0.01 //webworker tick time, main thread tick time, diff ww 2 - 1485111848.798 m_ 2 - 1485111848.798 1485111848.799 0.001 ww 3 - 1485111848.898 m_ 3 - 1485111848.898 1485111848.898 0 ... Tab Inactive: starting in 2sec ww 1 - 1485110821.95 //webworker tick time in seconds ww 2 - 1485110822.049 ww 3 - 1485110822.149 m_ 1 - 1485110821.95 1485110822.169 0.219 //webworker tick time, main thread tick time, diff m_ 2 - 1485110822.049 1485110822.17 0.121 m_ 3 - 1485110822.149 1485110822.171 0.022 ... Do you know any ideas for measuring time for html5 gaming without throttle?
-
Hey guys, I have a question about game loops for large games in javascript. I am making a tycoon style game where at any time I can have many Sales Men who are working simultaneously. This means they all need to have accsess to the GAMELOOP at any given time. I have provided pseudo code on how I currently do this, however this feels messy. The code is simply, making two Sales Men, setting there current task with the assignJob function, then the loop will detect their Job and add to there profit. Is there a better way to do this (inside the step function)? init();//Set JobsassignJob(SalesMen[0], 'Door to Door Vacuum salesman');assignJob(SalesMen[1], 'Door to Door Ironing Board salesman');function init(){ //Set up SalesMan SalesMen = [ {id: 1, name: 'example1', job: false,profit: $0.00}, {id: 2, name: 'example2', job: false,profit: $0.00}, ]; step();}function assignJob(salesMan,jobType){ salesMan.job = jobType;}function step(){ //HERE IS THE ISSUE - THIS FEELS WRONG for(var i = 0 ; i < SalesMen.length ; i++){ if(SalesMen[i].job){ SalesMen[i].profit += 0.10; } } //LOOP GAME step();} (fyi I also had a version where each function that needed a loop would just loop internally, I removed this as I know having n-nunber of loops is bad)
-
So i've recently been building a game in Phaser, trying to keep objects as modular as possible, which lead me to this question. I have a main game state that currently handles all input events and moves / mutates objects as necessary, e.g. player, enemies, particles, etc, each being a modular object which is required using browserify. I wanted to keep all input handling / updating within this function to reduce the function calls I'm making each frame (to reduce delta times). My question is, would this actually yield noticeable efficiency improvements, or should I just pass a reference to the game object to each module to handle their own input / updating. Considering objects pass by reference, this shouldn't be an issue right? FOR EXAMPLES SAKE, So basically instead of update: function() { game.physics.arcade.overlap(enemyBullets, tank, bulletHitPlayer, null, this); enemiesAlive = 0; for (var i = 0; i < enemies.length; i++) { if (enemies[i].alive) { enemiesAlive++; game.physics.arcade.collide(tank, enemies[i].tank); game.physics.arcade.overlap(bullets, enemies[i].tank, bulletHitEnemy, null, this); enemies[i].update(); } } if (cursors.left.isDown) { tank.angle -= 4; } else if (cursors.right.isDown) { tank.angle += 4; } if (cursors.up.isDown) { // The speed we'll travel at currentSpeed = 300; } else { if (currentSpeed > 0) { currentSpeed -= 4; } } if (currentSpeed > 0) { game.physics.arcade.velocityFromRotation(tank.rotation, currentSpeed, tank.body.velocity); } land.tilePosition.x = -game.camera.x; land.tilePosition.y = -game.camera.y; // Position all the parts and align rotations shadow.x = tank.x; shadow.y = tank.y; shadow.rotation = tank.rotation; turret.x = tank.x; turret.y = tank.y; turret.rotation = game.physics.arcade.angleToPointer(turret); if (game.input.activePointer.isDown) { // Boom! fire(); }}I'd have something like update: function() { this.tank.update(this.game); this.turret.update(this.game, this.tank); this.shadow.update(this.game, this.tank); // etc etc}
-
Hi guys, my first post on these forums, how exciting A little background of myself - I am a web developer by profession, and most of my experience is within the tradition lamp stack / php development, however, I've seen the light! Although I've always know enough javascript to get by, and understand most simple concepts, i've never really truly understood the language. I've fallen head over heels in love with the language and much prefer 'the javascript way' of prototypal inheritance, synchronous programming, dynamic typing, etc. I've recently been trying to broaden my low level javaScript knowledge, and I love games, so most most of my tinkering has been within the game development realm. ANYWAYS, enough of the life story, basically what i've done is tried to fully grasp the idea of a game loop written in javascript - I was hoping to get as much feedback / suggestion / constructive criticism as I could. So without further adue, I present to you, my understanding of a fixed time-step game loop written in javascript. var Game = function() { // our fixed time-step // 60 FPS // or 16.667 ms per frame this.timeStep = 1000 / 60; // used to store the relative 'execution' time of the previous frame this.lastFrameTime = 0; // used to store the time taken to process the previous frame this.deltaTime = 0; // used to store update calls within our 'time-step' simulation this.updateCalls = 0; // the maximum number of update calls we'll allow before we intervene this.maxUpdateCalls = 240; // start our loop - bind our local execution context (the game object) requestAnimationFrame(this.mainLoop.bind(this));}// timestamp: indicates the current time when callbacks queued by// requestAnimationFrame begin to fire. think of it as "startFrameTime"// this is automatically passed by the requestAnimationFrame functionGame.prototype.mainLoop = function(timestamp) { // this function is called when our update calls exceed the maximum // update call limit, either our update logic has taken too long to // process, resulting in a very large deltaTime, or the window has // lost focus. function panic() { console.log('WARNING :: loop panic!'); this.deltaTime = 0; // discard the unsimulated time // snap the player to the authoritave state (from the server) } // the accumulation of the remaining delta time from the last // update + the time taken to process the previous frame (the delta time) this.deltaTime += timestamp - this.lastFrameTime; // set the last frame time to the current timestamp // this is confusing, we are basically setting our 'last frame time' // for the next frame this.lastFrameTime = timestamp; // reset our update call counter this.updateCalls = 0; // simulate the total elapsed time in fixed-size chucks while the time taken to // render the frame is greater or equal to the desired timestep (the amount of // time we want to render a frame (16.667ms)) // If the time that has passed since the last frame is less than the // fixed simulation time, we just won't run an update() until the the next frame // the remaining time left over is added to the next frame's delta time while (this.deltaTime >= this.timeStep) { // !!!!! update with our fixed time step (1000/60 === 16.667) !!!!! // // decrease our desired time step time from the accumulated delta // until it is less than 16.667ms this.deltaTime -= this.timeStep; // are we in a spiral of death if (++this.updateCalls >= this.maxUpdateCalls) { panic(); break; } } // !!!! draw our game objects !!!! // requestAnimationFrame(this.mainLoop.bind(this));}I've also read about FPS throttling, but I don't really understand the concept. I'm under the impression that if you have a fixed time-step and 'simulate' updates within your game loop, you'll never breach the time-steps resulting FPS, in this case 60 frames per second. Am I not understanding something correctly?
- 4 replies
-
- gameloop
- javascript
-
(and 1 more)
Tagged with:
-
Hello, currently I am working on a 2D side scrolling game. When I start it on my computer everything runs fine and smooth. IE is about 300 FPS. Firefox is about 100-110 FPS. So its a side scrolling game and there are some clouds in the sky, flooting from right to left. I am rendering the game inside of a canvas element. But there is a problem in generell. When I am just using a square like context.fillRect(800,200) an move it to the left it gets very jerky on low FPS. Sometimes it jumps. Sometimes its smooth. I cant explain why this happens. Im working since three full days on this problem and try to fix it. Here is what i have done so far. 1. I tried a gameLoop that locks the FPS at 30. - Animations gets Jerky when they speed up. 2. I tried to set a maximum for delta time - I move the shapes based on the time since the last update call. I tryed to set a maximum for the gap between: no effect still jerky. 3. I tried animation based of the FPS - That is not what I want because the game behaves diferent on devices with better hardware. Nevermind: animations still choppy! 4. I read everthing I found googeling the keywords: "Choppy game, gameLoops in generel, Html5 Animation Jerky, etc.. " 5. I downloaded every game I could find in the app store where I think they are made with HTML5 and Canvas. Some are very Jerky and Choppy! But I found some running smooth. 6. I tryed pixijs to render my stuff : still choppy 7. I thought about buying impactjs: In the forum are some topics about stuttering 100Bugs maybe a bad buy if the problem is still there. 8. I thought about giving up an play WoW again. 9. I created an html5gamedevs account and hope someone can help me. There must be a way to get this going. Even the SNES gets smooth animations. Thanks!
- 9 replies
-
- HTML5
- Javascript Canvas
-
(and 3 more)
Tagged with: