_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
2 | How to determine where on a path my object will be at a given point in time? I have map and an obj that is meant to move from start to end in X amount of time. The movements are all straight lines, as curves are beyond my ability at the moment. So I am trying to get the object to move from these points, but along the way there are way points which keep it on a given path. The speed of the object is determined by how long it will take to get from start to end (based on X). This is what i have so far get now() returns seconds since epoch var timepassed get now() myObj id .start seconds since epoch for departure var timeleft myObj id .end get now() seconds since epoch for arrival var journey time 60 this means 60 minutes total journey time var array 650,250 way points along the straight paths if(step 0 step lt array.length) var destinationx array step 0 var destinationy array step 1 else if( step array.length) var destinationx 250 var destinationy 100 else var destinationx myObj id .startx var destinationy myObj id .starty step When the user logs in at any given time, the object needs to be drawn in the correct place of the path, almost as if its been travelling along the path whilst the user has not been at the PC with the available information i have above. How do I do this? Note The camera angle in the game is a birds eye view so its a straight forward X Y rather than isometric angles. |
2 | determine collision angle on a rotating body update new diagram and updated description I have a contact listener set up to try and determine the side that a collision happened at relative to the a bodies rotation. One way to solve this is to find the value of the yellow angle between the red and blue vectors drawn above. The angle can be found by taking the arc cosine of the dot product of the two vectors (Evan pointed this out). One of my points of confusion is the difference in domain of the atan2 function html canvas coordinates and the Box2d rotation information. I know I have to account for this somehow... SS below questions Does Box2D provide these angles more directly in the collision information? Am I even on the right track? If so, any hints? I have the following javascript so far Ship.prototype.onCollide function (other ent,cx,cy) var pos this.body.GetPosition() collision position relative to body var d cx pos.x cx var d cy pos.y cy length of initial vector var len Math.sqrt(Math.pow(pos.x cx,2) Math.pow(pos.y cy,2)) body angle can over rotate hence mod 2 Pi var ang this.body.GetAngle() (Math.PI 2) vector representing body's angle same magnitude as the first var b vx len Math.cos(ang) var b vy len Math.sin(ang) dot product of the two vectors var dot prod d cx b vx d cy b vy new calculation of difference in angle NOT WORKING! var d ang Math.acos(dot prod) var side if (Math.abs(d ang) lt Math.PI 2 ) side "front" else side "back" console.log("length",len) console.log("pos ",pos.x,pos.y) console.log("offs ",d cx,d cy) console.log("body vec",b vx,b vy) console.log("body angle ",ang) console.log("dot product",dot prod) console.log("result ",d ang) console.log("side",side) console.log(" ") |
2 | Creating HTML5 Canvas Objects in Javascript I'm currently trying to learn how to make HTML5 Canvas games with JavaScript. I would like to use object oriented JavaScript to manage the elements of the game, but i'm having trouble. I've done a lot of research already, but there seems to be a million ways of doing everything and no one source has been able to provide me with the information I think I need in order to get the result I think I want. More specifically I'm having trouble utilizing object prototypes. I've started out by creating the canvas in my code like so var body document.getElementsByTagName("body") 0 var canvas document.createElement('canvas') body.appendChild(canvas) My thought process has lead me to thinking that I should make an object out of this so I can use this dynamically later on if needed. So i've implemented it like so. var gamearea function() this.generate function() var body document.getElementsByTagName("body") 0 var canvas document.createElement('canvas') body.appendChild(canvas) I know that I will probably need multiple contexts of the canvas element going forward, so I'm thinking that I should create a prototype for this like so. var context function() return canvas.getContext('2d') My thinking is that I can then ceate the objects for the context I need by instating them with there prototypes like so. var background Object.create(context) var foreground Object.create(context) But in order to assign IDs to these objects so I can reference them for drawing on later, I need to assign IDs to them. I found a blog that indicated the proper formatting would mean implementing the following. var background Object.create(context, id value 'background' ) var foreground Object.create(context, id value 'foreground' ) So my question is this. Is there a way to incorporate more unified formatting to all of this? Id like to establish this prototypes with their id's beforehand like I did with the gamearea object. I want to avoid giving objects properties inline. I am doing this right? Is there a better way? I'm I a complete idiot? Thank you very much for your time on this guys, I really appreciate it. ) |
2 | How can I get a property of an entity without having to call getEntityByType every time? I'm trying to get an entity (a bullet, a grenade, and an explosive) from my player. Specifically, I want the shootingRate of my bullet (how frequently it can be fired). How can I do this without having to call getEntityByType each time I fire this projectile? There has got to be a cleaner way from what I'm doing right now, which is Shooting var isShooting ig.input.state('shoot') if (isShooting amp amp this.lastShootTimer.delta() gt 0) switch (this.activeWeapon) case("EntityBullet") ig.game.spawnEntity(this.activeWeapon, this.pos.x, this.pos.y 10) var equipedWeap ig.game.getEntitiesByType(EntityBullet) this.lastShootTimer.set(equippedWeap.shootingRate) console.log(equipedWeap.shootingRate) break case("EntityGrenade") ig.game.spawnEntity(this.activeWeapon, this.pos.x, this.pos.y 5) var equipedWeap ig.game.getEntitiesByType(EntityGrenade) this.lastShootTimer.set(equipedWeap.shootingRate) console.log(EquipedWeap.shootingRate) break case("EntityExplosiveBomb") ig.game.spawnEntity(this.activeWeapon, this.pos.x, this.pos.y 5 ) var equipedWeap ig.game.getEntitiesByType(EntityExplosiveBomb) 0 this.lastShootTimer.set(equipedWeap.shootingRate) console.log(equipedWeap.shootingRate) break |
2 | Having trouble swapping elements I'm trying to visualize a simple Hanoi solver that uses an algorithm, and I'm swapping elements on array to visualize it. Here's my code let A let B let C let moveCount 0 let once true hanoi(3, A, C, B) 3, how many disk A C B are rods alert(A '. n' B '. n' C '.') function hanoi(n, start, target, other) if (once) once false for (var i 1 i lt n i ) start.push(i) if (n lt 1) let temp start n 1 start n 1 target target.length start start.filter(Boolean) target target.length temp target target.filter(Boolean) console.log('Moving disk ' n ' from rod ' start ' to ' target ' rod') moveCount else hanoi(n 1, start, other, target) let temp start n 1 start n 1 target target.length start start.filter(Boolean) target target.length temp target target.filter(Boolean) console.log('Moving disk ' n ' from rod ' start ' to rod ' target) moveCount hanoi(n 1, other, target, start) The C value should be expected 3, 2, 1 but only shows 2. I also checked A and B and 1 is nowhere to be found How do I make this properly so the output would be 3, 2, 1 Imagine 3 is the largest disk and so on... |
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 | Adding multiple animated sprites on canvas make the game FPS drop sharply I am using PIXI.js to build a html5 canvas game. Although this is PIXI.js specific question I think this may happen very often in HTML5 canvas games. I have placed hundreds of static sprites in my game and all goes well. But when I try to add 30 animated sprites (AI players) in the game, the FPS drops from 60 to 30. If I add even more it becomes very slow and unplayable. I have profiled my program on Chrome and found that this method CanvasSpriteRenderer.prototype.render is using too many CPU resources. Is there a way to reduce the CPU consumption and make my game smooth again? |
2 | Optimize DOM game performance I am working on a game developed on DOM using Crafty JS framework, and Greensock GSAP JS (http www.greensock.com gsap js ) for animations. It is my first time working with these technologies. I have a problem with FPS going down to 15 and less while animations are performed on bigger DOM elements. After investigating the issue with Chrome Developer Tools Timeline I discovered that 80 of bottleneck events time are Image Resize(non cached) I assume it is caused by the fact that I am using CSS Transform scale() for the game to adjust to browser size. Performance is acceptable once the scaling is disabled. Is there any way to cache the resized images in browser to improve performance? The game will only be used on a local computer. Any help and advice will be greatly appreciated. |
2 | Best way to do "cutscenes" I'm curious about the best way to display cutscenes in canvas. When I say cutscene I mean something like a static image fading from one to the other. Would it be best to use a timeout for a certain amount of seconds then go to the next image? Alternatively, would it be better to somehow use the main loop and increment a counter? If anyone has a method they use, post an answer! D |
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 | What is some game development literature purely in javascript? I'm mainly interested in the videogames development in pure javascript, since nowadays there's so many books about htm5 and javascript I couldn't find any book about game development with javascript only. |
2 | Separate shaders from HTML file in WebGL I'm ramping up on WebGL and was wondering what is the best way to specify my vertex and fragment shaders. Looking at some tutorials, the shaders are embedded directly in the HTML. (And referenced via an ID.) For example lt script id "shader 1 fs" type "x shader x fragment" gt precision highp float void main(void) ... lt script gt lt script id "shader 1 vs" type "x shader x vertex" gt attribute vec3 aVertexPosition uniform mat4 uMVMatrix ... My question is, is it possible to have my shaders referenced in a separate file? (Ideally as plain text.) I presume this is straight forward in JavaScript. Is there essentially a way to do this var shaderText LoadRemoteFileOnSever(' shaders shader 1.txt') |
2 | How to use apply class inheritance in Enchant.js You're developing a game using Enchant.js and you just need an Enemy class which multiple enemy classes derive from and every enemy has its own sprite and stuff. |
2 | Multilayer game HTML5 canvas I've have a problem with HTML5 canvas and using multiple layers. I'm using 3 layers. The first layer is where the player and the collision base objects are. And the second and the third layer have the rest of that objects, and that are suppose to cover the character if is behind them. But I have this problem The tile in the upper layer than the character cover him, even if he is in front of that object. And I have other problem When is a the back of the element, there's a part of the character that appears in the middle of the poster. How can I resolve this? I don't know how exactly do this, and I think that use layers is not very convenient. Here's how I render the map function drawMap () for (var rowCtr 0 rowCtr lt map.tileMap 0 .length rowCtr ) for (var colCtr 0 colCtr lt map.tileMap 0 0 .length colCtr ) var tileId map.tileMap 0 rowCtr colCtr 1 var sourceX Math.floor(tileId 8) 32 var sourceY Math.floor(tileId 8) 32 ctx.drawImage(map.sprite.img, sourceX, sourceY, 32, 32, colCtr 32, rowCtr 32, 32, 32) finn.movement(this.ctx, this.world) if (map.tileMap.length gt 1) for (var capa 1 capa lt map.tileMap.length capa ) for (var rowCtr 0 rowCtr lt map.tileMap 0 .length rowCtr ) for (var colCtr 0 colCtr lt map.tileMap 0 0 .length colCtr ) var tileId map.tileMap capa rowCtr colCtr 1 var sourceX Math.floor(tileId 8) 32 var sourceY Math.floor(tileId 8) 32 ctx.drawImage(map.sprite.img, sourceX, sourceY, 32, 32, colCtr 32, rowCtr 32, 32, 32) And here's an example of the map 0, 0, 0, 0 , 0, 0, 0, 0 , 0, 0, 0, 0 , 0, 1, 1, 0 , 0, 0, 0, 0 , 0, 1, 1, 0 , 0, 1, 1, 0 , 0, 0, 0, 0 That's the array of the layers. The first is the first layer, where the character moves, and the second element is the layer where the part of the objects which cover are drew. Is there any solution for this without using any external Engine, only using canvas and javascript? Thanks advance! |
2 | How do I respond to keyboard events which occur between polling? In my games update loop, which happens on a fixed timestep of 30 times per second, I am checking the current state of several keys to determine how to move the player. For example if(Keyboard.down(KEY LEFT) move character left This works fine in situations where I expect the player to hold the key down for extended periods (such as movement), but for things like shooting, where the player just taps the key quickly, it doesn't always pick up the key being down. This is due to the key being both pressed and released in the gap between polling. Now obviously I don't want to trigger my shooting code 30 times a second like I do my moving code, so the solution needs to incorporate some kind of buffering delay mechanism to make sure each shot is still x milliseconds apart, but I need the first one to register immediately and with certainty. I am using Javascript, so I can easily use event driven functions linked to keypresses (in fact I am doing this already in order to keep track of which keys are down), but I didn't want to have game logic outside of the fixed timestep update. Can anyone suggest a solution? I'm not looking for code, more an idea of how to design structure the code around the problem. |
2 | Line strokes also adding borders to other shapes? When you run the project, you can see that the first circles have a black border around them. When I remove the Game.drawLines(), the circles don't have the border around them anymore. Any help is appreciated! |
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 | ImpactJS and Construct 2 I'm interested in HTML5 game development and I found about this 2 game engines, I already know ImpactJS requires more programming experience and that Construct 2 has its own event and action system that can be extended with plugins made with JavaScript. I want to know what are each engine's primary focus, when would someone choose one over the other assuming programming knowledge is not a concern. Is it a matter of taste, features available, type of game or is it that each tool serves better for some kind of games or development process?. I'm not looking to know which is better, just in which situations works better each tool, so people can have an idea of what's better for building the game they have in mind. |
2 | Copying section of map array I'm experimenting a bit with pathfinding. I'm using Javascript. I have a map array as follows mapArray 0, 0, 0, 1, 1, 0 , 1, 0, 0, 1, 0, 0 , 0, 1, 0, 1, 1, 0 , The map is fairly excessive in size and I would like to take out a portion of it to pass to the pathfinding algo. How could I go about doing this? From the above, I could take out a section to leave this for instance mapArray 0, 1, 1 , 0, 1, 0 , 0, 1, 1 , Which would be copying from 0,2 through to 1,4 (xy). My first thought was a for loop but it is failing for a reason I don't fully understand. Probably a misunderstanding of inserting into arrays? var pathfindingMapArray for ( y startRow y lt endRow y ) for ( x startColumn x lt endColumn x ) pathfindingMapArray y x mapArray y x The above fails as a TypeError. |
2 | Experience embedding javascript I'm looking into scripting languages to embed in my game. I've always assumed Lua was the best choice, but I've read some recent news about embedding V8 as was considering using it instead. My question is two fold Does anyone with experience embedding v8 (or another javascript engine) recommend it? How does it compare with embedding Lua? I like that v8 has a c embedding API. However Lua API has had lots of time to be refined (newer isn't always better and all that). Note At this point I'm not too concerned with which is better language or which library has better performance. I'm only asking about ease of embedding. |
2 | Manually updating HTML5 local storage? I'm just starting out HTML5 game developement (and game dev in general) and watching all the videos and tutorials available something has crossed my mind. Everyone keep saying I should set the cookie's (or cached files) to be expired after a certain amount of time. So that when it reaches that time the browser automatically downloads all assets again, even if it's the same asset's. Wouldn't it be possible to manually define the version of the game? For example the user has downloaded all the files for 1.01 of the game, when updating I change a simple variable to 1.02. When the user logs in it would compare his version to the current and if they are not equal only then it downloads the files? This could even be improved to download only specific files depending on what needs to be updated? Would this be possible or am I just dreaming? What are the possible downsides of this approach? |
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 | Is it bad practice to for the server to request data for a client from another client? I'm making a collaborative whiteboard app so that when someone is drawing and uses a rectangle for example, a rectangle packet is sent to the server with parameters like x, y, width, height, color and then that packet is sent to everyone else in the room so that a rectangle is drawn on their screen. So far everything works perfectly and there's also a stack on each client of all the commands thus far for infinite undo and redo. However, there server does not contain this stack because all it has to do is forward commands to clients in the room. Everything is working perfectly so far and everyone can see everyone else drawing in real time but I'd like to implement a feature where if someone joins a room late they can see the current whiteboard. That is, the entire command stack would have to be sent to someone. However, this data isn't stored on the server, but each client has their own (identical copy). Would it be bad for when someone joined to have the server ask one of the clients (which? round robin?) to send his command stack to the server and have the server forward it to the client? My concerns are the delay and teh amount of data being sent in one go (congestion). What do you all think? Are there any other options? |
2 | Is reobfuscating javascript every time the page is loaded a valid option for a multiplayer game? I am looking for ways to prevent cheating on a multiplayer browser game. I saw this answer where it was mentioned that obfuscation is not an effective technique. My plan is not only to obfuscate the code differently every time the page is loaded but periodically change the protocol that the client uses to communicate with the server. This would mean that even if they were able to deobfuscate the client side code, they would need to update the protocol every time I changed it or they wouldn't be able to communicate with the game servers. I know that this will be difficult to implement, but I believe that I can do it. Would this work? I know that it's impossible to outright prevent cheating, but I believe that this would make it extremely difficult. |
2 | Line strokes also adding borders to other shapes? When you run the project, you can see that the first circles have a black border around them. When I remove the Game.drawLines(), the circles don't have the border around them anymore. Any help is appreciated! |
2 | How do I query a server with visible map tiles? In my game, I need to retrieve data of items in the visible tiles based on what tiles are visible in the viewport. I am planning to make a batch AJAX request with the visible tiles, containing image tags like Google Maps. The item information will be in JSON format. What is the best approach for this? I currently have a class that determines the visible columns rows and offsets relative to the visible area shown. |
2 | How to make physics of motion on an inclined surface There is the following platform And a coin above it And the following code using arcade physics gravity y 100, x 10 , in config function preload () this.load.image('platform', 'assets platform.png') this.load.image('star', 'assets star.png') function create () platforms this.physics.add.staticGroup() platforms.create(400, 568, 'platform') player this.physics.add.sprite(100, 450, 'star') player.setCollideWorldBounds(true) The code is approximate, a coin above the platform, sprites in png format. But the coin falls and does not roll, but moves horizontally, after which it falls again. How to make it "roll"? UPD Will it help me? https github.com photonstorm phaser examples blob master examples arcade 20physics circle 20body.js And how to be with the platform? |
2 | Tips on how to architect your JavaScript game with classes OK, so I'm creating a lt canvas gt game using JavaScript (ES6 ) features like Classes. It's straight from the vue cli and webpack. So, I have these Classes with the following (and such) variables class Player this.x 1 this.y 5 this.name 'Guy' this.stats class Map this.level 1 this.config this.images Image() this.canvas null this.context null this.board From a tileset POINT OF ENTRY STARTS HERE const game new Game() class Game this.map null this.player null this.assets Images() The problem I'm having is that sometimes, I'm having to access a created object that was instantiated elsewhere. For example, this.player was instantiated inside the Game class. But in the Map class, I have the drawMouseSelection method where it needs the current Player's X and Y and Map's board array of tiles. For example, I pass the all of board 2500 to a static helper method in UI class to get the correct tile hovered on. What I am doing I just pass the whole object and deal with it as such. Am I passing too big of objects? |
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 | Browser board game and server push I want to start developing a browser game. Not for success, just for the sake of doing it and learning something from it. Now, a point where I have serious problems figuring out how to deal with it is how does one player receive message of another player does something that is somehow time critical. Easy example for a trading card game Player 1 plays The devious flames of hell and Player 2 has to react to this card by playing Watery waves directly afterwards, before the card of Player 1 takes effect (so to say a counter card). Of course, I could just request the server every second and see if the other player did something, but I was hoping for a less request frequent solution, like the server pushes the event of Player 1 playing a card to Player 2. |
2 | Cellbased maps explanation? I've been trying to understand cellbased maps and how they work, i have googled alot but can't seem to find any explanation for it. With cell based maps i mean the ones where you do height and everything like walls roof floor in each cell. If possible i would appreciate an explanation from a Javascript perspective, but only a theoretical explanation can do. So why do we use them? how do they work? Is it just like a normal array with more information? |
2 | How to determine where on a path my object will be at a given point in time? I have map and an obj that is meant to move from start to end in X amount of time. The movements are all straight lines, as curves are beyond my ability at the moment. So I am trying to get the object to move from these points, but along the way there are way points which keep it on a given path. The speed of the object is determined by how long it will take to get from start to end (based on X). This is what i have so far get now() returns seconds since epoch var timepassed get now() myObj id .start seconds since epoch for departure var timeleft myObj id .end get now() seconds since epoch for arrival var journey time 60 this means 60 minutes total journey time var array 650,250 way points along the straight paths if(step 0 step lt array.length) var destinationx array step 0 var destinationy array step 1 else if( step array.length) var destinationx 250 var destinationy 100 else var destinationx myObj id .startx var destinationy myObj id .starty step When the user logs in at any given time, the object needs to be drawn in the correct place of the path, almost as if its been travelling along the path whilst the user has not been at the PC with the available information i have above. How do I do this? Note The camera angle in the game is a birds eye view so its a straight forward X Y rather than isometric angles. |
2 | How can I delete an object when it's not stored in an array? I have a boss appearing in my game, but since it's only one character I didn't put it in an array. Now I'm trying to make disappear if its health is less or equal to 0 but I don't know how to do that. Is there a way to remove the object? I only know how to remove a property of an object. Here's the boss object function Boss1(x, y) this.sprite boss1Sprite this.x x this.y y this.imgWidth 160 this.imgHeight 224 this.frameWidth this.imgWidth 4 this.frameHeight this.imgHeight 4 this.health 1500 this.directionMode 1 this.currentFrame 0 this.SPEED 1 this.delta 1 this.updateFrame function () this.currentFrame 0.2 this.showHealth function () ctx.fillStyle "red" ctx.fillRect(this.x,this.y 10,(this.health 100) 3.3,5) ctx.strokeRect(this.x, this.y 10, (100 100) 50, 5) this.show function () this.updateFrame() this.walkingMode Math.floor(this.currentFrame) 4 ctx.drawImage(this.sprite, this.walkingMode this.frameWidth, this.directionMode this.frameHeight, this.frameWidth, this.frameHeight, this.x, this.y, this.frameWidth, this.frameHeight) target hero position this this.move function () this.dx hero.x this.x this.dy hero.y this.y this.length Math.sqrt(this.dx this.dx this.dy this.dy) if (this.length) this.dx this.dx this.length this.dy this.dy this.length this.x this.dx this.delta this.SPEED this.y this.dy this.delta this.SPEED enemy wave object function random(min, max) return Math.random() (max min) min function Enemy(x, y) this.sprite enemySprite this.x x this.y y this.imgWidth 128 this.imgHeight 192 this.frameWidth this.imgWidth 4 this.frameHeight this.imgHeight 4 this.toDelete false this.dx random(1, 3) this.enemiesHealth 100 this.directionMode 1 this.currentFrame 0 this.updateFrame function() this.currentFrame 0.2 this.showHealth function () ctx.fillStyle "red" ctx.fillRect(this.x,this.y 10,(this.enemiesHealth 100) 50,5) ctx.strokeRect(this.x, this.y 10, (100 100) 50, 5) this.show function() this.updateFrame() this.walkingMode Math.floor(this.currentFrame) 4 ctx.drawImage(this.sprite,this.walkingMode this.frameWidth, this.directionMode this.frameHeight, this.frameWidth, this.frameHeight, this.x, this.y, this.frameWidth, this.frameHeight ) this.move function() this.x this.x this.dx this.deletion function() this.toDelete true this is when the boss is spawning the game loop function draw() bullets bullets.filter((bullet) gt bullet.x lt viewLimit) enemies enemies.filter((enemy) gt enemy.x gt viewLimit1) while (enemies.length lt enemiesPerTick amp amp kills lt 5) var enemy new Enemy(canvas.width, random(0, canvas.height 60)) enemies.push(enemy) for (var v 0 v lt enemies.length v ) enemies v .showHealth() ctx.clearRect(0, 0, canvas.width, canvas.height) hero.show() hero.update() hero.showHealth() for (var i 0 i lt bullets.length i ) bullets i .show() bullets i .move() for (var j 0 j lt enemies.length j ) enemies j .show() enemies j .move() for (var t 0 t lt enemies.length t ) enemies t .showHealth() collision() drawScore() if (enemies.length 0) boss1.show() boss1.move() boss1.showHealth() requestAnimationFrame(draw) console.log(enemies, bullets) draw() |
2 | Box2dWeb setting velocity of bodies using events I would like to move a kinematic box by pressing the down arrow. As is noted by the console logs, the keydown actually does change the box's velocity... but for reasons beyond my grasp it still doesn't move. Note that if you place the SetLinearVelocity() call in a spot where it runs immediately, the box will move, but if it is in a setTimeout, or as in my example, called from an event, the box stays frozen despite its y velocity property changing to 1. I created the simplest example I could to show my problem. Note I am using the latest release of Box2dWeb std variables var b2Vec2 Box2D.Common.Math.b2Vec2 , b2BodyDef Box2D.Dynamics.b2BodyDef , b2Body Box2D.Dynamics.b2Body , b2FixtureDef Box2D.Dynamics.b2FixtureDef , b2Fixture Box2D.Dynamics.b2Fixture , b2World Box2D.Dynamics.b2World , b2PolygonShape Box2D.Collision.Shapes.b2PolygonShape , b2DebugDraw Box2D.Dynamics.b2DebugDraw create world and gravity var world new b2World( new b2Vec2(0, 10) , true ) fixture defs var fixDef new b2FixtureDef fixDef.density 1.0 fixDef.friction 0.5 fixDef.restitution .2 body defs var bodyDef new b2BodyDef fixDef.shape new b2PolygonShape fixDef.shape.SetAsBox(2,2) bodyDef.type b2Body.b2 kinematicBody bodyDef.position.x 3 bodyDef.position.y 0 body and fixture creation var body1 world.CreateBody(bodyDef) body1.CreateFixture(fixDef) "Before" console log console.log("Claimed velocity before down is pressed " body1.GetLinearVelocity().y) Listener and keycode switch for intended velocity change window.addEventListener("keydown", onKeyDown, false) function onKeyDown(e) switch(e.keyCode) case 40 down body1.SetLinearVelocity(new b2Vec2(0,1)) console.log("Claimed velocity after down is pressed " body1.GetLinearVelocity().y) debug drawing var debugDraw new b2DebugDraw() debugDraw.SetSprite(document.getElementById("canvas").getContext("2d")) debugDraw.SetDrawScale(30.0) debugDraw.SetFillAlpha(0.5) debugDraw.SetLineThickness(1.0) debugDraw.SetFlags(b2DebugDraw.e shapeBit b2DebugDraw.e jointBit) world.SetDebugDraw(debugDraw) window.setInterval(update, 1000 60) loop function update() world.Step(1 60, 10, 10) world.DrawDebugData() world.ClearForces() |
2 | Any way to set drag events on a phaser 3 group? I'm trying to set a drag event on a phaser 3 group, but I wasn't able to achieve what I want. I was reading some phaser 2 blogs, and they said that it isn't possible to set a group a drag event. Can somebody help me with this? It's really impossible to set a drag event to a group? |
2 | Using EaselJS, my spritesheet based map is not showing up I have a random map that generates based on a level and a set of Tile ID's, constructed using a Height Map generator I wrote using the BitmapData extension. I've confirmed that the Tile IDs are generated correctly and can be modified to cycle through a set of tiles and changing circumstances. The actual base image that holds the tiles is loaded and I was able to draw it separately. However... after I update the stage when the function finishes building, I don't see any map at all and I don't understand why. I've tried to add to a container and to the stage directly, neither method is working. Could anyone identify the problem? function buildBackground() var mapSeed Math.round(Math.random() 2) var channel Object.create(createjs.BitmapDataChannel) var channelOptions channel.RED channel.GREEN channel.BLUE var offsets new createjs.Point(0, 0), new createjs.Point(0, 0) var interpolateType "cos" var TileMap new Array() accessMap new createjs.BitmapData(null, 200, 200) accessMap.perlinNoise(100, 100, 6, mapSeed, true, false, channelOptions, true, offsets, interpolateType) var BitmapLayout new createjs.Bitmap(accessMap.canvas) BitmapLayout.scaleX 5 BitmapLayout.scaleY 4 BitmapLayout.x 0 BitmapLayout.y 0 var gridSizeX 10 var gridSizeY 7 heightMap new Array() for (x 0 x lt gridSizeX x ) heightMap x new Array() for (y 0 y lt gridSizeY y ) heightMap x y 0 var pixelPoint new createjs.Point() var darkest pixel 1 var brightest pixel 0 for (x 0 x lt gridSizeX x ) for (y 0 y lt gridSizeY y ) pixelPoint.x Math.round((x gridSizeX) accessMap.width) 1 pixelPoint.y Math.round((y gridSizeY) accessMap.height) 1 heightMap x y accessMap.getPixel(pixelPoint.x, pixelPoint.y) heightMap x y 0xffffff if (heightMap x y lt darkest pixel) darkest pixel heightMap x y heightMap x y Math.round(heightMap x y (Math.random() 3)) for (x 0 x lt gridSizeX x ) TileMap x new Array() for (y 0 y lt gridSizeY y ) TileMap x y 0 TileMap x y Math.round(heightMap x y (Math.random() 5)) var bitmap new createjs.Bitmap(preload.getResult("BackgroundTiles")) var BackgroundTileObjData images bitmap , frames width 100, height 100 var BackgroundTileInfo new createjs.SpriteSheet(BackgroundTileObjData) var frameSize 100 var graphic new createjs.Graphics() for (x 0 x lt gridSizeX x ) for (y 0 y lt gridSizeY y ) var TileID TileMap x y var levelModifier 1 var tile new createjs.Sprite(BackgroundTileInfo) tile.gotoAndStop(TileID) tile.x 100 x tile.y 100 y stage.addChild(tile) stage.update() console.log("Tile SpriteSheet?") |
2 | How to disable touch in Quintus? I'm trying to build card game using the Quintus game engine. I have objects called Card. I can touch and drag it in the screen but I want just to touch and drag it one time but I can't figure out how to disable the touch after I dragged the card and I try to Google it but no luck. My code Q.Sprite.extend("Card", init function(p) this. super(p, asset "Queen OF Hearts.png", x Q.el.width 2, y Q.el.height 120 ) this.on("drag") this.on("touchEnd") , drag function(touch) this.p.dragging true this.p.x touch.origX touch.dx this.p.y touch.origY touch.dy , touchEnd function(touch) this.p.dragging false put a line on the screen if the card pass it put the card in the new position if not put the card in the orginal(old) postion if(touch.origY touch.dy gt Q.el.height 200) define the line that the card should pass if the amount of draged gt the screen line in Q.el.height 200 put the card in the same old postion if is not pass the line this.p.x touch.origX this.p.y touch.origY else put the card if it pass the line in the new postion this.p.x Q.el.width 2 this.p.y Q.el.height 280 ) so in the else statement in the touchEnd I'm trying to do some thing like that this.p.touch false but is not working. |
2 | Timers check in game loop, or run independently? Specifically talking in the context of JavaScript game development. For example, I can use the language specific timeout mechanism Timeout is not tied to game loop at all, tied to language specific timer loop setTimeout(() gt player.age 1, 1000) Or I can create some custom game timer game.createFixedDelayTimer(() gt player.age 1, 1000) In update loop let lastTimerCheckTime Date.now() function update(game) checkTimers(game, lastTimerCheckTime) Fire timer if specified delay has passed. lastTimerCheckTime Date.now() The disadvantage to approach 2 is that the checks are less granular... but maybe it's still desirable so that game behavior is deterministic? |
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 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 | Javascript Eventlistener 'keydown' not registering all keys pressed when holding down other keys Sollution provided in the comments. The issue is that my keyboard has what is called ghosting issues, this means it doesn't support some key combinations when pressed together. When the user holds 's' and 'd' key at the same time (movement keys, so character would move south east), and during this presses the 'n' or 'm' key, the keydown event of the 'n' and 'm' key is not triggered. This happens with other key combinations as well, but not with all. Per example holding down the 'w' and 'a' key will trigger the 'n' and 'm' keydown events. Is there a way to allow any keydown event to be triggered, regardless of other keys pressed? You can test this behavior using the following code document.addEventListener('keydown', (e) gt console.log(e.key) ) |
2 | How to draw a tileset using HTML5 canvas? I have a tileset something like this 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 My tileset draw code looks like this var image new Image() image.src '32x32.png' var tile 5 var tileSize 32 var x 100 var y 100 context.drawImage(image, Math.floor(tile tileSize), 0, tileSize, tileSize, x, y, tileSize, tileSize) And this code draws the 5 tile, but how would I draw the 10 tile, or the 15 tile without adding tileX and tileY? I probably need something like if tile is equal to 15, then draw tile 15. |
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 | UV texture mapping with perspective correct interpolation I am working on a software rasterizer for educational purposes and I am having issues with the texturing. The problem is, only one face of the cube gets correctly textured. The rest are stretched edges You can see the running program online here. I have used cartesian coordinates, and all I do is interpolate the uv values along the scanlines. The general formula I use for interpolating the uv coordinates is pretty much the one I use for the z buffering interpolation and looks like this (in this case for horizontal scanlines) u Slope (right.u left.u) (triangleRight x triangleLeft x) v Slope (right.v left.v) (triangleRight x triangleLeft x) ... new u left.u ((currentX onScanLine triangleLeft x) u Slope) new v left.v ((currentX onScanLine triangleLeft x) v Slope) Then, when I add each point to the pixel buffer, I restore z and uv z (1 z) uv.u Math.round(uv.u z 100) 100 because my texture is 100x100px uv.v Math.round(uv.v z 100) Then I turn the u v indexes into one index in order to fetch the correct pixel from the image data (which is a 1 dimensional px array) var index texture.width uv.u uv.v and the rest is unimportant imagedata index .RGBA bla bla The interpolation formula is correct considering the consistency of the texture (including the straight stripes). I must get some sleep now, but before I get into further dissecting of every single value to see what goes wrong, Can someone more experienced guess why might this be happening, just by looking at the cube? "I have no idea what I'm doing" (it's my first time implementing a rasterizer). Did I miss an important stage? Thanks for any insight. PS My UV values are as follows u 0, v 0 , u 0, v 0.5 , u 0.5, v 0.5 , u 0.5, v 0 , u 0, v 0 , u 0, v 0.5 , u 0.5, v 0.5 , u 0.5, v 0 EDIT The uv values were to blame, and pixel 50 being in the second zone, as Victor pointed out. My new uv values u 0, v 0 , u 0, v 1 , u 1, v 1 , u 1, v 0 , u 1, v 0 , u 1, v 1 , u 0, v 1 , u 0, v 0 To some extent this was "a bug in my code", but also I had overlooked an important part of the process the uv values should not just be assigned to the 8 corners of the cube. |
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 | Phaser Scaling to fill screen, maintain pixel ratio, but not aspect ratio I've used libraries in other languages before that provide different types of scaling via viewport types. The best example of what I want is from a library called libgdx for Java, their ScreenViewport. The ScreenViewport does not have a constant virtual screen size it will always match the window size which means that no scaling happens and no black bars appear. A player with a bigger screen might see more of the game than a player with a smaller screen size. Essentially what I want is to Fill the screen meaning that there's no black bars or the sides of the game Maintain the pixel ratio meaning that every in game pixel is equal to one pixel on screen, so no stretching Not maintain aspect ratio meaning that it doesn't matter to my game what the aspect ratio of the game is. Its job is to forget about aspect ratio and follow the above two criteria The way how I'm achieving this is by using Phaser's EXACT FIT scaling type so that the canvas automatically resizes to fit the window. Then upon resizing, I update the size of the camera and the game's renderer so that they match the new canvas size. Here's the code I have in my create function. this.scale.scaleMode Phaser.ScaleManager.EXACT FIT Phaser.ScaleManager.SHOW ALL USER SCALE this.scale.pageAlignHorizontally true this.scale.pageAlignVertically true this.scale.setResizeCallback(function () var width window.innerWidth var height window.innerHeight console.log('size ' width ', ' height) this.camera.setSize(width, height) this.game.renderer.resize(width, height) , this) It works fantastic in the horizontal axis, but when the window shrinks vertically, there is some vertical stretching of the pixels. Here's a working example of my issue http shooty.us.to scale And here's the code on GitHub, in case it's of any help. https github.com qwertysam space game Thank you for reading, any help is appreciated! EDIT I've isolated the issue, it appears to be that when the game is initially created, the height that I specify is the initial height of the canvas. e.g. var game new Phaser.Game(16 80, 9 80, Phaser.AUTO, '') Phaser's scaling method allows the canvas to grow in height, but not to shrink in height. The renderer is rendering to a much taller canvas (which goes off screen) than expected, therefore causing the vertical stretching. Any thoughts on how I can shrink the canvas myself, or would that conflitch with Phaser's ScaleManager? Thanks! |
2 | Phaserjs, filters, save to image cache I've tried to apply a Pixi filter to a image and save it to cache but the image doesn't get saved with the filter. colorMatrix new PIXI.ColorMatrixFilter() colorMatrix.matrix 0,0.0,0.5, 0.2, 0,0,1.0, 0.2, 0.0,0.0,0.5, 0.2, 0.0,0.0,0.0,1 image game.make.bitmapData() image.load("testImage") image.filters colorMatrix game.cache.addBitmapData("testImageWIthFilter", image) Is it not possible to save it to cache? The only thing I see is the original image when using the code down below messageImage game.add.sprite(0, 0, game.cache.getBitmapData('testImageWIthFilter')) |
2 | Lighting effects with 2D sprites I would like to know how to best achieve lighting effects with 2D. I guess the only way is to make sprites of the area to be lit in specific colors? Say I have a streetlamp, and around this place sprites to make it appear lit? Is there a better way? Edit Found a good screenshot of what I'm looking for http www.saltgames.com wp content uploads 2009 11 multipleLights.png |
2 | Is there any reason for doing back face culling in software? I, a newbie, have been doing back face culling in javascript for my WebGL app because I didn't know gl.cullFace() existed. Is there any reason to use software based culling instead of just passing all faces to GPU and let it do the culling? |
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 | Rotate arrow on canvas I need to draw a flow dynamically based on some user choices. In that flow I want to draw the choices (blue circles with number) and the directions of that choices (line and arrow). For example node 1 to node 2. JSFiddle Example To draw the direction I draw a arrow in the end of the line but I can't make the arrow rotate around itself. JS code (document).ready(function () drawOnCanvas() ) function drawOnCanvas() var canvas document.getElementById('myCanvas') if (canvas.getContext) var ctx canvas.getContext("2d") var circle1 x 75, y 75, r 15 var circle2 x 225, y 50, r 15 var arrow h 5, w 10 drawCircle(ctx, circle1, "1") drawCircle(ctx, circle2, "2") var ptCircle1 getPointOnCircle(circle1.r, circle1, circle2) var ptCircle2 getPointOnCircle(circle2.r, circle2, circle1) var ptArrow getPointOnCircle(circle2.r arrow.w, circle2, circle1) drawLine(ctx, ptCircle1, ptCircle2) drawArrow(ctx, arrow, ptArrow, ptCircle2) function drawArrow(canvasContext, arrow, ptArrow, endPt) var angleInDegrees getAngleBetweenPoints(ptArrow, endPt) canvasContext.beginPath() first save the untranslated unrotated context canvasContext.save() move the rotation point to the center of the rect canvasContext.translate(ptArrow.x, ptArrow.y) rotate the rect canvasContext.rotate(angleInDegrees) canvasContext.moveTo(endPt.x, endPt.y) canvasContext.lineTo(endPt.x arrow.w, endPt.y arrow.h) canvasContext.lineTo(endPt.x arrow.w, endPt.y arrow.h) canvasContext.closePath() canvasContext.fillStyle "rgb(72,72,72)" canvasContext.stroke() canvasContext.fill() restore the context to its untranslated unrotated state canvasContext.restore() function drawCircle(canvasContext, circle, text) canvasContext.beginPath() come a ou reinicia o desenho de algo canvasContext.fillStyle "rgb(43,166,203)" canvasContext.arc(circle.x, circle.y, circle.r, 0, 2 Math.PI, false) cria arcos canvasContext.fill() atribui estilos drawText(canvasContext, circle, text) function drawText(canvasContext, circle, text) canvasContext.font '8pt Calibri' canvasContext.fillStyle 'white' canvasContext.textAlign 'center' canvasContext.fillText(text, circle.x, circle.y 3) function drawLine(canvasContext, startPt, endPt) canvasContext.moveTo(startPt.x, startPt.y) canvasContext.lineTo(endPt.x, endPt.y) canvasContext.stroke() function getPointOnCircle(radius, originPt, endPt) var angleInDegrees getAngleBetweenPoints(originPt, endPt) Convert from degrees to radians via multiplication by PI 180 var x radius Math.cos(angleInDegrees Math.PI 180) originPt.x var y radius Math.sin(angleInDegrees Math.PI 180) originPt.y return x x, y y function getAngleBetweenPoints(originPt, endPt) var interPt x endPt.x originPt.x, y endPt.y originPt.y return Math.atan2(interPt.y, interPt.x) 180 Math.PI I think the problem is in drawArrow() method in the lines canvasContext.translate(ptArrow.x, ptArrow.y) canvasContext.rotate(angleInDegrees) I already tried every possible values for the rotation and the translation but arrow still don't rotate properly around itself. Can anyone help me? |
2 | animating a spritesheet using crafty.js this is my jsfiddle http jsfiddle.net seekpunk ek6ub4u5 1 i don't understand what i am missing it's been three days now working and trying to do the animation but i am stuck Crafty.sprite(128, "https 0.s3.envato.com files 42440549 1 Ninja.jpg", idle 1, 0 ) i've loaded the spriteseet image and declare idle Crafty.c("animation", init function () this.requires("SpriteAnimation") this.animate("run", 1, 1, 4) this.bind("enterframe", function () if (!this.isPlaying("run")) this.animate("run", 20) ) ) then i have declared the animation component and the bindframe function var player Crafty.e("2D,Canvas,idle, animation") .attr( x 0, y ch 128, w 128, h 128 ) then i've declared the player ,but sadly the animation is not working .. can anyone tell me what i am missing please |
2 | Handling input through callbacks or through game loop? I've tried to figure out how to handle player input properly, but without luck so far. As far as I have figured out, I can either Call the respective methods directly through the callback fired when an input event is detected. Or Save the input in an array and detect it through my main loop. I would like some thoughts on this in terms of if there is any restrictions benefits using one over the other. |
2 | p2.js body position is NaN when spawned inside of each other I'm working on a project for which I need a physics engine. At the moment I'm playing around with p2.js but I'm running into a problem When I try to create multiple bodies (circles and or boxes) which overlap the positions are set to NaN as soon as world.step() is called. The bodies have a mass of 5 and are dynamic. In very rare occasions it does actually work. How can I make sure it works every time? Do I have to wait for the bodies to be initialized? 4 circles before the simulation starts, once world.step is called the positions of these circles is NaN var world new p2.World( gravity 0, 9.82 ) function PhysicsBody(type, x, y, widthOrRadius, height) this.body new p2.Body( mass 5, position x, y , ) this.type type if (this.type 'rectangle') this.shape new p2.Box( width widthOrRadius, height height ) else if (this.type 'circle') this.shape new p2.Circle( radius widthOrRadius ) this.body.addShape(this.shape) world.addBody(this.body) var bod1 new PhysicsBody('circle', 0, 0, 32) var bod2 new PhysicsBody('circle', 10, 0, 32) |
2 | Rotate arrow on canvas I need to draw a flow dynamically based on some user choices. In that flow I want to draw the choices (blue circles with number) and the directions of that choices (line and arrow). For example node 1 to node 2. JSFiddle Example To draw the direction I draw a arrow in the end of the line but I can't make the arrow rotate around itself. JS code (document).ready(function () drawOnCanvas() ) function drawOnCanvas() var canvas document.getElementById('myCanvas') if (canvas.getContext) var ctx canvas.getContext("2d") var circle1 x 75, y 75, r 15 var circle2 x 225, y 50, r 15 var arrow h 5, w 10 drawCircle(ctx, circle1, "1") drawCircle(ctx, circle2, "2") var ptCircle1 getPointOnCircle(circle1.r, circle1, circle2) var ptCircle2 getPointOnCircle(circle2.r, circle2, circle1) var ptArrow getPointOnCircle(circle2.r arrow.w, circle2, circle1) drawLine(ctx, ptCircle1, ptCircle2) drawArrow(ctx, arrow, ptArrow, ptCircle2) function drawArrow(canvasContext, arrow, ptArrow, endPt) var angleInDegrees getAngleBetweenPoints(ptArrow, endPt) canvasContext.beginPath() first save the untranslated unrotated context canvasContext.save() move the rotation point to the center of the rect canvasContext.translate(ptArrow.x, ptArrow.y) rotate the rect canvasContext.rotate(angleInDegrees) canvasContext.moveTo(endPt.x, endPt.y) canvasContext.lineTo(endPt.x arrow.w, endPt.y arrow.h) canvasContext.lineTo(endPt.x arrow.w, endPt.y arrow.h) canvasContext.closePath() canvasContext.fillStyle "rgb(72,72,72)" canvasContext.stroke() canvasContext.fill() restore the context to its untranslated unrotated state canvasContext.restore() function drawCircle(canvasContext, circle, text) canvasContext.beginPath() come a ou reinicia o desenho de algo canvasContext.fillStyle "rgb(43,166,203)" canvasContext.arc(circle.x, circle.y, circle.r, 0, 2 Math.PI, false) cria arcos canvasContext.fill() atribui estilos drawText(canvasContext, circle, text) function drawText(canvasContext, circle, text) canvasContext.font '8pt Calibri' canvasContext.fillStyle 'white' canvasContext.textAlign 'center' canvasContext.fillText(text, circle.x, circle.y 3) function drawLine(canvasContext, startPt, endPt) canvasContext.moveTo(startPt.x, startPt.y) canvasContext.lineTo(endPt.x, endPt.y) canvasContext.stroke() function getPointOnCircle(radius, originPt, endPt) var angleInDegrees getAngleBetweenPoints(originPt, endPt) Convert from degrees to radians via multiplication by PI 180 var x radius Math.cos(angleInDegrees Math.PI 180) originPt.x var y radius Math.sin(angleInDegrees Math.PI 180) originPt.y return x x, y y function getAngleBetweenPoints(originPt, endPt) var interPt x endPt.x originPt.x, y endPt.y originPt.y return Math.atan2(interPt.y, interPt.x) 180 Math.PI I think the problem is in drawArrow() method in the lines canvasContext.translate(ptArrow.x, ptArrow.y) canvasContext.rotate(angleInDegrees) I already tried every possible values for the rotation and the translation but arrow still don't rotate properly around itself. Can anyone help me? |
2 | Anti cheat Javascript for browser HTML5 game I'm planning on venturing on making a single player action rpg in js html5, and I'd like to prevent cheating. I don't need 100 protection, since it's not going to be a multiplayer game, but I want some level of protection. So what strategies you suggest beyond minify and obfuscation? I wouldn't bother to make some server side simple checking, but I don't want to go the Diablo 3 path keeping all my game state changes on the server side. Since it's going to be a rpg of sorts I came up with the idea of making a stats inspector that checks abrupt changes in their values, but I'm not sure how it consistent and trusty it can be. What about variables and functions escopes? Working on smaller escopes whenever possible is safer, but it's worth the effort? Is there anyway for the javascript to self inspect it's text, like in a checksum? There are browser specific solutions? I wouldn't bother to restrain it for Chrome only in the early builds. |
2 | Maintaining relative location of objects across different screen resolutions I'm developing a very simple interactive HTML5 game, in which I need to show a room having multiple objects like a cupboard, table, fan etc. How can I display all of the objects together, so that they remain at same place, on all screen resolutions? |
2 | Is it bad practice to for the server to request data for a client from another client? I'm making a collaborative whiteboard app so that when someone is drawing and uses a rectangle for example, a rectangle packet is sent to the server with parameters like x, y, width, height, color and then that packet is sent to everyone else in the room so that a rectangle is drawn on their screen. So far everything works perfectly and there's also a stack on each client of all the commands thus far for infinite undo and redo. However, there server does not contain this stack because all it has to do is forward commands to clients in the room. Everything is working perfectly so far and everyone can see everyone else drawing in real time but I'd like to implement a feature where if someone joins a room late they can see the current whiteboard. That is, the entire command stack would have to be sent to someone. However, this data isn't stored on the server, but each client has their own (identical copy). Would it be bad for when someone joined to have the server ask one of the clients (which? round robin?) to send his command stack to the server and have the server forward it to the client? My concerns are the delay and teh amount of data being sent in one go (congestion). What do you all think? Are there any other options? |
2 | How can i fix "get transform can only be called from the main thread" error in my code? Here's my code var forward transform.TransformDirection(Vector3.forward) var input Input.GetAxis("Vertical") function Update() transform.position forward input Time.deltaTime transform.Rotate( 0 , Input.GetAxis("Horizontal") 45 Time.deltaTime , 0 ) I keep getting this error get transform can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function. |
2 | How to encode a save game game state as a string? I'm building an HTML game. For this game I want to implement a save feature that should work like in some already existing games The user can chose export, this will create a string, representing the game state (I guess). This string can be pasted into an import input and will load the save game. I thought about storing the state in a JSON, minifying it, stringifying and encoding it in Base64. But I don't think this is a good idea, users could easily cheat in this game by decoding the string, changing whatever they want, encoding it again and loading this string. I already tried generating save files in games with this feature and decoding them in Base64 which didn't work, so I assume they use a different encoding. How can I encode the JSON like this? |
2 | How can I detect and compensate for system related lag? The best example I can think of is Doom 3. It seemed to me that if there was any kind if lag the game would pause and then resume without "fast forwarding" to catch up. I'm trying to figure out a good practice to use for lag detection in JavaScript. |
2 | HTML5 check if font has loaded At present I load my font for my game in with font face For instance font face font family 'Orbitron' src url('res orbitron medium.ttf') and then reference it throughout my JS implementation as such ctx.font "12pt Orbitron" where ctx is my 2d context from the canvas. However, I notice a certain lag time while the font is downloaded to the user. Is there a way I can use a default font until it is loaded in? Edit I'll expand the question, because I hadn't taken the first comment into account. What would the proper method of handling this be in the case that a user has disabled custom fonts? |
2 | Using Racing Wheel force feedback with a JavaScript game I have a Thrustmaster T80 Racing Wheel that I am using while developing an online game with ThreeJS. I have already made it so I can drive the car with the wheel and the game knows when I crash the car. But looking online I couldn't find a way to make the wheel 'rumble' or shake when the car crashes. The wheel does support this on other (downloaded exe) games but it would be amazing if it was possible to achieve in a JS game, but I couldn't find any mention of doing this online. |
2 | Can a .exe file ported from a program like NW.js or Electron be put console stores? I'm early in development working on a game in HTML5 JavaScript canvas, and I wondering if porting the game with some HTML JS to .EXE converter would allowed it to be posted on consoles? I think it should be possible, since Downwell(though made with an entirely different language) is a .EXE file, and is available on Switch and Playstation. |
2 | How to make Pong ai paddle? I'm trying to make an ai so the paddles will move to position before the ball reaches it. I'm not sure how to go about it in this case. Here's the game http cssdeck.com labs ping pong game tutorial with html5 canvas and sounds Function to increase speed after every 5 points function increaseSpd() if(points 4 0) if(Math.abs(ball.vx) lt 15) ball.vx (ball.vx lt 0) ? 1 1 ball.vy (ball.vy lt 0) ? 2 2 Track the position of mouse cursor function trackPosition(e) mouse.x e.pageX mouse.y e.pageY Function to update positions, score and everything. Basically, the main game logic is defined here function update() Update scores updateScore() Move the paddles on mouse move if(mouse.x amp amp mouse.y) for(var i 1 i lt paddles.length i ) p paddles i p.x mouse.x p.w 2 Move the ball ball.x ball.vx ball.y ball.vy Collision with paddles p1 paddles 1 p2 paddles 2 If the ball strikes with paddles, invert the y velocity vector of ball, increment the points, play the collision sound, save collision's position so that sparks can be emitted from that position, set the flag variable, and change the multiplier if(collides(ball, p1)) collideAction(ball, p1) else if(collides(ball, p2)) collideAction(ball, p2) else Collide with walls, If the ball hits the top bottom, walls, run gameOver() function if(ball.y ball.r gt H) ball.y H ball.r gameOver() else if(ball.y lt 0) ball.y ball.r gameOver() If ball strikes the vertical walls, invert the x velocity vector of ball if(ball.x ball.r gt W) ball.vx ball.vx ball.x W ball.r else if(ball.x ball.r lt 0) ball.vx ball.vx ball.x ball.r If flag is set, push the particles if(flag 1) for(var k 0 k lt particlesCount k ) particles.push(new createParticles(particlePos.x, particlePos.y, multiplier)) Emit particles sparks emitParticles() reset flag flag 0 Function to check collision between ball and one of the paddles function collides(b, p) if(b.x ball.r gt p.x amp amp b.x ball.r lt p.x p.w) if(b.y gt (p.y p.h) amp amp p.y gt 0) paddleHit 1 return true else if(b.y lt p.h amp amp p.y 0) paddleHit 2 return true else return false Do this when collides true function collideAction(ball, p) ball.vy ball.vy if(paddleHit 1) ball.y p.y p.h particlePos.y ball.y ball.r multiplier 1 else if(paddleHit 2) ball.y p.h ball.r particlePos.y ball.y ball.r multiplier 1 points increaseSpd() if(collision) if(points gt 0) collision.pause() collision.currentTime 0 collision.play() particlePos.x ball.x flag 1 Function for emitting particles function emitParticles() for(var j 0 j lt particles.length j ) par particles j ctx.beginPath() ctx.fillStyle "white" if (par.radius gt 0) ctx.arc(par.x, par.y, par.radius, 0, Math.PI 2, false) ctx.fill() par.x par.vx par.y par.vy Reduce radius so that the particles die after a few seconds par.radius Math.max(par.radius 0.05, 0.0) |
2 | Box2dWeb setting velocity of bodies using events I would like to move a kinematic box by pressing the down arrow. As is noted by the console logs, the keydown actually does change the box's velocity... but for reasons beyond my grasp it still doesn't move. Note that if you place the SetLinearVelocity() call in a spot where it runs immediately, the box will move, but if it is in a setTimeout, or as in my example, called from an event, the box stays frozen despite its y velocity property changing to 1. I created the simplest example I could to show my problem. Note I am using the latest release of Box2dWeb std variables var b2Vec2 Box2D.Common.Math.b2Vec2 , b2BodyDef Box2D.Dynamics.b2BodyDef , b2Body Box2D.Dynamics.b2Body , b2FixtureDef Box2D.Dynamics.b2FixtureDef , b2Fixture Box2D.Dynamics.b2Fixture , b2World Box2D.Dynamics.b2World , b2PolygonShape Box2D.Collision.Shapes.b2PolygonShape , b2DebugDraw Box2D.Dynamics.b2DebugDraw create world and gravity var world new b2World( new b2Vec2(0, 10) , true ) fixture defs var fixDef new b2FixtureDef fixDef.density 1.0 fixDef.friction 0.5 fixDef.restitution .2 body defs var bodyDef new b2BodyDef fixDef.shape new b2PolygonShape fixDef.shape.SetAsBox(2,2) bodyDef.type b2Body.b2 kinematicBody bodyDef.position.x 3 bodyDef.position.y 0 body and fixture creation var body1 world.CreateBody(bodyDef) body1.CreateFixture(fixDef) "Before" console log console.log("Claimed velocity before down is pressed " body1.GetLinearVelocity().y) Listener and keycode switch for intended velocity change window.addEventListener("keydown", onKeyDown, false) function onKeyDown(e) switch(e.keyCode) case 40 down body1.SetLinearVelocity(new b2Vec2(0,1)) console.log("Claimed velocity after down is pressed " body1.GetLinearVelocity().y) debug drawing var debugDraw new b2DebugDraw() debugDraw.SetSprite(document.getElementById("canvas").getContext("2d")) debugDraw.SetDrawScale(30.0) debugDraw.SetFillAlpha(0.5) debugDraw.SetLineThickness(1.0) debugDraw.SetFlags(b2DebugDraw.e shapeBit b2DebugDraw.e jointBit) world.SetDebugDraw(debugDraw) window.setInterval(update, 1000 60) loop function update() world.Step(1 60, 10, 10) world.DrawDebugData() world.ClearForces() |
2 | Capitalizing on JavaScript's prototypal inheritance JavaScript has a class free object system in which objects inherit properties directly from other objects. This is really powerful, but it is unfamiliar to classically trained programmers. If you attempt to apply classical design patterns directly to JavaScript, you will be frustrated. But if you learn to work with JavaScript's prototypal nature, your efforts will be rewarded. ... It is Lisp in C's clothing. Douglas Crockford What does this mean for a game developer working with canvas and HTML5? I've been looking over this question on useful design patterns in gaming, but prototypal inheritance is very different than classical inheritance, and there are surely differences in the best way to apply some of these common patterns. For example, classical inheritance allows us to create a moveableEntity class, and extend that with any classes that move in our game world (player, monster, bullet, etc.). Sure, you can strongarm JavaScript to work that way, but in doing so, you are kind of fighting against its nature. Is there a better approach to this sort of problem when we have prototypal inheritance at our fingertips? |
2 | Best way to store NPCs, Monsters, Shops, etc for JavaScript game? OK, let's say I have a JavaScript game (preferably on jQuery framework) and its using HTML5 Canvas. What would be your way of storing data to map out shops, monsters, and NPCs? I was thinking maybe JSON txt files on the website? Or maybe simple text files and simple delimiters? I am not sure. How would you store that kind of data? |
2 | How can i call a thing a lot of times (game dodger) Hey I am new to coding and i want to know how to get the same thing to hapen until i "say" stop. The game is that you need to dodge stuff that is falling, i was thinking that i could use a while loop and Push the object in the list like the following Var i 0 Var theObjects While ( i lt 100) theObjects.push() i But that would be 1. Spawn them at the same time and the it would be 2. This only works for x amount of time. How can i make the object spawn til i say stop and spawn at difrent times Sorry for my bad english. |
2 | Game runs at different speeds in Chrome versus Firefox I am using Box2D for physics on the server side. Player position is updated on the server, so there is nothing the client can do except give input. But running game in Chrome only, the player moves faster as compared to running in Firefox only. If running in both browsers (one player in each browser), then the game in both browsers runs at the speed at which it runs in Chrome. Using this update loop function update() for(let p of players) if(p.dead) continue p.keyEvents() aabb.lowerBound.Set( p.body.GetPosition().x p.s w (2 scale),p.body.GetPosition().y p.s h (2 scale) ) top left aabb.upperBound.Set( p.body.GetPosition().x p.s w (2 scale),p.body.GetPosition().y p.s h (2 scale) ) bottom right world.QueryAABB( ReportFixture , aabb , p.id ) p.socket.emit('players',foundPlayers) foundBodies.players world.Step( 1 60 frame rate , 8 velocity iterations , 3 position iterations ) if(deletePlayerIds.length gt 0) deletePlayer() world.ClearForces() setInterval(update, 1000 60) to call update loop I have read that for Box2D there is no need to apply a delta. What could be the reason for different speeds, and how it can be resolved? |
2 | How to reduce the total time spent checking against my world bounds? I'm making a game engine and currently I use a function for checking a new position after movement to prevent game objects from escaping the world const boundary function (min, max) return Math.min( Math.max(this, min), max ) I've noticed that it consumes around 9 10 of my game loop (testing with 4500 objects). Is there a better way to handle this? Do I generally need to make my world finite? To clear this up, this is not an object object collision detection question. For that I have a grid, and this grid is based on the size of the world, which is why I check that objects don't escape the world size limits. |
2 | In regards to real time turn based games, where should the turn handler be? I'm currently developing a pool like browser game. I'm stuck on where should I handle the turn changing, timer, etc. Currently, turn timer (i.e. 15 seconds left to do action, then turn will change) is handled by the server. But the changing of turns itself is handled by the client (the browser itself). Now in my current setup, whenever a player leaves window focus, the game gets out of sync. Should I migrate the turn change handling to the server instead? |
2 | CSS Sprite position updates slow due to addition of 'px'? I'm moving fewer than 10 position absolute elements around the screen. An enormous amount of CPU time (profiled in Chrome as (program) i.e. native code) is used where I do the following style.left monster.x 'px' style.top monster.y 'px' ... where style belongs to the DOM element representing the monster in question. This is a string concatenation cost since as soon as I remove that 'px', the problem disappears. Of course, then absolute positioning doesn't work onscreen since the px is required by the browser. I'm running this logic via requestAnimationFrame which runs about 60FPS... am currently amending such that position updates only occur every 2 3 frames as this will certainly help. Am also modifying so that only when the numeric value changes, is the style property set anew, rather than setting the style property on every active frame. Even so, is this how CSS sprite updates are done? Is it always this slow? The only alternatives I can see are to use canvas (usually also slow, for different reasons) or WebGL. I'd prefer CSS for simplicity. |
2 | Fix latency when sending state I have a multiplayer game done with Phaser, which runs in the browser and on a node.js server. The server is authoritative, every 50ms or so it sends the game state object to all clients. The clients receive the state and update all instances accordingly. The game runs at 60fps, and the physics and AI are the same on clients on server, so if there is no user interaction the game will evolve exactly the same (the next frame on the server will be equal to the next one on the client). This should make sync much easier, but I have a problem When the client receives the state from the server, the state is no longer up to date (as there is the latency between server and client). Here is a drawing Server State1 State2 State3 State4 State5 ................................................ V Client State1 State2 State3 State4 State5State3 So, when the client receives State3, it is no longer usable as it has already been at State3. This makes the game always rewind a few frames when it receives the update from the server. How can I solve this, taking in account that the same game engine runs on both client and server (so prediction is much easier). I would try "rendering the game in the past" as I have seen in other cases, but I do not really think I can break Phaser physics render loop connection. |
2 | Using copyrighted sprites Possible Duplicate How closely can a game resemble another game without legal problems I was thinking about making a pacman clone, I know there is a similar question here Using Copyrighted Images , but I know i can't use the original art from the game because it belongs to Namco, so if I design a character that has the shape of the slice circle it will look exactly like pacman, maybe if I use green instead of yellow? Also if the game plays like the original pacman, it is wrong? I just want to make the game as a personal project and and publish it in my site without getting in trouble |
2 | Creating looping canvas animation (slot machine with reels) I have a small assignment to create something like slot machine with spinning pictures. I have to use HTML5 Canvas. I would like to hear some opinions how this can be made simply and performantly. There are symbols that would be spinning vertically while only 2 would be fully visible, next 2 are partially hidden and remaining 2 are not visible at all. I have chosen CreateJS suite, but I have no experience with that, so I am just trying to figure it out. I made this for the start... var reels 160, 405, 648, 892, 1137 X offset of reels var reelLines 0, 317, 634 Y offset of symbols in the reel var stage new createjs.Stage('game') for (x 0 x lt reels.length x ) for (y 0, y lt reelLines.length y ) bmp new createjs.Bitmap('symbol').set( x reels x , y reelLines y ) stage.addChild(bmp) This displays 3 symbols in each reel and it looks good. Now I need to add some animation to it. I am thinking about it like having stack of symbol bitmaps at the top position where it's not visible yet. I tried to use Tween class like this. createjs.Tween.get(bmp, loop true ).to( y 808 , 500) It's basically correct, symbol rolls in and out and then it pops at top again. However this works for single symbol only. If I position three symbols as stated above and run same tween on them, each of them will go in different speed, because to call second argument is duration, not the speed. I would really appreciate some ideas on this approach and if it's even correct one. |
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 | 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 | What is the best way to debug and profile a web application on an iPod in Mobile Safari? I've built a web app that makes heavy use of JavaScript and HTML5 canvas. It's easy to debug in Chrome, but on a mobile device the developer tools are much less robust. Is there a tool or technique that will enable me to easily debug and profile my application on an iPod in Mobile Safari? |
2 | How can I structure my ASCII terrain object? So I have this object which represents a simple ASCII "overworld". Note the code is broken, but it's for demonstration purposes... var TerrainObj w name 'water', glyph 'w' , g name 'ground', glyph 'g' , terrain w, w, w, w , w, g, g, w , w, g, w, w , g, g, w, w , generate display function(terrain) ... Code that returns an array the same as terrain but containing the glyphs from the objects in terrain ... So as you can see, the object contains the data for different types of terrain cell, the overworld itself, and a method to covert the terrain info into an array of glyphs for printing to the screen. But of course the problem with this code is that in the terrain array, there will be an reference error to each object. I want to be able to write out the terrain array without using more than a one letter name, because presumably to get this to work I'd have to do something like terrain function() var map this.w, this.w, this.w, ... , ... ... So is there a nicer way I can produce my "semantic" terrain layer that references objects but without me having to write lengthy references to them in my array declaration? |
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 | How can I structure my ASCII terrain object? So I have this object which represents a simple ASCII "overworld". Note the code is broken, but it's for demonstration purposes... var TerrainObj w name 'water', glyph 'w' , g name 'ground', glyph 'g' , terrain w, w, w, w , w, g, g, w , w, g, w, w , g, g, w, w , generate display function(terrain) ... Code that returns an array the same as terrain but containing the glyphs from the objects in terrain ... So as you can see, the object contains the data for different types of terrain cell, the overworld itself, and a method to covert the terrain info into an array of glyphs for printing to the screen. But of course the problem with this code is that in the terrain array, there will be an reference error to each object. I want to be able to write out the terrain array without using more than a one letter name, because presumably to get this to work I'd have to do something like terrain function() var map this.w, this.w, this.w, ... , ... ... So is there a nicer way I can produce my "semantic" terrain layer that references objects but without me having to write lengthy references to them in my array declaration? |
2 | Separating .js elements .js element communication So I have 2 questions regarding the code below function goldClick(number) gold gold number document.getElementById("gold").innerHTML gold function buyMiner() var minerCostG Math.floor(100 Math.pow(2.1,miner)) var minerCostW Math.floor(10 Math.pow(3.1,miner)) if(gold gt minerCostG) if(wood gt minerCostW) miner miner 1 gold gold minerCostG wood wood minerCostW document.getElementById('miner').innerHTML miner document.getElementById('gold').innerHTML gold document.getElementById('wood').innerHTML wood var nextCostMG Math.floor(100 Math.pow(2.1,miner)) document.getElementById('minerCostG').innerHTML nextCostMG var nextCostMW Math.floor(10 Math.pow(3.1,miner)) document.getElementById('minerCostW').innerHTML nextCostMW window.setInterval(function() goldClick(miner) , 1000) Question 1 Is it possible to separate these functions (goldclick, buyminer, window interval,) into their own documents so that if I have say, 50 different XXXXclick functions, and 50 buyXXXX functions and 50 interval functions, I have just 3 .js documents instead of 50. Question 2 If it is possible to separate them, how would I ensure that they are communicating with each other and variable values are not being confused or sent to the wrong lt span gt in the displaying html. |
2 | timezone independant Date.now() for node.js game I have a game I'm working on using node.js and socket.io. The issue I'm having, is I'm trying to have it so that players execute whatever actions they inputed about 50ms in the future, giving everyone a chance to stay relatively in sync. I've got frame independant code running, which works well until a client has a different time than the server. to predict when the client should act out movement code from the server, I use Date.now() gt command.timeStamp The issue I'm having is that the client isn't in the same timezone as the server, for instance someone I'm testing with is just one minute above below my server time, resulting in commands being 900 milliseconds in the past or future, which is non ideal. Is there some way I can use a common timestamp across clients and server? |
2 | Particle Turbulence Effect in Babylon.js Is there any way to implement a turbulence effect in a babylon.js Particle System? I know that its possible to use physics engines on mesh objects, but I've not seen any discussion of using them on a babylon particle system. Might there be a way to bake a particle system as a .vdb and import it if real time simulation is not an option? |
2 | Tagging "regions" in rot.js map generator I'm working on a small roguelike and I'd like to be able to tag the various quot regions quot generated via the Map generators so that I can use it as a lookup to environment descriptions. I see that there are quot Rooms quot that are generated in the dungeon generator algorithms, however I didn't really see anything similar in say, the cellular automata generator. Is there a way to leverage the generator in rot.js, or am I stuck with manually determining if I'm in a particular open area (and breaking encapsulation of internal, private variables along the way)? Basically, I'd like to be able to link up my player's location to the text you see at the bottom of , but can't seem to figure out how to do it generically. I'm fairly certain I could use the 'Rooms' object in the first 2 screenshots, and everything else is a hallway, but I'm not clear on how I could get a particular 'region' in a cellular automata generator (or one of the maze generators, for instance). |
2 | How to draw a tileset using HTML5 canvas? I have a tileset something like this 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 My tileset draw code looks like this var image new Image() image.src '32x32.png' var tile 5 var tileSize 32 var x 100 var y 100 context.drawImage(image, Math.floor(tile tileSize), 0, tileSize, tileSize, x, y, tileSize, tileSize) And this code draws the 5 tile, but how would I draw the 10 tile, or the 15 tile without adding tileX and tileY? I probably need something like if tile is equal to 15, then draw tile 15. |
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 | Is it more efficient to encode rotation in a spritesheet or rotate at runtime? I'm developing a game with JavaScript and HTML5 and I'm wondering about the performance implications of sprite rotations. There are two ways that I know to rotate a sprite Rotate the actual sprite based on its rotational speed and velocity, as it travels along it's trajectory. Pre compute the rotations and store them as frames within the sprite sheet to give the illusion that it's spinning when it isn't. On one hand, I can see how rotating some sprites in a spritesheet would be efficient because it's one image that is loaded, split into frames, and re used. But on the other hand, I'm not sure the calculations involved for rotating the sprite based on its velocity and rotational speed are really anything for current browsers (on computers and mobile devices) to worry about. In my game, the canvas area is 800 x 600, and the game is using 32 x 32 sprites for everything. The "map" isn't tile based. Of the two options above, which would be more efficient for runtime performance? |
2 | How decoupled should game logic and rendering be? From a data perspective, how decoupled should game logic and rendering be? How much does it have to know about each other? Take a look at the following example. I'm going to use javascript because that's what I'm most familiar with. Block Basically, when the Block.destroy is called, there is a delay before it loses a life function Block(life, destructionDelay) this.life life this.destructionDelay destructionDelay this.destructionCountdown 0 Block.prototype destroy function() this.destructionCountdown this.destructionDelay , update function() if(this.destructionCountdown gt 0) this.destructionCountdown if(this.destructionCountdown 0) life What was supposed to happen here is when the Block is destroyed, it plays a "being destroyed" animation before it loses a life destroyed. As I have been informed, it is ideal for the game logic to know nothing minimal about the renderer and vice versa. How do I design these kinds of entities? |
2 | I can't clear the paint image in my Canvas I'm trying to make the Mario move, but somehow it leaves traces behind, can anybody help??? var canvas document.getElementById("screen") var ctx canvas.getContext("2d") var mario var marioSprite var tiles var speedX 1 marioSprite Specification mario target picture specification X amp Y, Width amp Height px 276, py 44, pwidth 16, pheight 16, drawing on Canvas specification X amp Y, Width amp Height cx 16, cy 116, cwidth 16, cheight 16, draw Mario in Canvas function drawMarioSprite() marioSprite new Image() marioSprite.src 'file C Users MASTONO ALI Desktop img characters.gif' marioSprite.addEventListener('load', e gt ctx.drawImage(marioSprite, mario.px, mario.py, mario.pwidth, mario.pheight, mario.cx, mario.cy, mario.cwidth, mario.cheight) ) this.position function() this.mario.cx speedX position() drawMarioSprite() end drawTiles and tilesLoop function drawTiles() tiles new Image() tiles.src 'file C Users MASTONO ALI Desktop img tiles.png' tiles.addEventListener('load', e gt tilesLoop() ) function tilesLoop() for (let x 0 x lt 25 x ) for (let y 11 y lt 13 y ) ctx.drawImage(tiles, 0, 0, 26, 26, x 12, y 12, 20, 20) drawTiles() end function draw() drawMarioSprite() drawTiles() window.requestAnimationFrame(draw) window.requestAnimationFrame(draw) thank you |
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 | phaser.io mouse cursor sprite I am trying to build a game and i want people to be able to select stuff with a pointer but i don't want it to be just an ugly looking default pointer so i wrote this code to try and get a image as it first i loaded the image game.load.image('selector', 'assets img pointer.png') then I put it into my game selector game.add.sprite(game.world.centerX, game.world.centerY, 'selector') and then in my render() function i do this selector.x game.input.x selector.y game.input.y it moves fine with my mouse but with one problem my game is designed so that i have to use a camera that follows my character because the map is bigger than the view so since for some reason my sprite always starts at 0,0 it can only move 800x600px since thats all that the canvas sees the mouse in so i need a way to fix this but i'm not sure how to do this because i am new to phaser |
2 | Map scrolling around the world I am developing an TBS (turn based strategy) game. I have created a simple canvas renderer to render hexagonial map. I already implemented scrolling on the map. My current problem is that I want to make it like in the civilizations games that you can scroll around the world. But I am kind of stuck on how to implement that. I had the idea of checking if a tile was rendered and if there is still space to the left render next sibling and so on, but this would turn out into long loops. My map array (2d) holds all the tiles and every tile has a member which holds all the siblings. How would you solve this? This is a screenshot from the example. You can check it out on http civ.minerjs.com. The code is also available to browse on the site using developer tools. Thanks for reading! |
2 | How can I tweak this A search pathfinding algorithm to handle different terrain movement values? I'm creating a 2D map based action game with similar interaction design as Diablo II. In other words, the player clicks around a map to move their player. I just finished player movement and am moving on to pathfinding. In the game, enemies should charge the player's character. There are also five different terrain types that give different movement bonuses. I want the AI to take advantage of these terrain bonuses as they try to reach the player. I was told to check out the A search algorithm (http en.wikipedia.org wiki A search algorithm). I'm doing this game in HTML5 and JavaScript, and found a version in JavaScript http www.briangrinstead.com blog astar search algorithm in javascript I'm trying to figure out how to tweak it though. Below are my ideas about what I need to change. What else do I need to worry about? When I create a graph, I will need to initialize the 2D array I pass in passed on with a traversal of a map that corresponds to the different terrain types. in graph.js "GraphNodeType" definition needs to be modified to handle the 5 terrain types. There will be no walls. in astar.js The g and h scoring will need to be modified. How should I do this? in astar.js isWall() should probably be removed. My game doesn't have walls. in astar.js I'm not sure what this is. I think it indicates a node that isn't valid to be processed. When would this happen, though? At a high level, how do I change this algorithm from "oh, is there a wall there?" to "will this terrain get me to the player faster than the terrain around me?" Because of time, I'm also debating reusing my Bresenham algorithm for the enemies. Unfortunately, the different terrain movement bonuses won't be used by the AI, which will make the game suck. I'd really like to have this in for the prototype, but I'm not a developer by trade nor am I a computer scientist. D If you know of any code that does what I'm looking for, please share! Sanity check tips for this are also appreciated. |
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 | Prevent cheating in html Javascript game I have made a Javascript html game. Now the problem I have is anyone can edit the client code and cheat in game for example there is a man shooting a enemy. Man HP nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp 100 Enemy HP nbsp nbsp nbsp nbsp nbsp 50 lt div id "man" hp "100" gt lt div gt Now if someone changes the hp attribute to a very high value then he becomes literally immortal making the game easy. Now how can I prevent this type of thing ? |
2 | How to display a tile map from a 2D array in JavaScript? I have stored my map, but the problem I am having is displaying it. My map is 100x100 tiles which are 40x40px. I have my loop running through the array but I'm having difficulty selecting the portion of the map image to relate to the tiles. This is the code which selects the portion of the image on each iteration var sx Math.floor(tileId 8 tileWidth) source x var sy Math.floor(tileId 8 tileHeight) source y I'm using Canvas and keep getting this error message INDEX SIZE ERR DOM Exception 1 Index or size was negative, or greater than the allowed value. I'm guessing the remainder or division by 8 is wrong, this is something I picked up from the net, but what exactly does that integer need to be? Thanks |
2 | Eliminate isolated cave in procedural cave generation I've got an algorithm that generates a cave procedurally, the map is modeled in the data as a 2d array of 0s (empty space) and 1s (wall). The algorithm works just fine, but I've got quite some isolated small caves on the scene, which I would like to avoid. That's how the map looks that gets generated. Is there some efficient algorithm to remove the black holes in the white wall sections? I was thinking of something like For every closed cave, check if there is a bigger cave and if so, close it. But that seems insanely inefficient since I'd have to loop over the map a lot in order to do this for all small caves. |
2 | What is wrong with my Dot Product? I am trying to make a pong game but I wanted to use dot products to do the collisions with the paddles, however whenever I make a dot product objects it never changes much from .9 this is my code to make vectors vector make function(object) return object.x object.width 2,object.y object.height 2 , normalize function(v) var length Math.sqrt(v 0 v 0 v 1 v 1 ) v 0 v 0 length v 1 v 1 length return v , dot function(v1,v2) return v1 0 v2 0 v1 1 v2 1 and this is where I am calculating the dot in my code vector1 vector.normalize(vector.make(ball)) vector2 vector.normalize(vector.make(object)) dot vector.dot(vector1,vector2) Here is a JsFiddle of my code currently the paddles don't move. Any help would be greatly appreciated |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.