_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
2 | Get speed from vector using box2d and javascript I need to find the speed of an object in a game. The game is made in HTML5 with jquery and jquery.box2d. For this I can use these methods GetLinearVelocity().x GetLinearVelocity().y I'm then trying to calculate the speed from this piece of code, but get some values that doesn't make sense when I console.log it. This is my code var heroVelX game.currentHero.GetLinearVelocity().x var heroVelY game.currentHero.GetLinearVelocity().y var speed Math.sqrt(heroVelX 2 heroVelY 2) console.log(speed) Some of the values in console.log are numbers, but most of them are NaN (Not A Number), which confuses me? Can someone help me solve this? The goal I want to achieve, is to see when the speed(of object .currenHero) drop below a certain value, so I can excute a new state in the game. |
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 | Moving a div with hotkeys using easing in and out I'm working on replicating Tagpro using AngularJS and Firebase as a learning project. I want this ball to move using ease in and out like in the youtube video below. My code http codepen.io clouddueling pen vCpuf http tagpro.koalabeast.com https www.youtube.com watch?v cyAeDTmG8GI At least my method goes in the right direction but is super glitchy. Does anyone have an example of the algorithm that makes this happen? Code sample? Here is a weird graph of the movement I'm trying to achieve Sorry if this is a duplicate I came from stackoverflow. |
2 | How to display a lot of small objects using WebGL? Introduction The game scene contains a lot of 10x10 pixel elements for 1980x1200 px. screen the number of elements on the scene can vary from 0 to 23760 (elements cannot intersect). The live example http fintank.ru game The entire game space comprised of tiles each tile is responsible for some area and keeps elements for that area (similar to google maps). Each tile exist as 2 entities S and G. S is a set of elements in the tile, G is rendered image of a tile. When the server put remove elements to the tile, we change S and then re render the G. To draw a frame (at 20 fps) I just put the G of each visible tile using the putImageData(). That is done without WebGL. The question What is the most CPU effective approach to implement such many elements management using WebGL? Should I render each tile to a texture or each element may be implemented as a separate textured rectangle? The main concern is that each tile may be updated 30 60 times a second (elements adding removal). How to avoid memory leaks (how to reuse buffers?) if we make many new textures every second? What is the most effective way to manipulate pixels during rendering a 100x100 tile? How to avoid re uploading the unchanged textures to graphic card? |
2 | 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 | Adapting tilemap algorithm to support isometric tilemap I'm using Phaser to build an isometric game. The framework doesn't have support for isometric tilemaps yet, so I'm starting to write a PR for it to support. What I currently have, loading an isometric tilemap on the current Phaser.Tilemap object, is this As you can see, the tiles are wrongly positioned because of the simple 2D tile positioning approach the framework currently uses. The class that actually makes the parsing of the JSON map and converts it into a tilemap is Phaser.TilemapParser, specifically at line 185. What I need is some help on where to start adapting this parser or any other part of the code in order for it to support isometric tilemaps. I don't know exactly where to start extending this parser or even writing a new parser just for isometric tilemaps. Also, I know the calculations are different for positioning isometric tiles, and I want to know too where that change should go here, as I didn't find that either. |
2 | How can I scale zoom to a point in canvas in the game? I am using html5 canvas to build a MMO game. When I scale my background by default it scales to (0, 0) which is the top left corner of the background. If I have other sprites on the screen they all will look like they are shifting to the bottom right a little bit. Suppose my sprite(player) is at (x,y) of the map and it is placed center on the canvas.How can I make the background scale or zoom to (x,y) instead of (0,0)? Its world position is (x,y) but its screen position is always (canvas.width 2, canvas.height 2). I think in this way the sprites around my player wouldn't shift their position to unexpected places. But I don't know how to do this. |
2 | How can I get a 4x4 matrix from a bullet quaternion? I'm trying to make a game using JavaScript with Ammo.js ( an implementation of bullet ) and Sylvester to do my matrix maths. The problem is I don't know how to turn the WXYZ that bullet gives into the 4x4 matrix Sylvester needs. If there is a way to just get Bullet Physics to give me the 4x4 matrix please tell me! I am completely lost here. |
2 | Buffer System For Items I am going to reference this image of what I want to accomplish in JavaScript. This is the Diablo buffer system. This question may be a bit advanced (or possibly not even allowed). But I was wondering how you might go about implementing this type of system in a JavaScript game. Currently to implement such a system in JavaScript escapes me, and I am turning to SO to get some suggestions, ideas, and hopefully some insight in how I could accomplish this without being to costly on the CPU. Some thoughts of mine for implementing such a system would be to Create DIVS within a DIV that hold each position of the inventory Go through each item you own in a container and see which DIV it belongs to Make said item images the DIVs image This type of system might possibly work if ALL items were 1x1, but for this example its not going to work out. I am at a complete lost of ideas how to even accomplish this. Although, maybe rendering directly to the canvas and checking mouse cords could work, there would more than likely be A HUGE annoyance when checking if other items are overlapping each other (meaning you cant place the item down, and possibly switching item with the cursor item ). That said, what am I left with? Do I need to makeshift my own hack system with messy code, or is there some source out there (that I don't know about) that has replicated this type of system in their own game. I would be very grateful to get some replies on how you might go about doing this, and will accept answers that can logically explain how you might implement such a system (code is not required). P.S. Id like to use pure JavaScript, and nothing else (even though it might be "reinventing the wheel", I also like to learn). |
2 | How can I ensure reasonably spaced out enemies I have a simple javascript game and I'm initializing their positions on the y axis using random numbers. How can I ensure that they are reasonably spaced apart? My simple algorithm is y (Math.random() 1000 600) However I frequently get enemies almost directly on top of each other. This is a huge problem for the game, since it's a word game and the enemies have text on their center, that if overlapped makes them impossible to kill since you can't see the words. Any advice would be appreciated! I'm pretty new to making games in general so this has all been a learning experience for me! |
2 | Javascript Audio solution still has issues. Flash works but... requires flash (an issue for iOS). What do you use in Javascript for audio? |
2 | Get points on a line between two points I'm making a simple space game in JavaScript, but now I've hit a wall regarding vectors. The game view is top down on a 2d grid. When the user clicks on the grid, the space ship will fly to that spot. So, if I have two sets of points x 100.2, y 100.6 the ship x 20.5, y 55.95 the clicked coordinates If the game loop ticks at 60 iterations per second, and the desired ship velocity is 0.05 points per tick (3 points per second), how do I calculate the new set of coordinates for the ship for each tick of the game loop? p.s. I do not want to account for inertia, or multiple vectors affecting the ship, I just want the ship to stop whatever it is doing (i.e. flying one way) and move to the clicked coordinates at a static speed. |
2 | Click on an isometric plane and obtain normal coordinates I have photos distributed as cells. When I click, I get the corresponding row and column. console.log("Col " X "Row " Y) When applying an isometric view conversion like this ctx.translate(0, 300) ctx.scale(1, 0.5) ctx.rotate( 45 Math.PI 180) I do not know what mathematical formula applies to get the coordinates correctly. Based on feedback so far, I've been able to get this far. The x coordinate seems to work fine, but the y coordinate not. Isometrico() function Isometrico() ctx.translate(0, 300) ctx.scale(1, 0.5) var radianes 45 Math.PI 180 ctx.rotate(radianes) document.addEventListener("mousedown", function(e) CorIsometrico( e.offsetX, e.offsetY) ) function CorIsometrico(xI,yI) RESPUESTA yI yI 300 yI yI 2 xI xI Math.cos(45) yI Math.sin(45) I yI Math.sin(45) yI Math.cos(45) console.log("Coor Isometricas " xI " " yI) Edit Each cell is 50x50. Having 10 columns and 50 rows, the information of each cell would look like this 1 50 50 2 100 50 3 150 50 ... 49 450 250 50 500 250 Maximum Y value 250. xI xI Math.cos(45 180 Math.PI) yI Math.sin(45 180 Math.PI) yI yI Math.sin(45 180 Math.PI) yI Math.cos(45 180 Math.PI) yI yI 2 yI yI 300 Click in X 1 Y 1 138.5929291125633 531.5575746753798 Click in X 1 Y 5 198.69700551341987 90.3229432149742 Y exceeds the maximum value. Edit2 var xI2 xIMath.cos(45 180 Math.PI) yIMath.sin(45 180 Math.PI) var yI2 xIMath.sin(45 180 Math.PI) yIMath.cos(45 180 Math.PI) yI2 yI 2 yI2 yI 300 xI2 xI2 150 console.log("Coor Isometricas " xI2 " " yI2 ) x coor 100 to 400 px if x 150 y coor 0 to 155. Been thinking that the problem is not necessary on isometry. What I'm looking for can be simplified to get the coordinates of a 2d plane by having it rotated X degrees |
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 | 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 | Particles to Denote Movement in Space I'm currently working on a WebGL project to realise an idea I've had for some years. On my desk is book on making a space sim written 15 years ago. There I found some algorithm for particles in space. The idea is simple A cloud of particles that stay in place so they fly past the player, but reset to be in front of the player when they move past the ship. This shows the player they're moving while there's nothing else around. For this, I reworked the algorithm found in the book a little ParticleField.prototype.updateCloud function(frustum, position, direction) var s this.size, s2 s 2 for (var i 0 i lt this.vertices.length i ) if (!frustum.containsPoint(this.vertices i )) this.vertices i .set( (position.x s Math.floor(Math.random() s2)) (s direction.x), (position.y s Math.floor(Math.random() s2)) (s direction.y), (position.z s Math.floor(Math.random() s2)) ((s Math.floor(Math.random() s2)) direction.z) ) Where s is the size of cloud. I played around with the sizes, but this simple function has several weaknesses. The particles 'pop up' in front of the player when they're moving. If the player backs up and moves backwards, the particles won't reset, leaving the cloud visible popping the illusion. Particles appear to be flying through the player. Without regard of how the particles look (they're simple points right now), how can I make this look more natural? I've seen the effect in games like Elite Dangerous and Freelancer, and I'd like to be closer to them, and I'd appreciate any hint on the topic. |
2 | HTML Canvas drawing Firefox error I am getting the following error ONLY when running my game in Firefox (3.6) Component returned failure code 0x80040111 (NS ERROR NOT AVAILABLE) nsIDOMCanvasRenderingContext2D.drawImage The issue does not occur in the other major browsers, and my game runs completely fine after I click 'OK.' Here are a few snippets of code where I have localized the issue to. Has anybody seen this issue before? According to Google it has something to do with drawing the image before it is loaded, but from my understanding I am loading it properly before using it!. player class var player new (function() var that this that.image new Image() that.image.src "res enemy1 sprites.png" that.width 16 that.height 16 that.frames 2 that.actualFrame 0 that.spriteXoffset 0 that.spriteYoffset 0 that.moved false that.boundary false that.num balls 5 that.rootX 350 that.rootY 250 that.ballX that.rootX,0,0,0,0 that.ballY that.rootY,that.rootY,that.rootY,that.rootY,that.rootY that.directions "up" 0, "right" 1, "down" 2, "left" 3 that.dirs that.directions.right,that.directions.right,that.directions.right,that.directions.right,that.directions.right for (i 1 i lt that.num balls i ) that.ballX i that.rootX (i that.width) ... ... that.draw function() try for (var i that.num balls 1 i gt 0 i ) update animation switch (that.dirs i ) case that.directions.left that.moveLeft() break case that.directions.right that.moveRight() break case that.directions.up that.moveUp() break case that.directions.down that.moveDown() break ctx.drawImage(that.image, that.spriteXoffset, that.spriteYoffset, that.width, that.height, that.ballX i , that.ballY i , that.width, that.height) catch (e) alert(e.message) if (that.moved) if (that.spriteYoffset gt 0) that.spriteYoffset 0 else that.spriteYoffset 16 that.moved false )() game loop var GameLoop function() .. .. player.move() player.draw() .. .. if (state) gLoop setTimeout(GameLoop, GAME SPEED) |
2 | Array of map data renders the map the opposite way A while ago by following some tutorials I made a game map array consisting of 0, 1 and 2. I program it the way I want to see it var mapArray 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 2, 2, 0 , 0, 0, 1, 1, 1, 0, 0, 2, 0, 0 , 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 , 0, 0, 0, 1, 1, 1, 1, 1, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 , 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 2, 2, 0 , 0, 0, 1, 1, 1, 0, 0, 2, 0, 0 , 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 , 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 , 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 So for example the line 0, 0, 0, 1, 1, 1, 1, 1, 0, 0 lies on the X axis and I want to see grass 1 horizontally, but when I draw it on the canvas it's being rendered vertically instead. So the y and x axis are being swapped in place. Why is this so? Here is the rendering code function render(viewport) context.save() context.translate(view.x, view.y) requestAnimationFrame(render) var oldPosX boatPosX var oldPosY boatPosY for (let i 0 i lt mapArray.length i ) for (let j 0 j lt mapArray i .length j ) if (mapArray i j 0) this.sprite.draw( background, 190, 230, 26, 26, i this.sprite.width, j this.sprite.height, this.sprite.width, this.sprite.height ) if (mapArray i j 1) this.sprite.draw( background, 30, 30, 26, 26, i this.sprite.width, j this.sprite.height, this.sprite.width, this.sprite.height ) if (mapArray i j 2) this.sprite.draw( background, 200, 20, 26, 26, i this.sprite.width, j this.sprite.height, this.sprite.width, this.sprite.height ) this.ship.drawimage(boat, boatPosX, boatPosY, 50, 50) var lineHeight 16 2.286 var textWidth context.measureText(theArray moveCount .question).width 3 context.textAlign 'left' context.textBaseline 'top' context.font "14px Verdana" context.fillStyle 'rgba(0, 0, 0 ,0.9)' context.fillRect(boatPosX ship.width 2, boatPosY ship.height 2, textWidth, lineHeight) context.fillStyle 'white' context.fillText(theArray moveCount .question, boatPosX ship.width 2, boatPosY ship.height 2) answerBtn1.innerHTML theArray moveCount .answer1 answerBtn2.innerHTML theArray moveCount .answer2 if(isPositionWall(boatPosX, boatPosY)) boatPosX oldPosY console.log("collision") context.restore() |
2 | HTML5 Canvas Depth Sorting I'm have problem with Isometric. I'm don't know how to name this "problem", but I'm show you some sceen what I get and what I'm need to get. My code now drawing something like http 2.bp.blogspot.com rqhF 8E1nlA R59d PmoREI AAAAAAAAAGo 3yHpmy55moc s400 lore2.png But I'm need draw something like this http 3.bp.blogspot.com rqhF 8E1nlA R59epfmoRFI AAAAAAAAAGw cE o A0bvm0 s400 lore3.png I'm hear this is "Depth sort" But what it is? how I'm can apply to my code and where I'm can learn this? My code 'http jsdo.it keichioor exU1 |
2 | 2D Grid based Pathfinding with Elevation I'm creating an isometric game which currently uses A Pathfinding on a basic grid representation of the map. Having elevations and allowing the Players to traverse up and down is an integral part of the game however I'm stuck on exactly how to implement that, whether it be with A or something else. For example, 0 0 0 X 0 4 4 4 0 0 0 0 0 4 4 4 0 0 1 2 3 4 4 4 Assuming X is the Player, the numbers are tile elevations, and that the Player can only traverse tiles 1 elevation to the tile they're currently on, is there an accepted known way of doing this pathfinding? |
2 | How would I process accelerometer data to use it for camera rotation? I'm using Three.js to make a web based 3D first person game. I would like the player to be able to control the camera rotation with their device's accelerometer. The sensor data is received via the DeviceMotionEvent event listener. Here is an example of what it returns How should I proceed with this? |
2 | ECS Components inside components? Reading up on ECS, I've tried to implement a simple 'game', if you can call it that. Basic concepts You have planets(entity), they produce gold. (gold is a component inside planet) Planets can build buildings on themselves(Buildings component) A building(entity) has associated gold costs(Costs component) But costs component has Gold in it(or it needs to anyway) As to my question Am I close with my interpretation of ECS(Should components be inside other components?) Are resources a valid Component? if not, where would it make sense to place them? Edit for clarity ECS Entity Component System. My entities are empty hash tables of components. My components are used inside systems for game logic, the Treasury entity has a Gold component and the IncomeSystem updates that component. Other components (Buildable, Population, Moveable) |
2 | OOP implementation of BUFFS and Stats. Suggestion I am developing an MMORPG server using NodeJS. I am not sure how to implement Buffs, i mean, equipped objects or used skills have effects on the Player() which has many Stats(), some of them have a max cap... Effects can change the Stat value, increasing or decreasing it by a value, a percentage or completly rewrite the value of the stat. After a while I have decided to create a base class for buffs, which can be hidden (if they are casted from an equipped object) or shown if they came from an ability (Spell). Anyway I need suggestion how to implement it, use an array for all active buffs for a stat and have a function calculate the value of the stat affected by buffs each time I need the value of the stat or...? Other more OOP's ways to do it? I have read this What 39 s a way to implement a flexible buff debuff system? but this implements only a percentage system, which buffs can only say " 10 , 20 , etc...", but I would love to have an hybrid system, which can have percentage values or static values (like WoW does), and using modifiers it's hard to implement, because modifiers refers to the current value of stat Thanks for suggestions ) |
2 | Centering camera on player div I've been making a roguelike style game in HTML5 without using canvas (only divs) with pure JS (fiddle!). I've been trying to enlarge the tile size (font size) while keeping the player centered within the camera. For some reason, when the tile size isn't equal to the map size, the camera will be slightly off. Note that the 3D effect is on purpose. Without it, the camera is still off center, and I believe it adds some much needed depth to the scene. D When tileScale (line 4 in the fiddle) is 9 (very undesirable the dots on the player's y axis should be aligned, not at a slight angle) When tileScale is 25 (on point!) Here's some relevant (trimmed) code window.onresize function() game.viewportWidth Math.max(document.documentElement.clientWidth, window.innerWidth 0) game.viewportHeight Math.max(document.documentElement.clientHeight, window.innerHeight 0) game.windowSize Math.min(game.viewportWidth, game.viewportHeight) Droid Sans Mono has a ratio of 3 4 (width height), conveniently. This may be problematic. I'm not sure. game.tileWidth game.windowSize .6 game.tileScale game.tileHeight game.windowSize .8 game.tileScale Update the camera position (needs help?) this.updateCamera function() Get player coordinates ( .5 because we need to get the player tile center) times the tileWidth plus the game window (inner square) size divided by two. var left (( game.player.x .5) game.tileWidth game.windowSize 2) "px" var top (( game.player.y .5) game.tileHeight game.windowSize 2) "px" game.planeContainer.style.left left game.planeContainer.style.top top How can I ensure that the dots in the center of the screen will be always lined up, instead of on a slight angle? My current evidence suggests that the position of the game.planeContainer object isn't being established correctly. I know this is a super tough problem, so any help will be greatly appreciated. Thanks in advance! (Another fiddle link, in case you skimmed over the first one. D) |
2 | DOM for GUI display animated objects I'm creating an HTML5 game using Canvas, but want to use DOM for the GUI for the reasons mentioned in there articles http blog.sklambert.com html5 game tutorial game ui canvas vs dom http www.html5gamedevs.com topic 29569 how do you guys build your ui http www.html5gamedevs.com topic 802 gui methodologies That being said, we have a component on the GUI that needs to be animated which will be through a sprite. Is it possible to render sprite animations through a DOM element? |
2 | Isometric game engine in JavaScript HTML5 Is anybody aware of any stable ish (ie out of alpha) isometric drawing engines for JavaScript HTML5? I have done some Google searches and found a few, but they were mostly in alpha invite only status. Is there anything mature enough to be used in a production environment? Or should I simply roll my own implementation for now and wait for the rest of the world to catch up? |
2 | Regeneration using Time.deltaTime I'm trying to regenerate stamina at a rate of 1 per second using Time.deltaTime, however this doesn't do anything (My 'current stamina' doesn't change at all). I've done some looking around and I have tried Time.fixedDeltaTime. Also tried Time.time, but that just regenerated all my stamina in under a second. Here is my code var max stamina int 100 var cur stamina int var staminaRegenRate int 1 function Update() regen if(cur stamina lt max stamina) cur stamina staminaRegenRate Time.deltaTime Debug.Log("Second has passed") What am I doing wrong? |
2 | Changing JavaScript Player Object based on keypress I'm currently working on a basic JavaScript top down shooter and I've run into a dilemma. I'm trying to implement a basic toggle weapon system however when I press the key it changes the weapon properly but when I press it again to toggle back it doesn't work. I don't think it's an issue with the rendering because the drawing function is able to detect the different weapons properly. I feel it's an issue with the actual toggle system code. Here's the code for the player class class Player constructor(set) this.cx set.x this.cy set.y this.r set.r this.color set.color this.angle 0 this.toAngle this.angle this.state 1 this.up false this.down false this.right false this.left false this.bind() bind() const self this c.addEventListener('mousemove', (e) gt self.update(e.clientX, e.clientY) ) window.addEventListener('keydown', (e) gt if(e.keyCode 81) if(self.state 1) self.state 0 if(self.state 0) self.state 1 ) toggle code window.addEventListener('keyup', (e) gt if(e.keyCode 81) if(self.state 1) self.state 0 if(self.state 0) self.state 1 ) update(ex, ey) this.toAngle Math.atan2(ey this.cy, ex this.cx) canv() if(this.angle ! this.toAngle) clear() ctx.save() ctx.translate(this.cx, this.cy) ctx.rotate(this.toAngle this.angle) ctx.translate( this.cx, this.cy) drawPlayer(this.cx, this.cy, this.r, 0, 180, this.color, this.state) this.angle this.toAngle drawing code (above this one in the complete file) function drawCircle(x, y, rad, startAngle, endAngle, color) ctx.fillStyle color ctx.beginPath() ctx.arc(x, y, rad, startAngle, endAngle) ctx.fill() function drawPlayer(x, y, playerR, playerStartAng, playerEndAng, color, state) left hand start if(state 0) ctx.fillStyle color ctx.beginPath() ctx.arc(x 15, y 15, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() end right hand start ctx.beginPath() ctx.arc(x 15, y 15, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() if(state 1) right hand start ctx.beginPath() ctx.arc(x 7, y 21, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() ctx.fillStyle color ctx.beginPath() ctx.arc(x 7, y 17, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() gun start ctx.fillStyle "black" ctx.beginPath() ctx.ellipse(x, y 20, 3, 25, 0, 0, 2 Math.PI) ctx.fill() gun border ctx.strokewidth 10 ctx.strokeStyle "black" ctx.stroke() end draw player drawCircle(x, y, playerR, playerStartAng, playerEndAng, color) |
2 | custom SetInterval function in javascript i am trying to make an custom set interval function for my game but everytime i tried, i end up with a infinite loop. I can't use the default javascript's set interval because it can not take the random number. any idea? |
2 | what function creates rotation effect in three.js? which part of the code is responsible for the rotation in this example? Is it the camera or the scene itself? http threejs.org examples canvas camera orthographic |
2 | Javascript How to create a moving bullet animation from canvas the bullet cant see to move at all function bullet() this.x playerx this.y playery this.init function() this.x 5 draw(this.x,this.y,10,10,"blue") console.log(this.x) in another function if(k.keyCode 17) bullets new bullet() bullets.init() |
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 | cocos2d js displays only one type of tile from a tmx file I am using Tiled to produce a tmx which I use in my code using cocos2d js. The problem is that when I run it on the browser, a wrong tile gets displayed, the first one of the image (0,0) and repeats for the whole map. The relevant js code is this this.farm new cc.TMXTiledMap(res.farm tmx) this.addChild(this.farm) where res.farm tmx the path to the tmx file. What could be the source of the problem? And how do I fix it? It seems to me that it is specific to my code. I do not find any other reports of the same problem. |
2 | creating a simulation game, what type of knowledge is needed? I am a beginner in game development. As a part of learning and fun, want to create a game in java script and html5. I am planning a game that we were used to play in childhood, that is "new business" a monopoly game, in that we used to buy ,rent,sell places and bank we get some money to play and etc. are features. Its just simple ludo like game. So can anyone suggest me from where to start? what will be the designing? Is it possible to create it only in a html5 and java script. |
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 | Keyboard input conflict in wall jump I'm trying to make a Megaman style wall jump in my 2D platform game with JavaScript. The character can do A,B,C motions when it sticks the wall My problem is that when I trying to jump off the wall(motion C), it goes to motion A or B first, C was not happened. I think the keyboard input was conflict but I have no idea how to handle it. Here is my current code if(key 'right' amp amp key 'jump' ) it doesn't work jump off the wall else if(key 'right' ) leave the wall else if(key 'left' ) stick the wall else release all keys falling down Please, Any help would be appreciated. |
2 | Making an enemy shoot every few seconds so I am making a 2d canvas game in Javascript and I want the enemy mobs to shoot a bullet every let's say 3 seconds. I'm almost done with the code , i made everything i just don't know how to make the function repeat. this is the enemy object function Enemy(x, y) this.sprite enemySprite this.x x this.y y this.shooting function() while(enemyBullets lt bulletsPerTick) var enemybullet new enemyBullet(this.x , this.y) enemyBullets.push(enemybullet) i'm adding the bullet object to an array . for(var i 0 i lt enemyBullets.length i ) enemyBullets i .show() enemyBullets i .move() if there is an element in the array , draw and update the bullet. i left only the important elements of the object needed to answer my question this is the enemy bullet object function enemyBullet(x, y) this.x1 x this.y1 y this.r 5 this.show function () ctx.beginPath() ctx.arc(this.x1, this.y1, this.r, 0, Math.PI 2) ctx.fillStyle "black" ctx.fill() ctx.closePath() drawing the bullet this.move function () this.x1 this.x1 5 updating the bullet In my main file , i have a function draw() which is in requestAnimationFrame(draw) for (var j 0 j lt enemies.length j ) enemies j .show() here i spawn the enemy sprite enemies j .shooting() this is the function which adds the bullets to the array , draws them and updates them. Basically , when i press the start the program now , only one bullet flies and disappears and i want that process to continue over and over again every few seconds , let's say 3 seconds for example , i tried to add enemies j .shooting() in an interval and timeout but they are in draw, which is in requestAnimationFrame and it doesn't seem to work , if anyone have any clue how to help me I want every advice possible. Also if you need more information about the problem , let me know. |
2 | Initial force to achieve orbital velocity I'm attempting to get asteroid to orbit a black hole that is asserting gravity. Some parts currently work, like the black hole asserting gravity, attracting asteroids in and destroying them. And sometimes the asteroids, or smaller chunks end up in orbit around the black hole. But my desire is to have them orbiting at random distances at the start of the game. Gravity First please note, I am certain the math behind a lot of this is off, I'm hacking a concept at the moment and once enough pieces are in place I intent to come back through and apply proper scale and units to everything. Next, it's written in JS but concepts should be fairly universal. function attractBodyToBlackHole(body) var sx body.position 0 var sy body.position 1 var bx blackHoleBody.position 0 var by blackHoleBody.position 1 var angleToBody Math.atan2(sx bx, sy by) var distanceToBody Math.sqrt(Math.pow(sx bx, 2) Math.pow(sy by, 2)) var magGrav 0.8 (distanceToBody 14) if(magGrav lt 0) magGrav 0 body.force 1 magGrav Math.cos(angleToBody) body.force 0 magGrav Math.sin(angleToBody) This function is applied to each object on p2's step, attracting it closer to the black hole. Asteroids function addAsteroid() var bx blackHoleBody.position 0 var by blackHoleBody.position 1 var a Math.random() (Math.PI 2) var dist 3 (Math.random() 3) var x dist Math.cos(a) var y dist Math.sin(a) var vx ? var vy ? var asteroidBody new p2.Body( mass 10, position x,y , velocity vx, vy ) So my question is, how can I calculate velocity x y (or force x y ideally) to get these objects, based on their position, distance and the force of attraction from the black hole? |
2 | Why Won't Image Drawing Work In JavaScript In my game at the beginning the first thing that you'll see is a campfire with this code var campfire new Image() campfire.onload function () ctx.drawImage(campfire, campfireX, campfireY) campfire.src "Sprites Campfire.png" However, it doesn't work, I put an alert("All systems a ok") at the end and i get the alert so i don't understand why it's there. You can find the actual image file here and the full code here. Sorry if I didn't format this well or something, I'm not very good at this 3 This may seem similar to an older question of mine in which I stated how to add a sprite onto the canvas, though in this case, I'm asking why the image doesn't appear on the canvas at all, even though there's no errors. |
2 | How to work with edge Texture Im not sure if i use the right terms, but im not able to find something to start with. Im trying to develop a little HTML5 game. I have a ground with a texture and now I want to make a surrounding texture. The texture is an image wich should be bend around the ground. At the moment im using easelJS for display my images textures. So im looking for some sort of Tutorial Script Advice. Im not even sure if I can bend a image in javascript. So the worst case I can think of is split the image in 100 pieces and then put it back together and rotate each piece. for example like this |
2 | Can I have keyboard controls in an MMO and still do movement calcuation in the server? I'm trying to decide between keyboard and mouse movement controls for a web based multiplayer. It would be quite resource intensive to use the WASD keys and AJAX the server with controls every second. Can I implement WASD key movement and still have the server do all the movement calculations (to deter cheating)? |
2 | Using dom elements for game interaction slow performance I have a need for my html5 game (using melonjs) to allow users to click tile areas on the map. The idea is it will show a css styled hover area. The browser tested is chrome. I could do this natively in the game engine but the styling options available for canvas entities is limited. So I went with creating a dom element for each item in the canvas map. As the player moves, I update only the positions of the dom elements which are on the viewport. Probably 70 total elements are created and only 2 3 are on the screen updating at any given time. I'm pretty surprised how slow it's making my browser. So my questions are why would updating 2 3 elements as the player moves be so slow? is it better to remove elements when offscreen then readd when they are back on, even though they arent updating as they move off screen? should I just scrap the dom solution altogether and rely on the api the canvas and game engines provide for styling |
2 | Why cap game loop delta time? I was reading some game's source code on Github and saw this game loop implementation for the first time var lastTime 0 var maxTime 1 30 param DOMHighResTimeStamp curTime requestAnimationFrame provides this value automatically this.loop function(curTime) requestAnimationFrame(Game.loop) Same as division by 1000 var dt (curTime lastTime) 0.001 if(dt gt maxTime) dt maxTime for(var i 0, len boards.length i lt len i ) if(boards i ) boards i .step(dt) boards i .draw(Game.ctx) lastTime curTime The key thing The game updates and draws at every step, but the delta time is capped at the desired maximum delta. That way, if a frame takes too long, the next frame steps with a constant delta. What are the pros and cons of this approach? I imagine it's useful for preventing huge entity movements caused by a long timestep, but can it cause problems? Edit Use curTime as provided by window.requestAnimationFrame in order to simplify stuff and avoid comments that don't deal with my main question. |
2 | How to display a lot of small objects using WebGL? Introduction The game scene contains a lot of 10x10 pixel elements for 1980x1200 px. screen the number of elements on the scene can vary from 0 to 23760 (elements cannot intersect). The live example http fintank.ru game The entire game space comprised of tiles each tile is responsible for some area and keeps elements for that area (similar to google maps). Each tile exist as 2 entities S and G. S is a set of elements in the tile, G is rendered image of a tile. When the server put remove elements to the tile, we change S and then re render the G. To draw a frame (at 20 fps) I just put the G of each visible tile using the putImageData(). That is done without WebGL. The question What is the most CPU effective approach to implement such many elements management using WebGL? Should I render each tile to a texture or each element may be implemented as a separate textured rectangle? The main concern is that each tile may be updated 30 60 times a second (elements adding removal). How to avoid memory leaks (how to reuse buffers?) if we make many new textures every second? What is the most effective way to manipulate pixels during rendering a 100x100 tile? How to avoid re uploading the unchanged textures to graphic card? |
2 | how to detect if a line is crossing another shape in javascript? given the situation here http jsfiddle.net h902cLpy is it possible to detect that a line going from A to B does cross another shape while A to C doesn't? |
2 | Animating a background 'pulse' with easing equation I'm trying to find a suitable easing equation (or other method) to animate an object so that it 'pulses' (imagine a 'spike' on a music visualiser, or see the image I drew badly below) 'v' is the value I'm using to scale. 't1' and 't2' mark the end of a single pulse. The game I'm working on is a puzzler, but I'd like to have objects in the background pulse in time with user selected music. I'm sure it's just a case of knowing what to search for, but any advice would be appreciated on how best to achieve this. |
2 | Increasing speed of circle over time as linear with Box2d Assume that there is a circle and it can be moved by using keyboard arrows.Is required that increasing speed over time like increasing car speed. For example max speed is 25 and time to reach max speed shall be 5 sec. Over 5 sec the speed will reach to max speed. Does Box2d handle that situation?. I tried setting linear valocity but it seems to make the circle have constant speed instead of increased speed over time. Thank You! Note I'm using Box2DWeb Javascript port of Box2D. |
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 | How to calculate whether a cuboids face edge is infront of or behind another for sorting I'm building an isometric game, I want to position and sort objects in a particular way. All my entities have 3d bounds which determines their cuboid, looking my example, a different edge is used to decide if a cuboid is in front of another, depending on whether the point b2 is left or right of a2. I have already calculated all the points a1,a2,b1,b2 which are x,y,z I think I basically need to virtually draw "aedge" and "bedge", and compare some intersection. If b2 is right of a2 the green cuboid (b) is consider in front of the red cuboid when bline is south east of aline. If b2 is left of a2 the green cuboid (b) is considered in front of the red cuboid when bline is south west of aline. Please forgive my ignorance here, I'm sure there's some terminology I should have used here. I'm struggling to put down in words what it is I need. |
2 | Selecting objects on a 2D map I have a object selection function by checking the mouse click and getting the relevant object. How ever there is a rare situation where if one object is partially behind the other then both objects are in the given area so im wondering how I can make the game know which one was selected, as currently my method does not know. This is my function that works it out function getobj(e) mx e.pageX curleft mouse click x my e.pageY curtop mouse click y function searchSprites(sprites, x, y) var matches , i 0, data null for (i 0 i lt spritea.length i) data spritea i .data if (x gt data 0 amp amp y gt data 1 amp amp x lt data 2 amp amp y lt data 3 ) var imageData ctx2.getImageData(x, y, 1, 1) if(imageData.data 3 ! 0) return spritea i .id i spritea.length res searchSprites(spritea, mx, my) bid res 0 if(bid '1') alert('You selected the skyscraper in front!') else if(bid '3') alert('You selected the skyscraper behind!') Image of the map It keeps telling me I clicked the skyscraper behind which is not necessarily what the user is trying to do. How can I improve the accuracy of this ? |
2 | HTML5 game Secure way of saving score I wrote a pretty basic game for colleagues to play the player shoots on an enemy which has 50 lives while other smaller enemies pop randomly on the screen. The goal is to kill the main enemy as fast as possible. One important point the game is written in javascript (using HTML5 canvas). At the end of the game, I send the score and username to my php function in Ajax, and that's where I have trouble I find it really hard to restrain my colleagues from cheating. Here are the different ways of cheating I've noted so far Changing the score sent during the ajax call At the beginning of the game, reducing the number of lives of the enemy At the beginning of the game, reducing the probability for enemies to appear Here are the solutions I implemented to counter that cheating Create an array that I fill each time I enter the game loop with "delta", the time between that frame and the previous. I send that list to my php save function and then check that the total time of the deltas is equal to the score sent. Create an array where I store the times when the Enemy loses 1 life. Then in the php save function I check that the list trully has 50 elements, and that the time between 2 elements is not less than a certain value Create an array where I store the time when an enemy appears. Then in the php save function I check the number of enemies is not less than a certain number. The 2 first points seem good enough for me it becomes too much trouble for anyone to try and cheat that. The last point is causing me much trouble. I cannot stop the user from changing apparition rate to 0, then in the ajax call just fill the array with 30 values, that seems pretty easy. This is my first try with this kind of issue, so I have several questions Am I on the good way? Are there any "patterns" I am missing for this kind of issue? What would be your approach? What would you do? How to make it even more difficult for the players to cheat? |
2 | why are my client and server physics not syncing up? node.js and html5 My server looks like this var timestep 1000 30 var delta 0 var lastFrameTimeMs 0 function panic() delta 0 var update function() currentTime Date.now() if (currentTime lt lastFrameTimeMs (timestep)) setTimeout(update) return delta currentTime lastFrameTimeMs lastFrameTimeMs currentTime let numUpdateSteps 0 previousTime currentTime while (delta gt timestep) player.update(timestep 1000) delta timestep if ( numUpdateSteps gt 240) panic() fix things break bail out setTimeout(update, 60) setTimeout(update, 60) and then my client looks like var timestep 1000 30 var delta 0 var lastFrameTimeMs 0 function panic() delta 0 discard the unsimulated time ... snap the player to the authoritative state function mainLoop(timestamp) Throttle the frame rate. if (timestamp lt lastFrameTimeMs (timestep)) requestAnimationFrame(mainLoop) return delta timestamp lastFrameTimeMs lastFrameTimeMs timestamp let numUpdateSteps 0 while (delta gt timestep) if(player ! undefined) player.update(timestep 1000) delta timestep if ( numUpdateSteps gt 240) panic() fix things break bail out requestAnimationFrame(mainLoop) requestAnimationFrame(mainLoop) I've been trying to get this work for days. I'm trying to have a fixed time step on both the client and server so they both simulate physics exactly the same down to the decimal point. But for some reason my client is moving much faster than my server. I used this article as a reference. https www.isaacsukin.com news 2015 01 detailed explanation javascript game loops and timing Where am I doing something wrong in one of my loops? They both use a .033333333333 timestep like I want them to, but they move at different speeds. What am I doing wrong? |
2 | HTML5 clicking objects in canvas I have a function in my JS that gets the user's mouse click on the canvas. Now lets say I have a random shape on my canvas (really its a PNG image which is rectangular) but i don't want to include any alpha space. My issue lies with lets say i click some where and it involves a pixel of one of the images. The first issue is how do you work out the pixel location is an object on the map (and not the grass tiles behind). Secondly if i clicked said image, if each image contains its own unique information how do you process the click to load the correct data. Note I don't use libraries I personally prefer the raw method. Relying on libraries doesn't teach me much I find. |
2 | Instantiate objects that share same variable I'm just wondering how to instantiate the same objects that all share the same variables, except their positions. I'm basically working on the scene of my HTML5 game, and I've build a streetlamp post that turns on and off. All the lamps will have the same variables, such as Image, Size, on off function. The only thing that will be different will be the position x and y. I've built my lamp within a variable function (I think they're called that var ), and within my actual game DrawFunction, I'm calling LampPost.draw() . Is it possible to do something like this? LampPost(0,0) LampPost(100, 0) LampPost(200, 0) etc ... and then possibly place each instantiate Lamp within an array? This is a snippet code for the lamp var LampPost lamp xsprite 0, lamp ysprite 0, light xsprite 0, lightysprite 0, x 440, y 320, Flicker effects lightFlicker 0, seconds Off 0, seconds On 0, randomLength Off 500, randomLength On 150, draw function(x, y) this.x x this.y y ctxPropsOver.setTransform(1, 0, 0, 1, Map.x gameWidth 2, Map.y gameHeight 2) ctxPropsOver.rotate(Math.PI 25) ctxPropsOver.clearRect(0, 0, 1000, 1000) ctxPropsOver.globalAlpha this.lightFlicker ctxPropsOver.drawImage(imgLights, 0, 36, 500, 463, 60 this.x, 190 this.y, 500, 463) ctxPropsOver.globalAlpha 1 ctxPropsOver.drawImage(imgLights, 0, 0, 210, 36, 0 this.x, 0 this.y, 210, 36) UPDATE Okay, So I've converted it into an instance of object, this is what I have so far LampPost function(lx, ly, la) x lx 500 y ly 335 centrex 12 centrey 17 rotate la 8 LampPost.prototype.draw function () ctxPropsOver.setTransform(1, 0, 0, 1, ( Map.x gameWidth 2), ( Map.y gameHeight 2) ) ctxPropsOver.clearRect(0, 0, 1000, 1000) ctxPropsOver.save() ctxPropsOver.translate(this.x, this.y) ctxPropsOver.rotate(this.rotate Math.PI 180) ctxPropsOver.translate( this.centrex, this.centrey) ctxPropsOver.globalAlpha this.lightFlicker ctxPropsOver.drawImage(imgLights, 0, 36, 500, 463, 60, 190, 500, 463) ctxPropsOver.globalAlpha 1 ctxPropsOver.drawImage(imgLights, 0, 0, 210, 36, 0, 0, 210, 36) ctxPropsOver.restore() |
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 do I maintain an online users list? In a multiplayer JavaScript game client, is it a good idea to poll the server periodically to refresh online user list, or keep track of joined left users? Is there a better option? |
2 | Detecting keys presses between keyboard layouts, operating systems and javascript I've recently encountered a few headaches when I tried to detect key presses for a custom game engine to supports Windows, MacOS, Linux, and WebGL. Naive approach At first I naively thought that using GLFW's keycodes instead of scancodes will be the best solution to cover as many operating systems as possible. I later found out that if the player has a different keyboard layout, the keys will be bound all over the place instead of having the WASD keys (regardless of what character they represent) sit together. Problem 1 So then I moved over to using scancodes. So this works great (other than having a different set of scancodes for each operating system) but it also introduces my first issue. Since scancodes are position based and defined as integers, how will I display to the player what character, for their unique keyboard layout, is currently bound in the game's "Keyboard Settings" dialog. I don't imagine detecting a keyboard layout is plausible (might even be impossible with Javascript since I don't have access to OS calls). Problem 2 My second issue is when the game is deployed with WebGL. In Javascript the keyCode value is just fed to the browser from the underlying operating system. What this means is I have to check the OS at runtime and remap all the keybinds based on the operating system. This is a nightmare because, if the user has customised keybinds (stored to his cloud profile) that was created on MacOS but then later opened up on Windows, then the code will have to do three remaps in order to, get the OS when keys where customised, then get the current OS, and then the conversion between the two prior to taking into consideration the customised remaps... Is there not a better way?! This would also mean I will have to send all the keycode constants for everything possible operating system to each user. Resulting in a lot of unnecessary boat in the Javascript file. Just assume? It seems like the big game engines out there have this issue solved and I am curious how they got around these issues. Do they just assume all players use QWERTY keyboards at the risk possibly frustrating a certain audience until they remap the keys ingame? And do they assume all browser based games are played on Windows, MacOS, and Linux to keep the javascript OS detection to a minimal? (effectively losing mobile players) |
2 | Difficulty aligning isometric tiles I'm trying to render isometric terrain in javascript. Currently, my tiles are being drawn with small gaps between them I want the tiles to line up with no pixel gaps in between My rendering function is like this var screenX (x 60 2) (y 60 2) var screenY (y 30 2) (x 30 2) console.log(screenX, screenY) context.drawImage(img, screenX, screenY, 60, 30) Btw, my image is 30x15. Can you help me with this problem? EDIT var screenX (x 56 2) (y 56 2) var screenY (y 28 2) (x 28 2) console.log(screenX, screenY) context.drawImage(img, screenX, screenY, 60, 30) It works, but I want to find a general solution |
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 | How To Animate A JavaScript Function I've been making this game where one of the characters, The Bandit, runs away from you mistaking you for a zombie. However, I can't seem to be able to animate the bandit. Is there a way I could use this w3schools example and make it fit with this canvas function? The code for bandit is here or the second site function drawBanditFacingDown() His face ctx.fillStyle " FFDE7A" ctx.fillRect(banditX, banditY, 25, 25) His left eye (your left not his) ctx.fillStyle "black" ctx.fillRect(banditX 5, banditY 5, 5, 8) His right eye (again your right) ctx.fillRect(banditX 15, banditY 5, 5, 8) His bandit thing on his mouth? I don't know what it's called ctx.fillStyle "red" ctx.fillRect(banditX, banditY 15, 25, 10) His shirt ctx.fillStyle "black" ctx.fillRect(banditX 5, banditY 25, 16, 25) His arms His right arm (YOUR RIGHT!!!!) ctx.fillStyle " FFDE7A" ctx.fillRect(banditX 21, banditY 25, 8, 20) His left arm (On your left side) ctx.fillRect(banditX 3, banditY 25, 8, 20) His pants His right pant leg (ur right) ctx.fillStyle " 11226B" ctx.fillRect(banditX 12, banditY 49, 8, 20) his left pant leg ctx.fillRect(banditX 5, banditY 49, 8, 20) ctx.fillStyle "black" ctx.fillRect(banditX 11, banditY 53, 3, 15) his shoes 200 LINES!!!!!! ctx.fillStyle "black" ctx.fillRect(banditX 5, banditY 68, 15, 5) |
2 | Interpolation using cubic Bezier curves I am trying to create an interpolate function for an animation library to achieve a tweening effect between frames. I want this to work with Bezier curves. I have created a jsFiddle (here) of my progress so far. I am trying to create a linear tween using this bezier definition p0 new Vector(0,0), Start point p1 new Vector(0,0), Control point 1 p2 new Vector(1,1), Control point 2 p3 new Vector(1,1) End point I have implemented the interpolation function from this tutorial. var u 1 t var tt t t var uu u u var uuu uu u var ttt tt t var p p0.multiply(uuu) p p.add(p1.multiply(3 uu t)) p p.add(p2.multiply(3 u tt)) p p.add(p3.multiply(ttt)) The problem I am having is that when I run the function, the animation does not appear to be linear, but rather like 'ease in out'. Ideally I would like the linear animation to work the same as this CSS transition. Can anybody see why it is not animating in a linear fashion? |
2 | Custom lookAt function goes wild I have written a custom lookAt function based on a lot of posts from all over the net, and it works very nice... except when a rotation (which is stored in a quaternion) crosses some 'threshold'. However, it works flawless when the camera's position is on the same horizontal plane as the model I'm lookingAt On the below GIF, all I do is hold a key to lookAt the model together with a left arrow key to move the camera along the right vector My following understanding about how this function should look like (in a brief) 1 .Calculate a quaternion rotation needed to rotate an object from it's facing vector and a target vector. 1.a. Calculate an angle between those vectors by taking their dot product and a perpendicular axis by taking their cross product. 1.b Convert angle axis info to a quaternion using this formula. 2 .Multiply the main quaternion rotation by the quaternion received above. If I'm right, I believe that I may have a bug in my code, but I'm not sure. My code below lookAt function(vec) if (this.position.isEqual(vec)) return this.rotation.multiply(new Quaternion().twoVecToQuat(this.rotation.getForwardVector(), this.position.sub(vec))) MVMatrix.setRotation(this.rotation.quaternionToMatrix()) , And the twoVecToQuat function based on Ogre3D quaternion library twoVecToQuat function(v0, v1) v0.normalize() v1.normalize() var dot v0.dot(v1) If dot 1, vectors are the same if (dot gt 1) return this.makeIdentity() If vectors are opposite if (dot lt (1.0e 06 1)) var fallbackAxis new vec3().make(1, 0, 0) fallbackAxis.crossSelf(this) If collinear, pick another vector if (Math.areScalarsSimilar(fallbackAxis.length(), 0)) fallbackAxis.make(0, 1, 0) fallbackAxis.crossSelf(this) fallbackAxis.normalize() this.axisToQuaternion(Math.PI, fallbackAxis) else var sDot Math.sqrt((1 dot) 2) var invSDot 1 sDot var tempVec v0.cross(v1) this.x tempVec.x invSDot this.y tempVec.y invSDot this.z tempVec.z invSDot this.w sDot 0.5 this.normalize() return this , UPDATE Slin's solutions proved to be working (that one about calculating lookAt matrix), but I still don't know where is the bug in the quaternions library code. Working lookAt function below lookAt function(at) if (this.position.isEqual(at)) return var zAxis this.position.sub(at).normalize() var up upVec() World's up vector instead of camera's up vector will unroll the camera var xAxis up.cross(zAxis).normalize() var yAxis zAxis.cross(xAxis) MVMatrix.make( xAxis.x, xAxis.y, xAxis.z, yAxis.x, yAxis.y, yAxis.z, zAxis.x, zAxis.y, zAxis.z, this.position.x, this.position.y, this.position.z) this.rotation.matrixToQuaternion(MVMatrix) this.copyEulerAngles() , |
2 | How to draw objects that have a smaller Y axis first? In my game there is a large 2D map of various objects. Example. As you see, upon creation objects of the same type (trees for example) are placed correctly, but objects of another type (enemies) are placed on top of the no matter the position. Now, how can I arrange that everything is drawn according to it's position? Another example (the dog should be drawn before the tree, and not on top of it) |
2 | Limit rotation to certain angles for transform.rotate I'm working on a small project to learn Blender and Unity, and one issue I recently came across is that while I can have the turret of my tank rotate on the z axis based on mouse movements, I can't for the life of me figure out how to lock it to certain angles. My current approach was to use Mathf.Clamp to limit the range of values that I could pass to the rotate function, but that doesn't seem to have done anything at all, even though when outputting the value Clamp produces, I can tell it doesn't go over my specification. The code I have enum RotationAxes MouseX, MouseY, MouseXandY var axes RotationAxes private var MouseX RotationAxes.MouseX var sensitivityX float 15F var minimumZ float 35 var maximumZ float 35 function Update () if (axes MouseX) yRotation Input.GetAxis("Mouse X") transform.eulerAngles Vector3(0, 0, yRotation) transform.Rotate(0, 0, Mathf.Clamp (Input.GetAxis("Mouse X") sensitivityX, 30, 30)) function Start () |
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 | Is it sound to use javascript for cross platform game scripting instead of lua? I might need web clients for my game I have been looking around for clues on the subject but I'm not convinced to commit to javascript as my primary scripting language. Currently I have started with lua. But I fear it will be a limiting choice for my future projects which include web clients for my games. So basically I would like to know if you think it would be a viable solution for handheld devices and consoles. Also, I would be glad to hear about anyone who had much success with javascript in cross platform games failures with javascript scripting engines restrictions within console SDKs that would prevent this type of solution successes using lua in web games |
2 | How to color each letter text in Phaser.js? I have a text created with text object (game.add.text) and I would like to color each letter differently if that is possible. If not, how can I achieve this? |
2 | To canvas, or not to canvas, when building browser based games? Background I have extensive development background, but the last time I coded a game was many years ago. My Javascript skills are quite limited, and I intend to improve them by building a simple game Tetris, Pac man, or something of that complexity level. Question It seems to me that a fundamental choice I need to make is whether I should render on a lt canvas gt element or not. With a canvas, I have basic tools for rendering points, lines, and more complex things on top of that. Presumably there are, or will be, also various frameworks to help with this. Without a canvas, I could keep my objects in the DOM tree, like a regular webpage, only quite complex, with many overlapping elements. Is one approach better than the other? Are they mutually exclusive? How do I know which to pick? |
2 | Collision between free player and tilebased map so I'm working on some sort of platformer in javascript where the map is tilebased but the player can move freely. Now, i have a problem with collision detection response. It's kind of obvious what I'm trying to do, I don't want the player to walk into walls and fall into the ground so i need collision stuff. Basic info The player is the same size as the tiles The tiles are 8x8 The map is stored in an array like this 0, 0, 0, 1, 1, 1, 0, 0, 0 . So if the map was 3x3 there would be a horizontal line in the center. I feel that the system that I'm using is very inefficient and there are some problems with it sides The tiles are 8x8 wide so i divide the players position by 8 to get the current tile the players is occupying. The player.y mapWidth player.x thing gets the tile at that position in the map array I use Math.floor instead of round to get the tile to the left of the player if (map (Math.round(player.y 8) mapWidth) Math.floor(player.x 8) 1) sides.left true else sides.left false if (sides.left) Set the players x position to exactly outside the wall. player.x Math.floor((player.x 8) 1) 8 Now this works fine for walls but when you use it on the ground it works but it glitches on corners. For example if the player half way over an edge it falls through the tile and is pushed to the side. Is there a better way to do this and if not, how do i fix the ground collision? |
2 | How do I make an HTML5 canvas tiled map with tiles which have other than squared edges? I'm creating an HTML canvas map and I'm trying to have the edges of the tiles not appear square, as in the tiles merge in to each other. I've scoured the internet for hours but can't seem to find anything. How would I go about doing this? Dropbox link to project I've included the used images so when the project is downloaded and run on the browser, the map should look like the following picture. This is not how I want it to look but how it currently looks. I know it's probably not possible to get this exact effect using a tile based map, and it's not a perfect representation, but here's a general idea of what I want to accomplish. Notice how the corners are no longer squared but have a more rounded look and appear to be blending in with the next color tile. That's my goal. Thanks in advance. |
2 | Any idea to be able to make the character still continue the game until no heart left I am newbie I am making a 2d game in unity 3d my code for the character game over is this.. I can get the heart less one heart if game over but turn back to five again I just want to decrease heart whenever character die until it loss all the five heart and my code for the heart is this... function Start () coins PlayerPrefs.GetInt("Coin") moveSpeed 10 anim GetComponent(Animator) MainCode.Hearts 5 function Update () transform.rotation.z 0 if(Input.GetKey(KeyCode.UpArrow)) transform.position.y moveSpeed Time.deltaTime if(transform.position.y lt 5) Application.LoadLevel(Application.loadedLevel) MainCode.Hearts 1 if (MainCode.Hearts lt 0) GameOver() var image GUITexture var Image 01 Texture2D var Image 02 Texture2D var Image 03 Texture2D var Image 04 Texture2D var Image 05 Texture2D var Image 06 Texture2D function Update if(MainCode.Hearts 5) image.texture Image 01 if(MainCode.Hearts 4) image.texture Image 02 if(MainCode.Hearts 3) image.texture Image 03 if(MainCode.Hearts 2) image.texture Image 04 if(MainCode.Hearts 1) image.texture Image 05 however its not working properly any help would be really much appreciated thank you in advance |
2 | How to inform pathfinding of solid objects blocking path? I'm sure this has been asked before, but I couldn't find the thread. Let me know if you can locate the duplicate. So, I have a my level is an array of tiles, where a tile can either be solid or walkable. I then use A star to path find my enemies from one location of the floor to another. The issue is that I also have solid entities. As an example, I may spawn 3 breakable vases at a certain location. They can be larger or smaller than a single tile, and they are just objects in the world, not tiles themselves. Because they are not a part of the A star grid (can they? they're larger or smaller than a tile, and their position is not locked to the grid), the path finding is not aware of their existence, since it only operates on its grid. As a result, sometimes the chosen path for the enemy to follow flows through the solid vases, so the enemy just gets stuck at that location. Is there a solution that alleviates this problem? I want the enemies to path around the vases (until they're destroyed, of course), instead of just getting stuck trying to unsuccessfully move through them. |
2 | Implementing navigatable achievement menu in javascript I am in the process of learning javascript for game design, and wanted to make a separate achievement page that the user can navigate to that will allow them to check their achievements on various games. (at the moment I am not concerned with implementing localstorage cookies etc, I just want to work on the page for now) So the requirements of my base idea is as follows Able to drag around the viewport page to view all the achievement categories as they will likely not all be in view on smaller screens Able to click on a category to open a small box containing all achievements belonging to that game category Able to mouse over all achievements in the boxes to get text descriptions of what they are OPTIONAL have lines connecting each box on the "overworld" to show users where nearby boxes are if they are off screen At first, I thought I would need canvas to be able to do this. I learned a bit about it and got decently far until I realized that canvas has a lot of restrictions like not being able to do mouseover events unless manually implementing each one. Here is the current progress I was at in doing a test run of learning canvas, but it's not very far var canvas document.getElementById('canvas') var ctx canvas.getContext('2d') canvas.width window.innerWidth canvas.height window.innerHeight function resize() canvas.width window.innerWidth canvas.height window.innerHeight ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.translate(panning.offset.x, panning.offset.y) draw() window.addEventListener("resize", resize) var global scale 1, offset x 0, y 0, , var panning start x null, y null, , offset x 0, y 0, , var canvasCenterWidth (canvas.width 2) var canvasCenterHeight (canvas.height 2) function draw() ctx.beginPath() ctx.rect(canvasCenterWidth, canvasCenterHeight, 100, 100) ctx.fillStyle 'blue' ctx.fill() ctx.beginPath() ctx.arc(350, 250, 50, 0, 2 Math.PI, false) ctx.fillStyle 'red' ctx.fill() draw() canvas.addEventListener("mousedown", startPan) function pan() ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.translate(panning.offset.x, panning.offset.y) draw() function startPan(e) window.addEventListener("mousemove", trackMouse) window.addEventListener("mousemove", pan) window.addEventListener("mouseup", endPan) panning.start.x e.clientX panning.start.y e.clientY function endPan(e) window.removeEventListener("mousemove", trackMouse) window.removeEventListener("mousemove", pan) window.removeEventListener("mouseup", endPan) panning.start.x null panning.start.y null global.offset.x panning.offset.x global.offset.y panning.offset.y function trackMouse(e) var offsetX e.clientX panning.start.x var offsetY e.clientY panning.start.y panning.offset.x global.offset.x offsetX panning.offset.y global.offset.y offsetY body overflow hidden canvas top 0 left 0 position absolute lt canvas id "canvas" gt lt canvas gt So I guess my question is now what is the best way to implement this? Is it feasable to do it with canvas, or should I just scrap that and try to figure out something with div movement? Should I be concerned with performance issues and should that affect how I implement it? |
2 | Three.js camera turning leftside right In Three.js I am trying to implement an orbiting camera can be rotated around the x and the y axis. I am using these two functions function rotateX(rot) var x camera.position.x, y camera.position.y, z camera.position.z camera.position.x x Math.cos(rot) z Math.sin(rot) camera.position.z z Math.cos(rot) x Math.sin(rot) camera.lookAt(scene.position) function rotateY(rot) var x camera.position.x, y camera.position.y, z camera.position.z camera.position.z z Math.cos(rot) y Math.sin(rot) camera.position.y y Math.cos(rot) z Math.sin(rot) camera.lookAt(scene.position) Now the x rotation works fine but the y rotation does not. Once I go over the top of the model as in that the camera's z position becomes negative then suddenly the lookAt method rotates the camera by PI amount on the Z axis and suddenly the left side of the model is on the right and vice versa. Now I can fix this by checking for a negative Z and then just fixing the camera's rotation but this then causes a malfunction when using x ad y rotation at the same time, the x then suddenly gets this inverting behavior. How should I go about fixing this? |
2 | Changing balls direction in Pong I'm making a Pong game to get started with game developement but I've run into a problem that i can't figure out. When trying to change the balls direction it doesn't change. This is the relevant code function moveBall() this.speed 2.5 this.direction 2 if(this.direction 1) ball.X this.speed else if(this.direction 2) ball.X this.speed function collision() if(ball.X 500) moveBall.direction 2 if(ball.X 300) moveBall.direction 1 Why doesn't it work? I've tried many different ways, and none of them seem to work. The moveBall.direction changes though, since it alerts the new direction once it reaches the defined ball.X position. If someone could help me I would deeply appreciate it. I've included a JSFiddle link. http jsfiddle.net hustlerinc y4wp3 |
2 | Colouring greyscale images sprites for HTML canvas What is the best method to colour in sprites at runtime using the canvas element and javascript? I know there are various blending modes using globalCompositeOperation, but I don't know how best to utilise this. I'll break my question down into the following Is there an optimum way to export greyscale images so they can be easily re coloured later? (At the moment, the images are created with colour in Photoshop or a similar package and then turned into a greyscale and exported from there before I even touch them) With these greyscale images in place, what method makes colouring them with any colour possible? (They must retain the shading etc) I've tagged this with HTML5 and Javascript, but any advise from other platforms would be helpful. Edit Here's an example greyscale output of the image on the left. I want to be able to restore it to the same colour, but also be able to blend it with other colours for different shades of skin. |
2 | Keyboard input conflict in wall jump I'm trying to make a Megaman style wall jump in my 2D platform game with JavaScript. The character can do A,B,C motions when it sticks the wall My problem is that when I trying to jump off the wall(motion C), it goes to motion A or B first, C was not happened. I think the keyboard input was conflict but I have no idea how to handle it. Here is my current code if(key 'right' amp amp key 'jump' ) it doesn't work jump off the wall else if(key 'right' ) leave the wall else if(key 'left' ) stick the wall else release all keys falling down Please, Any help would be appreciated. |
2 | 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 | How do I play audio with Javascript? I want to add a short audio track to a game of concentration I'm coding. I want the sound to occur when the user has won the game. How do I go about doing this? I would really appreciate the help, thank you. |
2 | How to get projectile direction vector in a 2d grid? I am having trouble figuring out how to trace the path of my projectiles in an Asteroids clone. Currently the ship is locked to the center of the screen and can be rotated a full 360 degrees. I know the angle the ship is pointing at any given time, but I am not sure how to calculate the vector that the projectile should use for its trajectory. I know that I can find the correct vector by subtracting the end point from the start point.. but the issue is that I do not know the end point. Theoretically.. the end point is whenever the projectile touches the edge of the screen or some object. This is the current game code https jsfiddle.net m6sxrk8w just using a hardcoded movement vector of x 1, y 1 . Can anyone give some advice on how to dynamically determine the true vector given the current direction of the ship? There must be some simple math I am missing here... |
2 | In Phaser, how should I be managing state? I'm quite new to Phaser and JavaScript really confused about state management. Phaser has lots of documentation and info on the net, but everyone seems to be doing it a different way. An example var game new Phaser.Game(800,600, Phaser.AUTO, 'phaser demo', preload preload, create create, update update, render render ) function preload() ... function create() ... function update() ... function render() ... Another window.game new Phaser.Game(800, 600, Phaser.AUTO) all other states are in different files module.exports preload function() ... , create function() ... , update function() ... I would be grateful for a simple overview of properly handling states. |
2 | How to solve this card game turn requestes clashing issue So I am developing a poker card game using JS node.js socket.io. It is turn based game. There will be a host and 4 other players.The flow is the players need to make a yes no choice, then the host need to make a yes no choice upon players' move, then players will need to make another yes no choice, then the server will determine who wins. Put simply, 1 Host set up the hand 2 inform all players 3 A player make a move(ticking yes or no) 4 this move will show up on the host's screen 5 the host need to make his her move(ticking yes or no) 6 the host's move show up on players' screen, they make another yes no choice 7 the server determine who wins. The issue lies on step 5. There will be multiple moves waiting for the host to process. Now the current design is all moves are shown by the form of a custom confirm box. It has yes no button. It works perfect when there is only one host and one player. But when there is more than 2 players, there is a serious clashing problem. If player A makes a move, it shows on the host's screen, and before the host ticking anything, player B makes a move and then player B's move (confirm box) will replace player A 's confirm box. In this case the host will not be able to process player A's move and the game cannot finalise. How to get this clashing issue sorted? I hope I am not making this issue sound too complicated but I have been scratching my head. |
2 | Game loop with fixed timestep gives strange result So I've read the famous article at http www.koonsolo.com news dewitters gameloop comment page 2 comments which describes different methods of implementing a game loop. I've tried to implement the final method that is described in the article in Javascript (ignoring interpolation for the time being) var Timer pastTime 0, currentTime 0, started false, starts the timer start function() if(!this.started) this.started true this.pastTime new Date().getTime() , gets the time in MILLSECONDS getTime function() return new Date().getTime() this.pastTime , stops the timer but does not reset it (i.e. getTime() can still be called to get the time between start() and end()) end function() if(this.started) this.currentTime new Date().getTime() this.started false return this.currentTime this.pastTime , resets the timer reset function() this.pastTime 0 this.currentTime 0 this.started false var maxFrameSkip 5 var nextTick new Date().getTime() var TICKS PER SECOND 25 var tickTimeMillis 1000 TICKS PER SECOND var ticksPerSecondReal 0 var ticksCounter 0 var timer Object.create(Timer) var loops 0 function gameLoop() loops 0 timer.start() while(new Date().getTime() gt nextTick amp amp loops lt maxFrameSkip) update() ticksCounter nextTick tickTimeMillis loops draw() if(timer.getTime() gt 1000) ticksPerSecondReal ticksCounter ticksCounter 0 timer.reset() console.log(ticksPerSecondReal) window.requestAnimationFrame(gameLoop) gameLoop() So the problem that I'm having is that the console.log(ticksPerSecondReal) should always be giving me 25 because that's the constant ticks per second that I want and have set up. What I end up getting is an alternating number that is 25 and 26. So periodically ( 1 second) it will be 25 and then 26 and then 25 and so on. And sometimes (much less frequently) it will even give a result of 27. It keeps switching back and forth when it should be constant at 25. What is the issue here? |
2 | how to join the body of snake in 2D snake game i'm making a snake game in javaScript from scratch. The problem is that the snake looks disjoint(see image). How can I connect the body(rectangles) of the snake? here is the code of drawing snake paintSnake(margin) draws the body of the snake this.snake.forEach((egg) gt console.log(egg) const isSnakeHead egg.cellX this.headCellX amp amp egg.cellY this.headCellY if (!isSnakeHead) this.ctx.fillStyle " 9ef739" this.ctx.fillRect(egg.cellX this.cellSize margin, egg.cellY this.cellSize margin, this.cellSize 2 margin, this.cellSize 2 margin) ) snake head this.ctx.beginPath() this.ctx.lineWidth 4 this.ctx.strokeStyle "red" this.ctx.rect(this.headCellX this.cellSize margin, this.headCellY this.cellSize margin, this.cellSize 2 margin, this.cellSize 2 margin) this.ctx.stroke() let head X this.headCellX this.cellSize margin, Y this.headCellY this.cellSize margin, width this.cellSize, height this.cellSize const args head.X, head.Y, head.height, head.width draw the head of the snake if (this.direction "up") this.ctx.drawImage( snakeHeadUpImg, ...args) else if (this.direction "down") this.ctx.drawImage( snakeHeadDownImg, ...args) else if (this.direction "right") this.ctx.drawImage( snakeHeadRightImg, ...args) else if (this.direction "left") this.ctx.drawImage( snakeHeadLeftImg, ...args) to see the whole code go to https github.com hackasaur snake game blob master main.js i know that the rectangles(body parts) need to be extended in the direction of the next rectangle but how can i achieve this? |
2 | Resource loader for an HTML5 and Javascript game I have made a type to shoot game using HTML5, Javascript and Ruby on Rails. Here is the link for the game Tweetraitor I wanted to make a loader for resources (sounds, images) when the game starts. Currently when the game starts the background image takes time to load and it does not look good. This loader should load all the assets those are used later in the game. Code for the game is here Tweetraitor on GitHub In the current version, all the images are loaded using js in an erb file which controls the game logic. Is there a better way to do this? |
2 | How do I generate a 2d grid based map without screwing it up? I'm relatively new to the mechanics of game development catching up fast, but there are still some things that escape me. For example generating a fully accessible map on a 2d grid. See the example at http crawl.s z.org. Each floor map starts with dozens of winding labyrinthine passages and randomly drops in points of interest temples, boss lairs, bazaars, etc. I know there's a lot of factors that go into this generating passages that always have at least one exit (no isolated tunnels in the walls), making sure passages have at least a one cell width wall between them and adjacent parallel passages, and dropping points of interest in such a way that they connect to the dungeon. I've taken a shot at it, and it's very easy to ranomly place lines in a 2d matrix that represent passages but they're never guaranteed to connect, and it's not nearly as elegant as the maps at the above example. I suppose my question is, what do I need to know to reproduce the example at crawl.s z.org? I know this is a large question I'd be fine with someone handing me a link to a reference site and telling me to learn it there. I'm just new enough at this that I don't even know what terms to google maybe there are names for different generation processes? Available techologies are JS (jQuery) and PHP, so a solution tailored to one of those would be ideal. Thanks! |
2 | Cocos Code IDE unable to find python I am trying to create a new JavaScript project on Cocos Code IDE but every time it immediately give me the error message Unable to find python. Please, click the setting button to set the python path, then python 3.0 or later is not supported. I click the button and I set the path to C Python27 which is the folder of my python installation, and I try again but I get exactly the same error. The version of my python installation is 2.7.8. I am using Windows8.1. EDIT It occurred to me that there is also another error message the python's version must be greater than or equal to 2.7.5 and less than 3.0 But I cannot understand why it does not accept my version(2.7.8). |
2 | How can I make my movement continuous? I'm making a game with simple movement code. I don't want the movement to be too complex since it's going to be a small game once it's done. Right now the character moves 10 units at a time, then stops, then 10 units, then stops, and this looks jerky. I'd like the character to move continuously, without stopping in between. I tried lowering the playerSpeed to make it less jerky, but then the character moved too slowly and players got bored. Instead I want the character to move a little every frame, not a big jump with delays in between. Here's what I've tried so far playerSpeed 10 document.addEventListener('keydown', function(e) if(e.key 'w' amp amp playerY gt 5) playerY playerSpeed ctx.clearRect(0, 0, outerWidth, outerHeight) drawProtagonistFacingUp() if(e.key 'd' amp amp playerX lt outerWidth 50) playerX playerSpeed ctx.clearRect(0,0,outerWidth, outerHeight) drawProtagonistFacingRight() if(e.key 's' amp amp playerY lt outerHeight 100) playerY playerSpeed ctx.clearRect(0,0,outerWidth, outerHeight) drawProtagonistFacingDown() if(e.key 'a' amp amp playerX gt 5) playerX playerSpeed ctx.clearRect(0, 0,outerWidth, outerHeight) drawProtagonistFacingLeft() ) |
2 | How do I make my character jump on a platform? This is the code I've written so far Html lt div id "stage" gt lt div id "splash" class "screen" gt lt h2 gt Land lt h2 gt lt button id "howtobutton" gt Instructions lt button gt lt button id "hsbutton" gt High Score lt button gt lt button id "optionsbutton" gt Options lt button gt lt button id "playbutton" gt Play Game lt button gt lt div gt lt div id "instructions" class "screen" gt lt h2 gt How to Play lt h2 gt lt button class "backtomenu" gt Back to Menu lt button gt lt div gt lt div id "highscores" class "screen" gt lt h2 gt High Scores lt h2 gt (Username), your high score is lt button class "backtomenu" gt Back to Menu lt button gt lt div gt lt div id "options" class "screen" gt lt h2 gt Options lt h2 gt lt button class "backtomenu" gt Back to Menu lt button gt lt div gt lt div id "game" class "screen" gt lt div id "ground" class "platform" gt lt div gt lt div id "score" gt Score lt div gt lt div id "player" gt lt div gt lt button id "btn quit" class "backtomenu" gt Back lt button gt lt div gt CSS div border 1px solid black h2 text align center button display block width 100px margin 10px auto stage width 400px height 400px overflow hidden position relative background image url(http www.hlgjyl888.com data wallpapers 151 WDF 1917288.gif) background size cover splash display block .screen position relative display none width 100 height 100 color white player width 30px height 30px border radius 50 position absolute background color blue bottom 50px top 269px left 100px score position relative top 0px right 5px width 100px btn quit position absolute margin 0 bottom 0px left 0px .platform position absolute background color white .onPlatform background color blue ground top 300px width 400px height 3px JavaScript var gravity 1 var maxheight var timer var jump 32 var velocity 0 var jumppressed false var username prompt("What is your name?") (document).ready(function() (' howtobutton').click(function() showScreen(' instructions') ) (' hsbutton').click(function() showScreen(' highscores') ) (' playbutton').click(function() showScreen(' game') ) (' optionsbutton').click(function() showScreen(' options') ) ('.backtomenu').click(function() showScreen(' splash') ) maxheight Math.round( (" stage").height() (" player").height()) timer setInterval(update, 1000 60) (document).keypress(function(e) console.log(e.which) if (e.which 32) console.log("it works") jump() ) ) function showScreen(screen) ('.screen').hide() (screen).show() function jump() if ( (" player").position().top gt maxheight) console.log("Jump is working") velocity 15 function update() if (velocity 0 amp amp (" player").position().top maxheight) else if (velocity gt 0 amp amp (" player").position().top gt maxheight) console.log(maxheight " through ground" (" player").position().top) (" player").css("top", maxheight "px") velocity 0 else velocity gravity var newPos (" player").position().top velocity "px" (" player").css("top", newPos) However I'm very new to game development, I've been stumped for a while now, I can't figure out a way to control my character movement. Can anyone tell me what's wrong with my code? My character should be jumping on the platform whenever the space key is pressed (that's it). |
2 | SailsJS Rotational direction coordinates calculation issue I'm creating a small game to learn how NodeJS amp Sails work (and by extension Waterline, Socket.io, Express, and all their components). I'm using websockets to make the server calculate the coordinates. Everything is handled server side. The client only receives serialized data in order to redraw the whole canvas. For debugging purposes, I decided not to redraw but simply "draw" (leaving the old canvas visible) to show you the result. See below for situation, issue and code. The issue I'm having trouble when calculating coordinates. What I need is a simple forward backwards system, and when pressing left or right keys, change the direction angle so the character can move in the canvas. Kinda like the good'ol Asteroids retro games. The issue is the following The drawn loops you see shouldn't exist. In fact, they should be circles. I drew this by simply pressing either up or down key, combined with one of left or right keys. I think there is an issue in the calculation system... This shouldn't be a performance issue because each tick occurs at the same interval, so even if it was a performance issue, it should only be related to delay when redrawing the canvas, not such an offset in coordinates calculation... Any idea ? Info about code api moves contains a javascript object like this left false, right false, up false, down false It is used to check whether the user is "pressing" associated arrow keys. It is updated each time there is a keyUp or keyDown event client side. user.pick contains the "physical object" to be rendered in the canvas, which contain x, y coordinates, and information about movement speed and rotation speed. Here's the code that handles the coordinates calculation. Change angle if "left" or "right" is pushed if (moves.left moves.right) let PI2 2 PI let angle user.pick.angle if (moves.left) angle user.pick.angleSpeed else if (moves.right) angle user.pick.angleSpeed Use this to avoid having huge integers to manage if (angle lt 0) angle 360 angle if (angle gt 360) angle angle 360 user.pick.angle parseInt(angle) Up and down allow us to move either forwards or backwards. if (moves.up moves.down) let moveRatio moves.up ? 1 1 let angleRadians user.pick.angle (PI 180) let x user.pick.x moveRatio user.pick.speed Math.sin(angleRadians) let y user.pick.y moveRatio user.pick.speed Math.cos(angleRadians) Avoids collisions with canvas walls if (x gt 0 amp amp x lt user.map.width) user.pick.x parseInt(x) if (y gt 0 amp amp y lt user.map.height) user.pick.y parseInt(y) |
2 | Javascript How and where to put game initialization data I'm new to JS game programming. In the past, when coding games (in Java), I tend to make separate files for configuration and game data (maps, character stats, etc). This is for separation of code and data. How can I effectively implement this on JS? EDIT This is for browsers only. |
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 | JavaScript character direction delay I am developing a top down game and I'm having trouble with a delay in switching from one character walk direction to another, particularly if the previous direction key is still being pressed by the user. Take the following user interaction User presses up arrow User presses right arrow (up arrow is still pressed) User releases up arrow (right arrow is still pressed). The problem I am experiencing is that there is a delay in the character switching from the "walk up" movement to the "walk right" movement. requestId 0, settimeoutID 0, counter 0, move function(keyCode) var this this Frame per seconds var fps 60 if (this.requestId 0) (function animationLoop() Control the timing of an animation with requestAnimationFrame this.settimeoutID setTimeout(function() this.render() this.requestId requestAnimationFrame(animationLoop, this.move) , 1000 fps) )() , changeAnim function() if (this.counter 10 0) if (this.currentFrame gt 1) this.currentFrame 0 else this.currentFrame , render function() Add some drawing this.counter if (keyCode config.PLAYER DOWN) this.action 'Front' this.newPos.y 1 else if (keyCode config.PLAYER UP) this.action 'Back' this.newPos.y 1 if (keyCode config.PLAYER RIGHT) this.action 'Right' this.newPos.x 1 else if (keyCode config.PLAYER LEFT) this.action 'Left' this.newPos.x 1 this.changeAnim() Draw player logic this.drawPlayer.reDraw(this.playerSprite 1 .Walk this.action this.currentFrame , this.newPos) , onKeyUp function() Cancel the animation request if (this.requestId) clearTimeout(this.settimeoutID) cancelAnimationFrame(this.requestId) Allow a new request to be called this.requestId 0 this.counter 0 this.currentFrame 0 this.drawPlayer.reDraw(this.playerSprite 1 .Walk this.action this.currentFrame , this.newPos) Note The function move gets called every time a new key is being pressed. |
2 | Implementing an efficient method of server side checking I'm making a web based action RPG game. I don't want players to cheat, but I also don't want the game to constantly pause to wait for the server to respond. I made it so the game is played on the client side (for responsiveness) and the server does routine checking to validate the game state. But the system is very cumbersome. The server has to calculate every single frame and compare the entire game state to the game state sent from the client. If anything in the game states are different form each other, the server kicks the player off. However, this means the game has to send 30 requests a second, and the server must calculate it all in time. If many people are playing the game, I don't think my one free Heroku dyno can handle that. How do I implement an efficient and elegant way of validating players' moves on the server side? |
2 | Collision between free player and tilebased map so I'm working on some sort of platformer in javascript where the map is tilebased but the player can move freely. Now, i have a problem with collision detection response. It's kind of obvious what I'm trying to do, I don't want the player to walk into walls and fall into the ground so i need collision stuff. Basic info The player is the same size as the tiles The tiles are 8x8 The map is stored in an array like this 0, 0, 0, 1, 1, 1, 0, 0, 0 . So if the map was 3x3 there would be a horizontal line in the center. I feel that the system that I'm using is very inefficient and there are some problems with it sides The tiles are 8x8 wide so i divide the players position by 8 to get the current tile the players is occupying. The player.y mapWidth player.x thing gets the tile at that position in the map array I use Math.floor instead of round to get the tile to the left of the player if (map (Math.round(player.y 8) mapWidth) Math.floor(player.x 8) 1) sides.left true else sides.left false if (sides.left) Set the players x position to exactly outside the wall. player.x Math.floor((player.x 8) 1) 8 Now this works fine for walls but when you use it on the ground it works but it glitches on corners. For example if the player half way over an edge it falls through the tile and is pushed to the side. Is there a better way to do this and if not, how do i fix the ground collision? |
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 | 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 | 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 | 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 | Shifting the camera and setting a new scene when using Box2D My jsFiddle START MOVE CAMERA var p new b2Vec2() p (ball.body.GetWorldCenter().x) physics.scale pos.push(p) var length pos.length var s (pos length 1 pos length 2 ) in pixels if ((halfwidth lt (dw p)) amp amp (p gt halfwidth)) ctx.translate( s, 0) I followed this tutorial, but the ball rendering is acting weird and slow. I can't figure out how this example did it. He used 3 variables (stage,x, y) that are undefined in the code he wrote. Also check out how the camera moves with the player in this ImpactJS demo. I'd like to have that. How can I do this? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.