_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
2 | Raycasting weird lines on walls when ray is facing up or right I am trying to make a raycasting game. Everything is rendered correctly except when the ray is facing up (angle gt PI) or facing right(angle gt 0.5PI and lt 1.5PI) lines are drawn on walls. I am not sure what is causing it to happen but I know that the lines are not affected by the rotation of the player only by the players position. I also tried rounding the rays position but that did not help. Right and up ray walls. The walls up close. Left and down ray walls. Code let rayX, rayY, rayAngle, rayDeltaX, rayDeltaY for (let i 0 i lt this.screen.width i ) rayAngle this.angle this.fov 2 i (this.fov this.screen.width) if (rayAngle lt 0) rayAngle Math.PI 2 else if (rayAngle gt Math.PI 2) rayAngle Math.PI 2 rayX this.x rayY this.y let stepY if (rayAngle gt Math.PI) stepY this.tileSize rayY Math.floor(rayY this.tileSize) this.tileSize 1 else stepY this.tileSize rayY Math.floor(rayY this.tileSize) this.tileSize this.tileSize rayX this.x (rayY this.y) Math.tan(rayAngle) rayDeltaY stepY rayDeltaX stepY Math.tan(rayAngle) while(true) if (this.Map.map Math.floor(rayY this.tileSize) this.Map.width Math.floor(rayX this.tileSize) ' ') break rayX rayDeltaX rayY rayDeltaY let rayHorizontalX rayX let rayHorizontalY rayY let rayDistanceHorizontal Math.sqrt((this.x rayHorizontalX) 2 (this.y rayHorizontalY) 2) rayX this.x rayY this.y let stepX if (rayAngle gt 0.5 Math.PI amp amp rayAngle lt 1.5 Math.PI) stepX this.tileSize rayX Math.floor(rayX this.tileSize) this.tileSize 1 else stepX this.tileSize rayX Math.floor(rayX this.tileSize) this.tileSize this.tileSize rayY this.y (rayX this.x) Math.tan(rayAngle) rayDeltaY stepX Math.tan(rayAngle) rayDeltaX stepX while(true) if (this.Map.map Math.floor(rayY this.tileSize) this.Map.width Math.floor(rayX this.tileSize) ' ') break rayX rayDeltaX rayY rayDeltaY let rayVerticalX rayX let rayVerticalY rayY let rayDistanceVertical Math.sqrt((this.x rayVerticalX) 2 (this.y rayVerticalY) 2) let rayFinalDistance if (rayDistanceHorizontal lt rayDistanceVertical) rayFinalDistance rayDistanceHorizontal ctx.fillStyle 'darkblue' else rayFinalDistance rayDistanceVertical ctx.fillStyle 'blue' let rayCorrectedDistance rayFinalDistance Math.cos(rayAngle this.angle) let lineHeight this.tileSize (this.screen.width 2 Math.tan(this.fov 2)) rayCorrectedDistance let lineBottom this.projectionPlane.centerY lineHeight 0.5 let lineTop this.projectionPlane.height lineBottom ctx.fillRect(i, lineTop, 1, lineHeight) Any help would be appreciated. |
2 | How to display a lot of small objects using WebGL? Introduction The game scene contains a lot of 10x10 pixel elements for 1980x1200 px. screen the number of elements on the scene can vary from 0 to 23760 (elements cannot intersect). The live example http fintank.ru game The entire game space comprised of tiles each tile is responsible for some area and keeps elements for that area (similar to google maps). Each tile exist as 2 entities S and G. S is a set of elements in the tile, G is rendered image of a tile. When the server put remove elements to the tile, we change S and then re render the G. To draw a frame (at 20 fps) I just put the G of each visible tile using the putImageData(). That is done without WebGL. The question What is the most CPU effective approach to implement such many elements management using WebGL? Should I render each tile to a texture or each element may be implemented as a separate textured rectangle? The main concern is that each tile may be updated 30 60 times a second (elements adding removal). How to avoid memory leaks (how to reuse buffers?) if we make many new textures every second? What is the most effective way to manipulate pixels during rendering a 100x100 tile? How to avoid re uploading the unchanged textures to graphic card? |
2 | Open source level editor for HTML5 platform game? A natty GUI editor is very helpful to create level map. I want to use some open source choices rather than build my own from scratch. I found Tiled Map Editor but it doesn't work for what I want. Though I'm building HTML5 game, I don't have to use a HTML5 level editor as long as it can output well formatted map files which my javascript can read. Edit Sorry for the confusion. Tiled does not work for me because to make the player perform a 'tricky' jump, sometimes I want to set the distance between two platforms to, say, 7 3 or 8 3 tiles. But in Tiled I get only 2 or 3. If Tiled can do this, please teach me. |
2 | User input in game loop I am building a simple multi player fly around a 3D world game in Javascript webGL websocket (Chrome, Firefox mostly). How should I handle and process user input? My preliminary design (untested) is to first just track which keys are down in the event handler var keys document.onkeydown document.onkeyup function(evt) keys evt.charCode evt.type "keydown" keys CTRL evt.ctrlKey keys SHIFT evt.shiftKey websock.send(JSON( time (new Date()).gettime(), down evt.type "keydown", key evt.charCode, shift evt.shiftKey, ctrl evt.ctrlKey )) and then, in my requestAnimationFrame callback, compute how many time slices (say 20 per second?) have elapsed since the last render callback, and then compute that many time steps using the booleans in the keys array to determine if to apply a left bank, right bank, up down and accelerate and so that time step for each player. How effective responsive is this? Is there a better way? And is there a neater way to deal with latency than just backdating changes for other user's ships? |
2 | Stop a rotating object at a specified angle? I'm working in JavaScript with HTML5 and the canvas. I have an object which is rotating at a certain speed, and I need the object's rotation to slow down gradually and the front of the object to stop at a specified angle. (I'm using radians, not degrees.) I have a variable to keep track of the angle which the object is facing, as it rotates. How would I go about getting the object to come to rest, facing the direction I want it to? |
2 | How add a sprite to canvas using JavaScript? I'm very new to sprites and I'm trying to figure out how to use them. I want to use a simple solution. Something like this var c document.getElementById ('canvas) var ctx c.getContext ('2d') ctx.upload('image testImage') I'm very sorry if the solution is an obvious one, I'm not very good at JS. I am using pure JavaScript, I don't really like using engines. |
2 | The rule to scale pixel art non multiple of integer ratios I have pixel art, I want to draw. When player jumping I want to animate the art to squash stretch to have a feeling. But when I scale the art it get's distorted, as demonstrated in the image. In one video I heard a rule to always scale to multiples of 100 ratio. So 150 is not allowed otherwise pixels collapse into each other. I haven't experienced that in this image but is it ok to scale arbitrarily in pixel art? I see they scale the sprite arbitrarily in Celeste Game Player source. But It feels wrong to me. |
2 | Performance problems with scrolling html5 canvas for large tile based game I try programming a splix.io clone as an electron app and do the visualization via the html5 canvas. The movement across the tiles should look fluent like the original, so I target 60 frames a second. The programm worked fine till I tried to replace the tiles created through fillRectangle() with svg images using drawImage(). This resulted in a huge performance drop, which I now try to fix. To mention here is that, like splix.io, I have a quite large playfield with a targeted size of 500x500 tiles and a fullscreen viewport, so basically the canvas has to draw the whole screen each frame. Known performance improvements, that I implemented are Separating the logic calculations and "rendering" into their own windows, separated from the main process. Only drawing the area visible to the player Foreach tileType hold a offscreen canvas, so that I can copy the ImageData to the onscreen canvas. Draw tiles and the players on separate canvases. A drawing loop with requestAnimationFrame() instead of setTimeout() seemed to be impractical because the ultimate goal is to let AIs, which will run in their own child process, play against each other. Therefore I can't rely on requestAnimationFrame which throttles performance when the window loses focus or is minimzed. What further performance improvements can you recommend? Is the scale of my game maybe too large for the canvas and would a switch to OpenFL WebGL may be the better solution? |
2 | Recognising when a user is clicking below a particular sprite I have a game, built using pixi.js, where I want to run some code every time the user presses below a certain sprite. I am handling the press event using hammer.js. The problem is that the y attribute of the sprite and the y attribute of the user s touch event don t match what I can see on my screen. As, an example, consider the code below if (touchPointer.clientY gt this.children.marker1.position.y) console.log(" Clicked Below the Line ") else console.log(" Clicked Above the Line ") The problem I have is that, when I click slightly above the sprite, the first section of code will run (which prints Clicked Below the Sprit ), even though on the screen, I can clearly see the pointer is above the sprite. I am guessing, what s going on is that the y positions for the pointer and the sprite are being calculated differently, but I don t know how to go about ensuring they re calculated consistently, so I can properly compare sprites against the pointer. Any suggestions? |
2 | 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 |
2 | Online Browser Game Resource Incrementing Production Problem I am working on a browser game where there are citys and their resource productions. Each player has their own production rate for each resource.Lets say stone as example. I have production rate,capacity and timestamp(when production started for that resource) for stone in db.I am pulling production rate from db and updating production value on client(incrementing it) but not in db since updating db value each second is not a good idea.So each time user refreshes page or does some action releated to stone,server checks timestamp and production rate and calculates what should be the value of stone in that time,i mean real value and updates client. "stone" "capacity" 10, "count" 0, "timestamp" 1531470433, when production started. "rate" 20, stone production in a minute This calculates users current stone value and updates db. var allStoneProduction Math.floor((currentTime stoneDbTime) stoneProductionRate 60) The problem is with capacity.Players are able to increase capacity of each resource. I can detect when stone capacity going to be full in server since i know production rate and production start time.Then i am making stonecount equal to capacity. This code checks if storage is full.If its not it sets value of stone production. var storageFullTime stoneDbTime (stoneCapacity stoneProductionRate) 60 if(currentTime lt storageFullTime currentTime storageFullTime) console.log("storage is full!") Resources.update( ownerId userid , set "stone.count" stoneCapacity ) else Resources.update( ownerId userid , set "stone.count" allStoneProduction ) As you see allStoneProduction is actually always going up without checking capacity since its only based on rate and start timestamp.This is ok if there is no max capacity. If stone count reaches its capacity i stop incrementing on client side by checking stonecount,stonecapacity.(10 10) lets say. If i change capacity from 10 to 20 on db,client gets new capacity value and starts to increment it 11,12,13... until capacity 20. But server cant follow up this.Should i also write timestamp of when capacity changed ? I couldnt really write the correct if else logic for this. So how do i compute this capacity change in server side ? allStoneProduction value doesnt care about reaching max capacity and increasing capacity.So if change capacity and refresh page,i get a wrong stone count.(since in server logic production never stops) |
2 | I'm having very negative thoughts, can you help me? I'm 27 years old and I recently started vocational studies for app development. The first year is mostly about introduction to c programming and also a light introduction to html and javascript. I have never studied anything related to coding before. I know how to make pixel art , music and sounds, but coding is just so difficult for me. My objective in life right now is to make a very simple game and I feel so frustrated because I can't achieve anything. I have even tried things like stencyl or construct 2 but even that kind of software I can't understand it enough to make a very simple game. I'm breaking all the rules here, but, can you help me? I read about people that are like 2 months into coding and are already making games. Am I too dumb? Should I just quit altogether? |
2 | PIXI v4 Is possible to disable Multi Texture Batching in PIXI v4 ? I would like to know if is possible to disable the multi texture batching in a PIXI V4 game. Recently i jus update my game PIXI lib from version 3 to 4.2. I m using cocoon Canvas . It seems perfect on iOS and android version greater than 5. In a old phone the texture batching is messing with the textures. https www.youtube.com watch?v t6wVYRm731I amp feature youtu.be Please. Is possible to disable it. I already tried PIXI "settings" .SPRITE MAX TEXTURES 1 PIXI "settings" .SPRITE BATCH SIZE 1024 without success |
2 | RayCasting with Mode7 I'm trying to join the mode7 algorithm with RayCasting. For mode7, I'm using a simple rotation matrix to implement the rotation. The result is a little strange and I can't fix it. Do you know what is the problem of the alignment of the algorithms? See the gif below to understand The code I'm using is function mode7() let x 0 let y 0 let z 0 let sin Math.sin(degreeToRadians(data.player.angle)) let cos Math.cos(degreeToRadians(data.player.angle)) for(let y data.projection.halfHeight y lt data.projection.height y ) for(let x 0 x lt data.projection.width x ) x ((data.projection.width x) cos) (x sin) y ((data.projection.width x) sin) (x cos) x z y z if( y lt 0) y 1 if( x lt 0) x 1 y 8.0 x 8.0 y data.floorTextures 0 .height x data.floorTextures 0 .width screenContext.fillStyle data.floorTextures 0 .data Math.floor( x) Math.floor( y) data.floorTextures 0 .width screenContext.fillRect(x, y, 1, 1) z 1 Is there someway or a tutorial to teach how to fix this issue? I tried to find it but i didn't find anyone about RayCasting with mode7. |
2 | Does pausing the canvas draw restores the FPS to higher value in a HTML5 game? I set Frame Per Second of 60 for my game. But after 1 minute it gets to a significantly lower value around 8 FPS. Does pausing the canvas drawing restores the FPS to higher value? If it does, how much time is enough to pause the game in order to get 60 FPS again? |
2 | 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 |
2 | Saving Scores Using Cookies I've recently created a small galiga like game recently using JavaScript and HTML5. I've run into a bit of trouble saving cookies, the cookie saves, but then resets itself when the page is refreshed, my code function saveScore() var date new Date() date.setMonth(date.getMonth() 5) var expires " expires " date.toGMTString() document.cookie "score " lvl expires " path " function loadScore() var cookiearray document.cookie.split(' ') for (var i 0 i lt cookiearray.length i ) var name cookiearray i .split(' ') 0 var value cookiearray i .split(' ') 1 if (name "score") alert("Prior score found. Loading score...") lvl value EDIT It appears as though I made an error outside of the given code, and reset the level to zero, I fixed this, and everything works well, I apologize for any confusion caused. |
2 | 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? |
2 | 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? |
2 | 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? |
2 | Time passed check with Pause functionality I am working on a game that has a lot of time passed checks of the following format. These work great, but there is a problem when the game is paused If paused for any meaningful amount of time, the if statement will become true. const t new Date().getTime() Get the current time (in ms) const fireCooldown 500 The time to wait before firing again (in ms) if(t gt lastFireTime fireCooldown) lastFireTime t fire() How can I integrate pause functionality into this in a way where pausing does not make the if statement true? |
2 | Strategies to make it difficult to cheat easier to identify cheaters in Javascript HTML5 game I intend to have a Javascript HTML5 game with a global leaderboard. I have devised a very simple system for submitting highscores as follow When the game finishes, the game client makes a POST request to server hosting the leaderboard that contains the name of the player and their score. Then, the server inserts the submission into its database. However, this system can easily be cheated by an individual with an html form submitting POST requests with whatever score they want to my server. I already know that a foolproof anti cheat system is impossible because of how easy it is to modify Javascript and HTML on the client. I also know that I should never trust the client. However, implementing everything on the server side will be impractical for me since my server will not have the resources necessary to perform all the calculations for all the players. So instead, I simply wish to make it as hard as possible for the average individual to cheat (and recognizing that it will always be possible to cheat), while making it as easy as possible for me to identify when a score that was submitted might possibly be fake. What are strategies I can use to accomplish such? Please include examples whenever possible. For example, I have heard someone suggest using "pre shared keys". However, I am not a cryptography expert and I have no idea how to go about implementing that. |
2 | Calculating the poly vertices based on the result of Connected Component Labeling I am making a tile based game. And now I can find all the connected area using the Connected Component Labeling algorithm. But now the problem I am having is how to calculate the poly vertices of each connected area. For example As you can see all the YELLOW tiles are of the same AREA and with the help of Connected Component Labeling algorithm I know all the (x, y) info of each tile. And now I want is the generate a poly vertices array for the YELLOW AREA POLY (clockwise). Is there any good algorithm for this ? Any suggestion will be appreciated, thanks ) |
2 | 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 |
2 | how do i make the JS jquery tic tac toe squares only clickable once? As i have it now my script makes the 3x3 grid clickable, and I dont know exactly how to turn on the click once it has been clicked. This is using jQuery and a simple if else statement to switch between turns. (document).ready(function() var turn 0 (" cell11, cell12, cell21, cell22, cell13, cell23, cell31, cell32, cell33, ") .click( function() var cell (this) if(turn 0) turn 1 cell.css("background","url(images o.png)") else turn 0 cell.css("background","url(images x.png)") ) ) |
2 | How do I generate a 2d grid based map without screwing it up? I'm relatively new to the mechanics of game development catching up fast, but there are still some things that escape me. For example generating a fully accessible map on a 2d grid. See the example at http crawl.s z.org. Each floor map starts with dozens of winding labyrinthine passages and randomly drops in points of interest temples, boss lairs, bazaars, etc. I know there's a lot of factors that go into this generating passages that always have at least one exit (no isolated tunnels in the walls), making sure passages have at least a one cell width wall between them and adjacent parallel passages, and dropping points of interest in such a way that they connect to the dungeon. I've taken a shot at it, and it's very easy to ranomly place lines in a 2d matrix that represent passages but they're never guaranteed to connect, and it's not nearly as elegant as the maps at the above example. I suppose my question is, what do I need to know to reproduce the example at crawl.s z.org? I know this is a large question I'd be fine with someone handing me a link to a reference site and telling me to learn it there. I'm just new enough at this that I don't even know what terms to google maybe there are names for different generation processes? Available techologies are JS (jQuery) and PHP, so a solution tailored to one of those would be ideal. Thanks! |
2 | setting a time delay between two frame when animation a sprite sheet this is my jsfiddle http jsfiddle.net Z7a5h As you can see the animation of the sprite sheet when the player is not moving is too fast so i was trying to make it slow by declaring two variable lastRenderTime 0,RenderRate 50000 but my code is not working and it seem i have a misunderstanding of the algorithm i am using so can anyone lay me a hand to how can i fix it ? if (!this.IsWaiting) this.IsWaiting true this.Pos 1 (this.Pos 1) 3 else var now Date.now() if (now this.lastRenderTime lt this.RenderRate) this.IsWaiting false this.lastRenderTime now |
2 | 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 |
2 | 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? |
2 | 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. |
2 | 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? |
2 | 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? |
2 | 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.) |
2 | 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? |
2 | 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. |
2 | 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? |
2 | 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! |
2 | 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? |
2 | 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!) |
2 | 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 |
2 | 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. |
2 | 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. |
2 | 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. |
2 | 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). |
2 | 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? |
2 | 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. |
2 | 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. |
2 | 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? |
2 | 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. |
2 | 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. |
2 | 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) |
2 | 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? |
2 | 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? |
2 | 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. |
2 | 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! |
2 | 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? |
2 | 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 |
2 | 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. |
2 | 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? |
2 | 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. |
2 | 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? |
2 | 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 ) |
2 | 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. |
2 | 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? |
2 | 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 |
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 |
2 | 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 |
2 | 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. |
2 | 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? |
2 | 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! |
2 | 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 ? |
2 | 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? |
2 | 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. |
2 | 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 |
2 | 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. |
2 | 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. |
2 | 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. |
2 | 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 |
2 | 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) |
2 | 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. |
2 | 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 |
2 | 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) |
2 | 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) |
2 | 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. |
2 | 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 |
2 | 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? |
2 | 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? |
2 | 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? |
2 | 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. |
2 | 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? |
2 | 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. |
2 | 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 |
2 | 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. |
2 | 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 |
2 | "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. |
2 | 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. |
2 | 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! |
2 | 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. |
2 | 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). |
2 | 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. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.