_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
2 | One big Instance or One instance for every moving entity? I am creating a multiplayer JavaScript game with a PHP central server. Each user will be able to move around in a 3D world, with other users and NPCs. These NPCs will be controlled by the central server in PHP. Should I create one big world simulation PHP file that simulates all the NPCs in turn or a smaller controller that will be ran for each active NPC (on its own thread)? Each NPC has its own row on an SQL table and will be retrieved by the client to determine its position, state, etc. Note This is my first time creating a networked game, so if there is anything that I can do better, or a unique way of doing things that could work for this, feel free to comment |
2 | Clearing just the object, not the whole canvas, leaving an uwanted trail I'm working on a platform game via poo. I heard is more efficient to clear just the object you're drawing instead of clearing the whole canvas. So I'm working on this, and all goes well when the player's velocity player.Xvel has an integer value. But when I use a floating point value for the velocity, then my object leaves a banded trail behind it, like a barcode of stripes and gaps. Can you help me identify what's causing this artifact? var canvas canvas.obj document.getElementById('canvas') canvas.ctx canvas.obj.getContext('2d') canvas.width canvas.obj.width canvas.height canvas.obj.height var Object function() this.draw function() switch (this.fill) case true canvas.ctx.fillStyle this.color canvas.ctx.fillRect(this.x, this.y, this.width, this.height) break case false canvas.ctx.strokeStyle this.color canvas.ctx.strokeRect(this.x, this.y, this.width, this.height) break default console.log('draw err') this.clear function() var prevCoords prevCoords.x this.x this.xVel prevCoords.y this.y this.yVel lineWidth fix canvas.ctx.clearRect(prevCoords.x, prevCoords.y, this.width, this.height) var player new Object() var game player.width 10 player.height 50 player.x 200 player.y 150 player.xVel 0.9 try to change this to integer float value then run player.yVel 0 player.color 'white' player.fill true player.movement function() this.x this.xVel this.y this.yVel game.key game.fps 15 game.obj setInterval(function() player.clear() player.draw() player.movement() , 1000 game.fps) body background rgb(110, 110, 110) color rgb(230, 230, 230) canvas background rgb(60, 60, 60) lt canvas id "canvas" width "460" height "360" gt lt canvas gt lt form action "" gt lt label gt Game lt label gt lt input type "button" value "run" onclick "" gt lt input type "button" value "stop" onclick "clearInterval(game.obj) console.log('end') " gt lt form gt |
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 | Prevent cheating in html Javascript game I have made a Javascript html game. Now the problem I have is anyone can edit the client code and cheat in game for example there is a man shooting a enemy. Man HP nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp 100 Enemy HP nbsp nbsp nbsp nbsp nbsp 50 lt div id "man" hp "100" gt lt div gt Now if someone changes the hp attribute to a very high value then he becomes literally immortal making the game easy. Now how can I prevent this type of thing ? |
2 | How to prevent (most) cheating (server side) in my JavaScript, Node JS, socket.io MORPG? I'm working on a fairly simple JavaScript Node JS socket.io (M)MORPG where multiple people play in the same world. This is actually working, but cheating is insanely easy at the moment. My goal is not to stop people from cheating client side, I know this is impossible. My goal is to have the server know when someone is cheating and do something about it. What I really want to know is how well a Node JS server would be able to handle the constant anti cheat checking. People can just adjust the client side JS code and the server currently doesn't do too much checking. So a player could just change his X amp Y coordinate and teleport around the map at will. It would be fairly simple to implement basic checks that don't allow crazy cheats. But I'd like a real way to prevent this. One possibility is to keep track of all player data on the server and make sure nothing weird is happening client side by constantly comparing the data the server has. My issue with this is that I have a lot of collision checking and my world will become rather big. I'm not sure how good of an idea it is to do all of this collision checking server side as well. Sure it would work for one or two players, but what about 10? 50? 200? Especially with all of these players bouncing off walls, shooting bullets, hitting monsters, getting hit by monsters, colliding with monsters, ... As far as I know, the only way to actually prevent cheating is by making the server check all movement and wall bullet monster collisions. Are there any other options? Like using an anti cheat engine of some sort? I know games like MapleStory have that, but I have no idea how they work or how affordable that would be? Or will doing all the collision checks server side be fine? At some point, like around 50 100 players, I could set up a second server instance to limit the amount of players on each server. Ofcourse I would also only check collisions near the player, so not map wide for each player. Any help advice on this is appreciated. Here's a link to my game that will make my questions less abstract. It's far from finished and the world is still very small, but it should give a good idea of what I'm asking http 185.115.218.199 3000 |
2 | How to 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 | Converting cartesian geo coordinates to isometric (real world map to game map) I need to create an automated method to convert real cartesian, geo coordinate data (such as roads and parks), into isometric coordinates as a game map view for use in HTML5 Canvas. Here is an image of what I mean Example Image Taking into account heavy map distortion in the process to fit they isometric layout. Is this even remotely possible? |
2 | How legal would it be to use some elements of the Half Life universe in my non comercial, indie game? I'm planning to make a simple, HTML5 game, that would use some elements of the Half Life universe. Basically, it would be a 2D Portal clone, but it would have it's own story, and portals would be different, along with the mechanics of making and using them. Also, how far can I go with this? If possible, I'd like to have Gman, a character from Half Life, walk by a few times, and maybe even use some of the sounds from Half Life or Portal. It's also important to note that I wouldn't be making any kind of profit. |
2 | Delta compressed world state when networking in JavaScript Lets say we send a snapshot from the server to the clients about world details, containing object positions, velocities etc, every second. We should send only delta data based on the previous snapshot that was sent. For example, if the player moved from (x 50, y 0) to (x 100, y 0), then the snapshot will only contain (move x 50 move y 0), and the clients will add the previous position and move x. We should sending delta values, as it is less data to send. How do I achieve this in Javascript? My objects already have data stored in Float32 (by TypedArray) and there is no Float16 data type in JavaScript. For example delta currentPos prevPos 20 100 80 okey, now I have 20 instead of 80, but this isn't less data to send.. still both will be send as Float32. data.writeFloat32(delta) for simplesness there is no Float16 and I am afraid that even if JS will has Float16 TypedArrays, then it still would be not enough, because for example 20.3454356 from Float32 to Float16 will lose precision to lets say sth like 20.34, or I'm wrong? How to send delta data in JS and gain the benefits of this technique in JS? |
2 | Click counting and actions based off count So I have a button that is the 'mine' for my incremental game. I would like to track the number of times that it is clicked and be able to do two things Have events happen say every 5 clicks. display the total number of times that is has been clicked. This is what I have so far function addstone() stone (parseFloat(stone) 0.1).toFixed(1) stone stone 1 var count 0 var totalcount 0 ("input type 'button' ").click(function() count count 1 if(count 5) stone stone 1 if(count 5) count 0 totalcount totalcount 1 document.getElementById("stone").innerHTML stone So what do I need to do from here. My button calls function "mine1Click" which in turn calls the different resource addition functions. so for "mine1Click" I have this function mine1Click() addstone() addwood() function addstone() stone (parseFloat(stone) 0.1).toFixed(1) TOO LARGE stone stone 1 TOO MUCH STONE var count 0 var totalcount 0 ("input type 'button' ").click(function() count count 1 if(count 5) stone stone 1 if(count 5) count 0 totalcount totalcount 1 document.getElementById("stone").innerHTML stone function addwood() wood wood 1 document.getElementById("wood").innerHTML wood function addcopper() UNIMPLEMENTED How should I go about this? |
2 | how do i make the JS jquery tic tac toe squares only clickable once? As i have it now my script makes the 3x3 grid clickable, and I dont know exactly how to turn on the click once it has been clicked. This is using jQuery and a simple if else statement to switch between turns. (document).ready(function() var turn 0 (" cell11, cell12, cell21, cell22, cell13, cell23, cell31, cell32, cell33, ") .click( function() var cell (this) if(turn 0) turn 1 cell.css("background","url(images o.png)") else turn 0 cell.css("background","url(images x.png)") ) ) |
2 | 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 | My sprite is not listening to any keyboard keys First time ever creating html canvas game. Once I finally got my sprite ant tiles drawn on the canvas, now I want to make my sprite interactive. Unfortunately, for some reason it is not working. I get a message in console when the certain key is pressed but the sprite is not changing its position. I wonder why? The code var canvas document.getElementById("canvas") var context canvas.getContext("2d") var mapArray 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 var StyleSheet function(image, width, height) this.image image this.width width this.height height this.draw function(image, sx, sy, swidth, sheight, x, y, width, height) context.drawImage(image, sx, sy, swidth, sheight,x, y, width, height) this.drawimage function(image, x, y, width, height) context.drawImage(image, x, y, width, height) Initial Sprite Position var boatPosX 230 var boatPosY 200 var Loader function(src) this.image new Image() this.image.src src this.image.onload function() var sprite new StyleSheet(background, 36, 36) var ship new StyleSheet(boat, 90, 100) for (let i 0 i lt mapArray.length i ) for (let j 0 j lt mapArray i .length j ) if (mapArray i j 0) sprite.draw(background, 190, 230, 26, 26, i sprite.width, j sprite.height, sprite.width, sprite.height) if (mapArray i j 1) sprite.draw(background, 30, 30, 26, 26, i sprite.width, j sprite.height, sprite.width, sprite.height) if (mapArray i j 2) sprite.draw(background, 200, 20, 26, 26, i sprite.width, j sprite.height, sprite.width, sprite.height) ship.drawimage(boat, boatPosX, boatPosY, 50, 50) return this.image Sprite controls function move(e) if (e.keyCode 39) boatPosX 2 console.log("works") if (e.keyCode 37) boatPosX 2 document.onkeydown move var background new Loader("ground.png") var boat new Loader("ship.png") console.log(background) |
2 | Character movement resetting x y position in HTML5 game I have an HTML5 game I'm working on and I'm at the point where I'm trying to make the character move. For the most part, the character(A rectangular square) is moving, but it's not moving from its starting position. Instead, when I hit the move key the character's x position and y position are reset to 0, 0. My question is, why is the character's position being set to 0, 0 before it starts moving? I've included a link to the dropbox with the project so it's easier to see what's going on, but here's the movement script for reference. initMap.js Script, lines 81 92 case "Player" gameObjectsLayerCtx.fillStyle "rgb(0, 0, 0)" gameObjectsLayerCtx.fillRect(xPos, yPos, destWidth 3, destHeight 3) window.onkeydown function(ev) var key ev.key if(key "w") yPos 5 gameObjectsLayerCtx.clearRect(0, 0, gameObjectsLayer.width, gameObjectsLayer.height) gameObjectsLayerCtx.fillRect(xPos, yPos, destWidth 3, destHeight 3) break Project The script is the initMap.js script and the movement functionality is from lines 81 92 The character's starting position Where the character moves to when pressing the move key |
2 | Player movement behind objects I was playing around on RPG JS and Browser Quest, and the player, when moving, can give the effect of walking behind the trees or houses etc, so the player effectively disappears while it is "behind" the object. How is this effect created? I am building and RPG using javascript and canvas at the moment, and would love to try and implement this into the game. I am working on A movement for my character. |
2 | How to do a genetic algorithm's chromosome which controls movements First I would like to inform you that I'm french and 15 so my english is not very good. I've read some articles about genetic algorithms (GA) and since I discovered the HTML5's canvas element, I can create an AI with animations, so I've created two little experiments to enjoy seeing robots moving on their own but first I'll present you the second one because it's easier The aim of this experiment for the white circles is to touch the red square and instead of using coordinate calculations, like I said, I would like to create an autonomous algorithm which evolves in the time. I give to the circles their relative coordinates to the red square like so they know exactly where they are and their speed that they will be able to change. So to do it I need a solution to create a chromosome that contains moving informations but since the x and y positions are randomly assigned to circles and the square, if a member of the population has the good solution, it's only for this particular configuration. I'm searching how to make them know that if the x coordinate is inferior to 0, they have to go left without creating a function like this if(firstGeneInfo 2) bot i .x redSquare.x bot i .x . This is a screenshot of the canvas And the jsfiddle link but movements are random for the moment. http jsfiddle.net KLn8r 1 The other experiment is a sort of "survival game" where the red square has to last, first I created it as a human AI experience but I prefer to do an AI vs AI game, and so implement a genetic algorithm but in this case it is a lot more complicated because they are multiple enemies, I thought that with informations like enemies's coordinates and speed once again, the red square would developp kind of a strategy. The enemies are controlled by an algorithm and there is no need to do a GA for them. A screenshot and the jsfiddle link http jsfiddle.net f6ghk If you've read all this, I already thank you ! I'm not asking for the full working code but just the principle of a chromosome that works in theses cases. I hope that my english wasn't to horrible to read and that for my problems I don't need a simulated neural network because it seems a bit complicated to me. Thank you for your answers ! |
2 | How to include a new file js in a project cocos2d js? I'm trying to include a new js file containing a new scene on a cocos2d js project, but every time try occurs the following error Uncaught ReferenceError GameScene is not defined. I included my file in jsList and in appList "jsList" "src game scene.js" , "appFiles" "src game scene.js" The code of my scene looks normal var GameScene cc.Scene.extend( onEnter function() this. super() var gameLayer new GameLayer() this.addChild(gameLayer) ) The code on app.js to call my scene looks good too var gameScene new GameScene() cc.Director.runScene(gameScene) What should I do? |
2 | Map scrolling around the world I am developing an TBS (turn based strategy) game. I have created a simple canvas renderer to render hexagonial map. I already implemented scrolling on the map. My current problem is that I want to make it like in the civilizations games that you can scroll around the world. But I am kind of stuck on how to implement that. I had the idea of checking if a tile was rendered and if there is still space to the left render next sibling and so on, but this would turn out into long loops. My map array (2d) holds all the tiles and every tile has a member which holds all the siblings. How would you solve this? This is a screenshot from the example. You can check it out on http civ.minerjs.com. The code is also available to browse on the site using developer tools. Thanks for reading! |
2 | Movement on Multiplayer Games I'm developing a JavaScript Multiplayer Game (Using NodeJS and Socket.IO). The problem I'm having is, on a Player's movement, the Event with the X and Y positions is sent to the server and then to all the other Players on that Server. Now, on a 60 FPS Machine, the event is sent to the server 60 times a second, resulting on smooth movement on all other Machines with 60 FPS. However, on a 30 FPS Machine, it's only sent 30 times a second, resulting on jumpy movement on higher FPS Machines (E.g. 60 FPS). Is there any way to resolve this problem? Thanks! |
2 | Testing HTML5 canvas games on low resource computers I've made a game in HTML5 amp JS and want to test it on varying types of user setups as I've heard it doesn't perform too well on older MacBooks. How can I accomplish this? I'm thinking of something like browserstack.com but for GPU, CPU and memory testing. |
2 | How do I keep a PHP server running forever? I'm making a web game RTS, it's mostly create units, manage resources, attack with army, and level up factories. I have created the basics of the game using Javascript, PHP, and MySQL databases. I use the database to store player credentials and stats, and PHP as a server side logic (like retrieve the right player and attack with X units). On the client side I use HTML CSS and javascript. My problem is that I need to keep adding resources based on the factories level (ex. 10 gold every min, when mine factory lvl.1). The only answers that I have found, is to modify the PHP file to run an infinite loop and keep connecting to the database to add those resources 24 7. I think the server also needs to handle attack travel (when units arrive at the enemy castle and the fight is over) and some other logic, but I don't have physical access to the server, and keep connecting to the database to add resources doesn't seem a good idea. I'm willing to make a server using other languages, or use other way to store data that keeps changing, so I can avoid multiple connections to the database. If you know a better way to do it, or something that can put me on tracks I will appreciate it. |
2 | How to use apply class inheritance in Enchant.js You're developing a game using Enchant.js and you just need an Enemy class which multiple enemy classes derive from and every enemy has its own sprite and stuff. |
2 | Checking if bullet collides with enemy when I know the start X Y, the angle, the speed and dist traveled of the bullets This is the bullet I create when a player clicks to attack var angInRadians Math.atan2(data.y playerArr i .y, data.x playerArr i .x) data.y amp data.x is mouseY and mouseX var temp angInRadians (180 Math.PI) function newBullet() this.attack temp this.playerX playerArr i .x this.playerY playerArr i .y this.speed 10 this.traveled 0 Then in my game loop I do this for(var j 0 j lt playerArr i .bullets.length j ) playerArr i .bullets j .traveled playerArr i .bullets j .speed Then to draw the bullet I am doing this ctx.translate(playerArr i .bullets j .playerX, playerArr i .bullets j .playerY) ctx.rotate(playerArr i .bullets j .attack (Math.PI 180)) ctx.fillStyle 'black' ctx.fillRect(playerArr i .bullets j .traveled, 0, 4, 1) Then for the players I just have a usual player X and Y and I can't figure out how to check if the bullet is within the area of the player, if you need any more code just ask If you want to see how the game is working here. |
2 | Time passed check with Pause functionality I am working on a game that has a lot of time passed checks of the following format. These work great, but there is a problem when the game is paused If paused for any meaningful amount of time, the if statement will become true. const t new Date().getTime() Get the current time (in ms) const fireCooldown 500 The time to wait before firing again (in ms) if(t gt lastFireTime fireCooldown) lastFireTime t fire() How can I integrate pause functionality into this in a way where pausing does not make the if statement true? |
2 | Why doesn't my computer paddle move in my Pong game? I'm making a pong game and I can't figure out why the computerPaddle won't move up or down when it's supposed to to hit the ball automatically! Please help me. Here's code lt html gt lt h3 gt PONG lt h3 gt lt canvas id "gameCanvas" width "800" height "600" gt lt canvas gt lt script gt var canvas var canvasContext var ballX 50 var ballY 50 var ballSpeedX 11 var ballSpeedY 5 var playerPaddleY 240 var computerPaddleY 240 const paddleHeight 120 const paddleThickness 12 function calculateMousePos(evt) var rect canvas.getBoundingClientRect() var root document.documentElement var mouseX evt.clientX rect.left root.scrollLeft var mouseY evt.clientY rect.top root.scrollTop return x mouseX, y mouseY window.onload function() canvas document.getElementById('gameCanvas') canvasContext canvas.getContext('2d') var framesPerSecond 30 setInterval(function() moveEverything() drawEverything() , 1000 framesPerSecond) canvas.addEventListener('mousemove', function(evt) var mousePos calculateMousePos(evt) playerPaddleY mousePos.y (paddleHeight 2) ) function ballReset() ballX canvas.width 2 ballY canvas.height 2 ballSpeedX ballSpeedX function computerMovement() if (computerPaddleY lt ballY) computerPaddleY 5 else computerPaddleY 5 function moveEverything() ballX ballSpeedX ballY ballSpeedY if (ballX gt canvas.width) if (ballY gt computerPaddleY amp amp ballY lt computerPaddleY paddleHeight) ballSpeedX ballSpeedX else ballReset() if (ballX lt 0) if (ballY gt playerPaddleY amp amp ballY lt playerPaddleY paddleHeight) ballSpeedX ballSpeedX else ballReset() if (ballY gt canvas.height) ballSpeedY ballSpeedY if (ballY lt 0) ballSpeedY ballSpeedY function drawEverything() canvasContext.fillStyle 'black' canvasContext.fillRect(0, 0, canvas.width, canvas.height) canvasContext.fillStyle 'white' canvasContext.fillRect(2, playerPaddleY, paddleThickness, paddleHeight) player canvasContext.fillRect(786, computerPaddleY, paddleThickness, 120) computer player canvasContext.beginPath() canvasContext.arc(ballX, ballY, 12, 0, Math.PI 2, true) ball canvasContext.fill() lt script gt lt html gt |
2 | Tweening multiple image objects in html5 js Is there an optimal way to choose when tweening multiple images as a single image? For example let's say i have 10 preloaded image objects in my script, and i want to place them one on top of the other (the arrangement is supposed to be dynamic), and then tween it as a single "collage". Do javascript tweening libraries like Tweenjs GSAP etc, care about how many objects you tween concurrently (as long as in the end they move in the same direction and with same speed), or is it transparent for the fact that the hardware will move an array of pixels in the end? Do you think that it would be better performance wize to pre combine the multiple images into one larger image, and then feed it to the tweening algorithm? I would like to do it this way, as it would be more transparent to me, seperating the image "collage" process from the tweening process, but i haven't found a way to dynamically create javascript image objects by combining multiple single images. Thank you. |
2 | Node.js V8 as a Platform for High End Local PC Game Development? As a Web UI dev rapidly expanding into more wide open generalist territory, the more I learn about how its done in other languages, the more I love JS for architectural and basic messaging event driven concerns. For the record I am most certainly not a full blown game dev (although I did once write for a major gaming mag which is like saying I pretended to be friends with game devs on TV, although you guys were always my favorite folks to talk to). Anyway, since it's fairly easy to bind C and C to JavaScript via Node (or perhaps more specifically V8), how reasonable would it be to assume you could write a decent 3D engine that exposed outcomes of things like collision calculations as events to the JS with the intention of getting the dynamic first class function party language benefits (assuming you see such things as benefits I do) to higher level architecture and AI logic concerns without a crippling loss in performance? Node, as I understand it, basically exposes a C event loop to JavaScript handled by V8. The JS is single threaded, meaning any attempt to do anything calculation IO intensive with the JS would be foolish, but you get the advantage of not really having to sweat threads, queuing etc... since you're ideally never trying to muck with the same data at the same time. Most code would of course be heavily event callback driven. All the file I O concerns and other processor intensive stuff is basically C or C under the hood telling you when its done. Not to mention handling UI concerns directly out of the JavaScript via a webkit layer slapped on top of everything. I'd be delighted to hear why you love hate the idea but the core question is is it feasible and why not? And no, I seriously doubt my own ability to do this all by myself, although plugging an existing 3D engine in might not be outside of the realm of possibility but I'd still be learning a lot of new stuff to make that happen I'm sure. |
2 | How to open box item animation? I want make 2d open box animation. Like cs go open keys or other random box. I need the basics of implementation it and i want get more information about it. Thanks. Upd Steps. I have array of elements. I press to button and shuffle array. I get random element from array by weight. All elements in array have images. So , after i press button all images start move with some accelerate to left or right. 6 images move to left. And what is next ? I need get random items images while acceleration is not end ? Or what ? I need logic example. My example realization(I don't know working it or not) I need add to array new items while acceleration is enable or what ? Or after i get random item by weight, i need sort array and past it item to last position and add other random items to this array. And after all i need loop to this array to last item. And when loop in last position i show it item in screen ? I really don't understand how it working.. D |
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 | 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 | Cellbased maps explanation? I've been trying to understand cellbased maps and how they work, i have googled alot but can't seem to find any explanation for it. With cell based maps i mean the ones where you do height and everything like walls roof floor in each cell. If possible i would appreciate an explanation from a Javascript perspective, but only a theoretical explanation can do. So why do we use them? how do they work? Is it just like a normal array with more information? |
2 | PHP and Javascript HTML5 Collaboration I've recently been working on a fairly complicated game. I've stored information with local storage, but that allows the player to edit it, and does not transfer from computer to computer. The two scripts run on a single server, and I use the following to ping the php server function initiateLoginSequence() var isnewplayer prompt("Hello! Are you new?(Y N)") if(isnewplayer.equalsIgnoreCase("N")) var username prompt("Enter username.") var password prompt("Enter Password.") parsing code goes here later. else var username prompt("Enter a username. This will be used for future logins.") var password prompt("Enter a password. This will be used for future logins."," ") var req new XMLHttpRequest() req.open('POST', 'http 69.144.34.106 Scores.php', true) req.send("returning false" " amp name " username " amp pw " password " amp level " lvl " amp save true") req.send() I then process the results with this lt ?php returning POST "returning" save POST "save" password POST "pw" username POST "name" score POST "lvl" connection mysql connect("localhost 3306"," "," ") if( returning "false" amp amp save "true") mysql select db("userdata", connection) sqlcmd "CREATE TABLE ". username."( Username varchar(". username.") Password varchar(". password.") Score varchar(". score.") )" mysql query( sqlcmd) else if( save false) sqlcmd "SELECT FROM userdata" result mysql query( sqlcmd) while( row mysql fetch array( result)) if( row 'Username' username amp amp row 'Password' ) echo row 'Score' else if( save true) sqlcmd "SELECT FROM userdata" result mysql query( sqlcmd) while( row mysql fetch array( result)) row 'Username' username row 'Password' Password row 'Score' Score ? gt But after creating the mysql database, nothing is populated. So my basic question is, Am I doing this right? If not, what am I missing? |
2 | How can I keep track of a battle log on a web game? Recently I started working on a Web turn based PvP RPG game. Now I'm working on the battle system but I encountered some issues How can I keep track of everything that happens in the battle? It should keep track of the characters on the field, inventory, the damage done etc. I first thought I would simply put it in the (MySQL) database, but I think it will be too much. Especially if several people are in a battle. I thought of puting this in sessions or cookies but I don't think thats reliable. Does anyone have an idea how I can do this? |
2 | html javascript shop Im new to drop down menus. How can I make a working shop in html javascript. I have this so far http prntscr.com o15oj7 . I want help with the selling of a material part. i know i should use if statements but im not sure how to format the function . I want if bronze is selected for how much you can sell it for to be displayed. then if u press sell button you gain that much gold then lose 1 bronze. var goldcoins 0 var goldcoins 0 var Bronzeprice 10 var Silverprice 20 var GoldPrice 50 var DiamondPrice 100 var ShrimpPrice 10 var BassPrice 20 var SalmonPrice 50 var SharkPrice 100 function sellItem() var mylist document.getElementById("myList") document.getElementById("favorite").value mylist.options mylist.selectedIndex .text Html code lt style gt lt font size " 2" gt lt b gt Shop lt b gt lt br gt lt font size " 0" gt Auto Miner lt button onclick "buyMiner()" id "MinerCostBtn" gt Buy lt button gt lt br gt lt font size " 0" gt Auto Fisher lt button onclick "buyFisher()" id "FisherCostBtn" gt Buy lt button gt lt br gt lt br gt lt form gt Sell lt select id"SellBox" gt lt option gt Bronze lt option gt lt option gt Silver lt option gt lt option gt Gold lt option gt lt option gt Diamond lt option gt lt option gt Shrimp lt option gt lt option gt Bass lt option gt lt option gt Salmon lt option gt lt option gt Shark lt option gt lt select gt For amp nbsp lt span id "currentPrice" gt 0 lt span gt amp nbsp lt button onclick "SellItem()" id "SellBtn" gt Sell lt button gt lt form gt lt br gt Gold Coins lt span id "goldcoins" gt 0 lt span gt lt br gt Buy skillpoint 100,000 gold lt button onclick "buySkillPoint()" id "SkillPointBtn" gt Buy lt button gt lt br gt Buy diamond 10,000 gold lt button onclick "buyDiamond()" id "diamonddBtn" gt Buy lt button gt lt br gt Buy shark 10,000 gold lt button onclick "buyShark()" id "sharkkBtn" gt Buy lt button gt lt br gt lt br gt lt br gt I expect when bronze is selected (etc) for how much you will gain from it to be displayed then when button is pressed for you to lose 1 bronze and gain that amount of gold. While the drop down menu is on that item. I have the variables on a diffrent javascript . i do that all those drop down button items . I just need to know how to format the funtion so if they are selected in the drop down menu that item will sell. |
2 | How should I manage Roguelike levels maps in JavaScript? I am developing a Roguelike in JavaScript using ROT.js. I'd like to keep with traditional gameplay (permadeath, randomly generated dungeons mobs items), but I want to have a statically defined overworld with randomly generated dungeons beneath. Currently, I use the TILED map editor to create my overworld map and export it to JSON JS format and import parse the map into my game. For randomly generated dungeons, I use ROT.js's built in dungeon generator tool to create dungeons that are in the same JSON JS format that the TILED maps are in. The issue I am facing is finding an efficient way to store these maps and levels once they are generated, alongside the overworld. Right now, I just throw the generated maps into a JavaScript object indexed by the name of the map. Here's an example of how I do this currently levels map class parses TILED map json and creates actors based on ascii let map new Map(TiledMaps "overworld" ) levels "overworld" map let dungeon new Map(randomMap(...)) random map generates tiled map levels "dungeon1" dungeon to switch levels, just set the current game map Game.map levels "dungeon1" Is this a good approach? I would like to consider the possibility of having different types of dungeons. So, in the overworld, you might visit different sections of the world and those have different dungeons. Something like Link to the Past perhaps? Any advice? |
2 | how to replace vertex buffer in webGL I want to replace a vertex buffer with another completely different vertex buffer, different size and values, it will not get replaced every frame. gl.deleteBuffer(vertexBuffer) vertexBuffer gl.createBuffer() gl.bindBuffer(gl.ARRAY BUFFER, vertexBuffer) gl.bufferData(gl.ARRAY BUFFER, vArray, gl.STATIC DRAW) I am using that code to replace it, I don't think it is the correct way because I am getting GL ERROR GL INVALID OPERATION glDrawArrays attempt to render with no buffer attached to enabled attribute 1 I don't know if this is related to the error but I am rendering using the vertex buffer when I replace it. |
2 | canvas ball physics animation I want to animate ball in html canvas like this. ctx.beginPath() ctx.arc(75, 75, 10, 0, Math.PI 2, true) ctx.closePath() ctx.fill() start position is left top corner and ball's maximum height position is always the same also I don't want to use javascript physics libraries thanks |
2 | How can I mimic an isometric perspective using square tiles? Can an isometric perspective be mimicked with traditional square tiles? Can't the effects of the 45 degree overhead view simply be "drawn in" to the square? How would this work? Picture this the tiles themselves are square (not diamond) but all objects placed on them (sprites, terrain objects like trees, buildings, etc) are drawn from isometric view as if they were on diamonds. This might be a silly question to ask, but I'm having difficulty understanding isometric perspective. |
2 | Separating .js elements .js element communication So I have 2 questions regarding the code below function goldClick(number) gold gold number document.getElementById("gold").innerHTML gold function buyMiner() var minerCostG Math.floor(100 Math.pow(2.1,miner)) var minerCostW Math.floor(10 Math.pow(3.1,miner)) if(gold gt minerCostG) if(wood gt minerCostW) miner miner 1 gold gold minerCostG wood wood minerCostW document.getElementById('miner').innerHTML miner document.getElementById('gold').innerHTML gold document.getElementById('wood').innerHTML wood var nextCostMG Math.floor(100 Math.pow(2.1,miner)) document.getElementById('minerCostG').innerHTML nextCostMG var nextCostMW Math.floor(10 Math.pow(3.1,miner)) document.getElementById('minerCostW').innerHTML nextCostMW window.setInterval(function() goldClick(miner) , 1000) Question 1 Is it possible to separate these functions (goldclick, buyminer, window interval,) into their own documents so that if I have say, 50 different XXXXclick functions, and 50 buyXXXX functions and 50 interval functions, I have just 3 .js documents instead of 50. Question 2 If it is possible to separate them, how would I ensure that they are communicating with each other and variable values are not being confused or sent to the wrong lt span gt in the displaying html. |
2 | Tagging "regions" in rot.js map generator I'm working on a small roguelike and I'd like to be able to tag the various quot regions quot generated via the Map generators so that I can use it as a lookup to environment descriptions. I see that there are quot Rooms quot that are generated in the dungeon generator algorithms, however I didn't really see anything similar in say, the cellular automata generator. Is there a way to leverage the generator in rot.js, or am I stuck with manually determining if I'm in a particular open area (and breaking encapsulation of internal, private variables along the way)? Basically, I'd like to be able to link up my player's location to the text you see at the bottom of , but can't seem to figure out how to do it generically. I'm fairly certain I could use the 'Rooms' object in the first 2 screenshots, and everything else is a hallway, but I'm not clear on how I could get a particular 'region' in a cellular automata generator (or one of the maze generators, for instance). |
2 | Play .mp3 with Craftyjs I want to play .mp3 sound files in a game I built with Crafty.js. Is this possible without converting the sound file? |
2 | Javascript 2D game tile textures I am using a texture atlas for my tiles. Of course I need to get the sub images to draw them on the canvas as separate tiles. Right now I can think of two ways to implement this. Divide the texture atlas into separate Image instances. Then draw them onto the canvas accordingly. Use a single image, and just draw part of it by adding extra parameters to CanvasRenderingContext2D's method drawImage. I'm not sure which is better. My thoughts were that the first option would be more manageable and flexible, since each tile is separated. What would be better? What are the ups and downs of each? |
2 | How to make sure a game can be completed I'm not sure what the correct term for what I'm looking for is described, so apologies if this is a duplicate question. But is there a term algorithm for making sure a game is "completable" with relation to an infinite scroller. What I mean by completable is that, if I had a game, where a user has to keep jumping up blocks as the screen tries to catch up with them, how would I ensure that there is always a reachable new block that the user could in theory jump to? I know in theory I would check how high the user can jump and ensure there is a block within that reach, but is there anything else to it? i.e avoiding expensive checks when placing new blocks to make sure they're not overlapping etc? I'm specifically looking at html5 js but I wondered if there was a term for this or a specific type of algo that I could investigate? Thanks |
2 | JavaScript THREE.js webgl spotlight rendering I'm playing with webgl JavaScript THREE and a spotlight. And I see unexpected results. And I don't understand what's going on, and I'm hoping you can point me in the right direction. In my particular case, the bizarre behavior is when the spotlight is behind the character, but the light is rendered as it's coming from the front. I apologize, I think it's best if you take a look here to see what I mean http dhkgames.com games redshifted . Please note that in my tests This website worked in chrome and Internet Explorer, but for some reason not in Firefox. Also, please be patient, the test website is hosted in Singapore, so it may take up to one minute onto the character is downloaded and rendered in the middle of the screen . What I'm interested in is to understand if the spotlight works as designed, or maybe I can update vertex fragment programs. As a secondary goal, in the spotlight The pants and the jacket material renders somehow differently, and once again I'm not sure why, so if you have some pointers for this as well It would be much appreciated! . Lastly, I apologize for misspellings, my arms and eyes don't work very well, and I use voice recognition software to interact with my computer . Thanks! |
2 | How to generate a random tunnel consists of series of two line paths I have a 2D path that follows series of lines thru points p1 p2 p3 p4. Like this I want to make a tunnel out of this path, so I need to split this path in two sideways and make a hole inside of it. Like this How do I do that? I actually want to just generate a random tunnel it doesn't have to follow a path. |
2 | How do I detect when an HTML 5 game has ended? I'd like to embed HTML5 games in a website, but I need to be able to detect when the game has ended so I can run some of my own JavaScript. Looking at the output of some game engines (Construct 2, for example) reveals a nightmare of code that I couldn't hope to tweak so that it fires off an event when done. How can I detect when a game has ended? |
2 | How to center a tilemap in Phaser? In Phaser, I am loading a Tilemap from JSON. I would like my Tilemap to display in a particular position (for simplicity here I say the middle of the screen). var map this.game.add.tilemap('level') map.addTilesetImage('tiles2', 'tiles2') var layer map.createLayer('Ground', map.widthInPixels, map.heightInPixels) layer.anchor.set(0.5) this does not work... layer.position.set(this.world.centerX, this.world.centerY) or even layer.x this.world.centerX layer.y this.world.centerY The anchor.set works as it should however setting the position does not seem to work. What am I doing wrong? |
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 | JavaScript rendering Canvas or DIV? I am planning on developing a multiplayer RPG (kinda like RuneScape, but don't worry, with a different gameplay) and i want to do this in the browser. Now before saying things like "A MMORPG is hard to make" or "Others tryied that too" please keep in mind that i am not dreaming at a huge game, it's just an idea that i want to see "breathing". The reason i choose JavaScript and HTML5 over other technologies is that i have some experience in web development (which of course includes a deep understanding of JS). I've looked over some libraries (or so called engines) on the web and i've found some that might have what i need. My question is What is the best way to render this kind of game in the browser, also could you suggest me the library that you think is the most suitable for this kind of job? |
2 | Choosing a data structure for a group of static (almost) thousands of objects on HTML5 canvas I have this requirement to implement a data structure for a group of thousands of displayable objects, on HTML5 canvas. Something like a particle system. The objects are randomly spread on the map. They have different colors and sizes. Each of them can be removed and I can also add more objects onto the map. These objects may move around a little bit but just one or two pixels. But on any specific (x,y) position there can be only one object. So we can say that these are static objects. To render this group of objects and make changes to them I have used a particle system and put all the objects in an array. It works but the performance isn't good especially if I perform some operations on the objects. I find that each time I need to find or remove a particular object at a specific location I have to loop through the entire array, which is not very efficient. Now my question is, can I put the objects into an object and use their position on the map as the key, and the object itself as the value? This way it works more like a hashmap or dictionary. So each time I want to get an object based on its location I can complete that operation in O(1) time. Removing any of the objects is also very easy too. When adding new object I just need to check if the location is occupied otherwise I put the new object in a new position. This way looks so good I want to implement it right away. In ES6 javascript maybe I will put them into Map or WeakMap. But before I do that I want to know if there is any drawback for this method or is it even a good option for this situation? I am also gonna implement this on the game server and transmit the data through network. I wonder if this method has any negative effect on networking? |
2 | Is it bad practice to for the server to request data for a client from another client? I'm making a collaborative whiteboard app so that when someone is drawing and uses a rectangle for example, a rectangle packet is sent to the server with parameters like x, y, width, height, color and then that packet is sent to everyone else in the room so that a rectangle is drawn on their screen. So far everything works perfectly and there's also a stack on each client of all the commands thus far for infinite undo and redo. However, there server does not contain this stack because all it has to do is forward commands to clients in the room. Everything is working perfectly so far and everyone can see everyone else drawing in real time but I'd like to implement a feature where if someone joins a room late they can see the current whiteboard. That is, the entire command stack would have to be sent to someone. However, this data isn't stored on the server, but each client has their own (identical copy). Would it be bad for when someone joined to have the server ask one of the clients (which? round robin?) to send his command stack to the server and have the server forward it to the client? My concerns are the delay and teh amount of data being sent in one go (congestion). What do you all think? Are there any other options? |
2 | Canvas animation drops to 30fps every 3 4 seconds Ok! I solved the problem. Chapter One Multiple Canvases I started to make pong utilizing requestAnimationFrame and I noticed that the ball was stuttering and slowing down every 3 4 seconds. So I implemented a crude FPS function to write the current fps to the screen and realized that the slow down was accompanied by an fps drop to 30fps. I thought it had something to do with my collision detection function, but it was not the case. MarkR noticed that I had two canvases drawing and updating the player ball separately, he suggested that I combine the two canvases into one. This produced better performance and now I could only see the slow down stuttering every 15 seconds. The problem was, the stuttering was still happening. Chapter Two Vsync, Chrome Developer Tools In comes Dreta! Dreta said that the fps was dropping to 30fps because canvas is trying to Vsync. I had no idea what he was talking about, so I asked Mr. Google and found a really good explanation of how Vsync double buffering triple buffering works. It's a medium read, but it it definitely worth checking out if you want to learn more about how your graphics card monitor works. He also told me that I can look at the fps of the game in Chrome by using the Developer Tool(which can be accessed by right clicking inspect element Timeline tab and clicking on the black circle at the bottom the circle will turn red when recording). You can also look at the memory usage and I noticed that it was periodically shooting up to 4mbs of memory used. Dreta suggested it was a memory leak Chapter Three Memory Leaks To locate a memory leak, use the following process Found at microsoft site (http msdn.microsoft.com en us library ms859415.aspx) Find the memory leak Detect the presence of a memory leak in the system, given a particular reproducible sequence. You should be able to identify a specific process, but demonstrating an overall increase in committed system memory can qualify a memory leak as well. Isolate the memory leak Determine the exact location in the source code where the un freed allocation occurs. This can be a lengthy and tedious process, requiring specific tools, trial and error, and teamwork with the original author of the code. Fix the memory leak After the first two steps are completed, this is easy. Fixing the memory leak usually involves adding some code to free the memory in the questionable code path. Dreta suggested that I use heap profiling to find memory leaks. I personally have not read up on it yet, but here's a link to chrome's explanation of heap profiling developers.google.com chrome developer tools docs heap profiling. He said Each time you update the player, you're creating a function. You probably want to change the Player class from this.update function() (" c").mousemove(function(event) tempY event.pageY ) this.y tempY which creates a function every 16ms I update the player to var that this (" c").mousemove(function(event) that.y event.pageY ) This helped optimize the game further. Chapter Four I'm stupid, yeah... Chrome Tabs Memory I remembered that there was an issue with chrome with multiple tabs open, and I decided to quit out of and restart chrome anew. Behold! Constant 60fps and 1 2.5 mb memory usage(where it was 2 4mb memory usage before). Moral of the story... close down all tabs and restart chrome before determining the problem, and use heap profiling to locate memory leaks. Thank you everyone for your help! I really do appreciate it. Here's the code on github. Please let me know if you find more stupid mistakes or you have general tips on working with canvas programming. Feel free to email me yangsunwoo gmail.com |
2 | Sync bullets node.js phaser.io i am currently having a struggle thinking about syncing bullets. I am using node js and phaser.io and I am creating top down shooter. I would do it like this Player shoots a bullet. Player sends information where that bullet is Player2 gets information and updates their bullet. But the problem is, when client window is out of focus. Physics are paused and so are bullet movement, which is horrible for multiplayer game. How can I achieve synced bullet across two or more clients . I tried searching for information about server sided physics for node, but I really couldn't find any. Thanks |
2 | javascript game character mouse movement When a mouse button is pressed, coordinates are stored and character begins to move towards that point. I do a check each frame if my character reached the destination, but because of the nature of how it all works, it can never be perfectly accurate. When I normalize my vector and multiply it by speed, I will always end up around that point but never directly at it. The bigger the speed, the more distance is passed in one frame and the further I get from where I wanted to be. let startX 110 let startY 110 let endX 400 let endY 200 let speed 5 let dx endX startX let dy endY startY let length Math.sqrt(dx dx dy dy) dx length dy length dx speed dy speed So this gives me a dx 4.775320684056187 and dy 1.4819960743622644, so that is the value that is added each frame, so in the end it gets to coords 399 191 next one is 404 193 etc. I have to pick a close one, or force object to move to the one I wanted, it never reaches exactly 400 200. It becomes a problem when path finding and collision comes to play, because I can get 2 pixels on an obstacle etc. How is this solved? What am I doing wrong? |
2 | Javascript game engine that can work 'seamlessly' with react native I have experience with Unity, but I don't like the fact that Unity compiles your game directly into APK (or IOS equivalent). I want to modify the game to provide chat interface for multiplayer mode etc. So, I thought of doing it the other way create an app and embed a multiplayer game within it. This approach meant that I had to develop for Android and iOS, separately. I then came across the React Native library, a mobile extension of the popular React framework. I have decided to create an app using React Native, but now I am confused as to which game engine I should use. I think, since React Native is JavaScript, the game engine needs to be in JavaScript for seamless integration. I am planning to use WebView to embed the game in my react native app. Can anyone suggest a good JavaScript game engine that can be used along with react native? I have done some research on Phaser and Pixi, but they use WebGL for rendering and, I read somewhere that WebView doesn't have great support for W bGL or Canvas. |
2 | Peer to Peer world download I am creating a multiplayer JavaScript game with a PHP central server. Each user will be able to move around in a 3D world, with other users and NPCs. It came to my attention that SQL is not going to handle all the requests being made in a reasonable time. So I cut down on SQL requests being made as often, using RAM when I can, but each user that logs into my world, or switches worlds requires a lot of data to be filtered from the server (So the client does not get any information it should not have, and so I don't have to distribute the entire world for every logon) and then uploaded to the client. So I had an idea What if I can get the World data from the users near to the player(In the 3D world), like a BitTorrent? How to resolve syncing issues? What are my options to prevent Hacking? My ideas were check with more than one user, get a hash from a server(will probably have syncing problems), have bots who request worlds from clients then checks with server to see if they are being honest, how ever they all seem to have their problems, and am not sure which one(s) I should incorporate, or if there is a better way I could get correct world data from peers, with minimal server interaction. Note Peer to Peer is only used to get the world, block world updates are still handled between the server and each client |
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 | Shop and Inventory System I'm creating a JavaScript game, and I'm getting stuck. When the player obtains X amount of gold, a middle column appears (you've unlocked the shop, yay!), and when you obtain more gold than an item costs, it will appear (except special conditions where it requires more than just gold of course). Right now, I'm stuck on the base foundation of the system, and I would like to hear some suggestions before I move on. function shop() this.items effect function() engine.player.revive(true) , "price" 100, "name" "Heal" The shop holds an array of item objects, some will be holdable, some will be instant use (currently working on instant use). Now, here's how the item is called in my elements.js file addShopItem function(gold) console.log(engine.shop.items.length) for (var i 0 i lt engine.shop.items.length i ) if (engine.shop.items i "price" lt gold) document.getElementById("items").innerHTML " lt br gt " engine.shop.items i .name , Which is called by going raiding (irrelevant, won't post that code, it's going to change to the engine's trigger function with flags based on the item object. Now my question is Is this a good way to handle an dynamic shop system? What's the best way to link this to a player object? (My initial guess is an object inventory inside the parent? |
2 | Is it bad practice to for the server to request data for a client from another client? I'm making a collaborative whiteboard app so that when someone is drawing and uses a rectangle for example, a rectangle packet is sent to the server with parameters like x, y, width, height, color and then that packet is sent to everyone else in the room so that a rectangle is drawn on their screen. So far everything works perfectly and there's also a stack on each client of all the commands thus far for infinite undo and redo. However, there server does not contain this stack because all it has to do is forward commands to clients in the room. Everything is working perfectly so far and everyone can see everyone else drawing in real time but I'd like to implement a feature where if someone joins a room late they can see the current whiteboard. That is, the entire command stack would have to be sent to someone. However, this data isn't stored on the server, but each client has their own (identical copy). Would it be bad for when someone joined to have the server ask one of the clients (which? round robin?) to send his command stack to the server and have the server forward it to the client? My concerns are the delay and teh amount of data being sent in one go (congestion). What do you all think? Are there any other options? |
2 | 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 | 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 | Canvas animation drops to 30fps every 3 4 seconds Ok! I solved the problem. Chapter One Multiple Canvases I started to make pong utilizing requestAnimationFrame and I noticed that the ball was stuttering and slowing down every 3 4 seconds. So I implemented a crude FPS function to write the current fps to the screen and realized that the slow down was accompanied by an fps drop to 30fps. I thought it had something to do with my collision detection function, but it was not the case. MarkR noticed that I had two canvases drawing and updating the player ball separately, he suggested that I combine the two canvases into one. This produced better performance and now I could only see the slow down stuttering every 15 seconds. The problem was, the stuttering was still happening. Chapter Two Vsync, Chrome Developer Tools In comes Dreta! Dreta said that the fps was dropping to 30fps because canvas is trying to Vsync. I had no idea what he was talking about, so I asked Mr. Google and found a really good explanation of how Vsync double buffering triple buffering works. It's a medium read, but it it definitely worth checking out if you want to learn more about how your graphics card monitor works. He also told me that I can look at the fps of the game in Chrome by using the Developer Tool(which can be accessed by right clicking inspect element Timeline tab and clicking on the black circle at the bottom the circle will turn red when recording). You can also look at the memory usage and I noticed that it was periodically shooting up to 4mbs of memory used. Dreta suggested it was a memory leak Chapter Three Memory Leaks To locate a memory leak, use the following process Found at microsoft site (http msdn.microsoft.com en us library ms859415.aspx) Find the memory leak Detect the presence of a memory leak in the system, given a particular reproducible sequence. You should be able to identify a specific process, but demonstrating an overall increase in committed system memory can qualify a memory leak as well. Isolate the memory leak Determine the exact location in the source code where the un freed allocation occurs. This can be a lengthy and tedious process, requiring specific tools, trial and error, and teamwork with the original author of the code. Fix the memory leak After the first two steps are completed, this is easy. Fixing the memory leak usually involves adding some code to free the memory in the questionable code path. Dreta suggested that I use heap profiling to find memory leaks. I personally have not read up on it yet, but here's a link to chrome's explanation of heap profiling developers.google.com chrome developer tools docs heap profiling. He said Each time you update the player, you're creating a function. You probably want to change the Player class from this.update function() (" c").mousemove(function(event) tempY event.pageY ) this.y tempY which creates a function every 16ms I update the player to var that this (" c").mousemove(function(event) that.y event.pageY ) This helped optimize the game further. Chapter Four I'm stupid, yeah... Chrome Tabs Memory I remembered that there was an issue with chrome with multiple tabs open, and I decided to quit out of and restart chrome anew. Behold! Constant 60fps and 1 2.5 mb memory usage(where it was 2 4mb memory usage before). Moral of the story... close down all tabs and restart chrome before determining the problem, and use heap profiling to locate memory leaks. Thank you everyone for your help! I really do appreciate it. Here's the code on github. Please let me know if you find more stupid mistakes or you have general tips on working with canvas programming. Feel free to email me yangsunwoo gmail.com |
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 | Configurable Dice Cup Sound Effect for HTML5 Game I am developing an HTML5 javascript based game, where the players will have to roll virtual dice. I am working on a 3d model of a dice Cup and plan on having the users shake it and turn it upside down in order to roll the dice. I would like some realistic sound effects to go along with this interaction, but do not know how to achieve this. The problem is that the number of dice, the duration, intensity and speed of the dice cup shake will vary. Consequently, I don't think I will be able to create a convincing sound experience by using a prerecorded sound effect. How does one deal with making such sound effects configurable?Would I need to programmatically generate the sound using the web audio API? If so I would be grateful for any pointers as to how to do it. |
2 | Canvas setTransform function clarification I'm currently building some kind of fake 3D dungeon, and I'm facing some difficulties understanding the behavior of the setTransform() function. Here's my simplified code var can document.getElementById('c'), ctx can.getContext('2d'), angle Math.PI 4 ctx.fillStyle "grey" ctx.setTransform(1, Math.tan(angle), 0, 1, 0, 0) ctx.fillRect(100, 0, 50, 50) Here's also s JsBin with the same code for you to see the result http jsbin.com oxaSIpe 7 edit Changing the x coordinate in the fillRect seems to also affect the y coordinate. It makes no sense. Skewing an element changes its position? No documentation mentions anything like that. If anyone could please try to explain this function and its weird behavior, I would be very grateful. |
2 | Invulnerability timer while standing on spikes I want to decrement the player's health every .7 seconds while the warrior is standing on a spike tile. Every frame, the game calculates what kind of tile the player is walking into. I've tried calling a function that uses setTimeout from the spike tile code in the walkingIntoTileType switch statement and I've tried using setInterval directly in the switch statement. My current implementation has this declaration at the top of the warrior class this.interval setInterval(function() blank , 1000) clearInterval(this.interval) I then have this in the warrior movement code, which gets run every frame switch( walkIntoTileType ) case TILE GROUND this.x nextX this.y nextY this.onSpikes false break other tile type code... case TILE SPIKES this.x nextX this.y nextY this.onSpikes true default any other tile type number was found... do nothing, for now break if(this.onSpikes) if(!this.running) this.running true this.interval setInterval(function() this.playerHealth , 700) else this.running false clearInterval(this.interval) Despite this, the player's health never gets decremented when on the spikes, and the console returns no errors. I would think the interval is not falling victim to garbage collection since its variable is declared at the top of the class, but obviously I could be wrong. |
2 | How can I have more values in array on X axis than Y axis in my tilemap? Following my old question Array of map data renders the map the opposite way after I got the answer to it and fixed my problem, I got another problem that occurs. If my mapArray is bigger on X axis than Y axis, I get script.js 113 Uncaught TypeError Cannot read property '0' of undefined So if my array looks like this, for example 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , I get an error. If I change it to this 2, 2, 2, 2, 2, 2, , 2, 2, 2, 2, 2, 2, , 2, 2, 2, 2, 2, 2, , 2, 2, 2, 2, 2, 2, , 2, 2, 2, 2, 2, 2, , 2, 2, 2, 2, 2, 2, , 2, 2, 2, 2, 2, 2, , 2, 2, 2, 2, 2, 2, , 2, 2, 2, 2, 2, 2, , (more values vertically) it works fine. I know that it has to do with my loop condition for (let i 0 i lt mapArray.length i ) for (let j 0 j lt mapArray i .length j ) j lt mapArray i .length this is not true if j is bigger than i length. Makes sense. But if I change the comparison lt value to gt I don't get drawn on the canvas anything but the white bg only. My question How can I have a big mapArray horizontally so that I could scroll it and have big game world without making it huge on the y axis as well? Code var mapArray 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 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, 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 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 , function render(viewport) context.save() if(Math.floor(boatPosX 36) lt 10) 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 j i 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 j i 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 j i 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) if(isPositionWall(boatPosX 36, boatPosY)) boatPosX oldPosY console.log("collision") context.restore() I know what's causing the problem (the loop) but not sure how to fix it properly. |
2 | How to make Pong Ball Control? I want to know how can I make the control of the Pong Ball in Plain Javascript. I would like to know how to make the ball faster when it hits the edges just like the original pong game, or how if the ball hit's the middle of the paddle it would go straight and slow. I just want to get a feel for how it works. |
2 | setting a time delay between two frame when animation a sprite sheet this is my jsfiddle http jsfiddle.net Z7a5h As you can see the animation of the sprite sheet when the player is not moving is too fast so i was trying to make it slow by declaring two variable lastRenderTime 0,RenderRate 50000 but my code is not working and it seem i have a misunderstanding of the algorithm i am using so can anyone lay me a hand to how can i fix it ? if (!this.IsWaiting) this.IsWaiting true this.Pos 1 (this.Pos 1) 3 else var now Date.now() if (now this.lastRenderTime lt this.RenderRate) this.IsWaiting false this.lastRenderTime now |
2 | 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 | 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 | Finding the closest face normal from a given point in space efficiently I have a large model (roughly 400k faces) and a large number of points on this model (roughly 2000) and I need to calculate a normal per point based on the closest face on the model. Is there a faster way that isn't O(n m) where n is the number of points and m is the number of faces (e.g., raycasting or iterating through every face)? I'm using THREE.js and the target hardware is a Toshiba tablet with Intel integrated graphics so I don't have a lot of power to work with. Currently if I compute this on load it takes about 10 minutes. I've been given the requirement that there shouldn't be any model specific information precomputed for each point so that we can use the points on a different model without recomputing everything and then have multiple datasets of point normal mappings. This is currently what we are doing and it works but doesn't scale well to our needs. |
2 | Are spritesheets worth it? Is a zip a good alternative? I was wondering if spritesheets are worth it. I am making a game with pixi.js and was thinking about optimization, beginning with asset loading. I currently have an arraya of all files and use PIXI.loader, but I know this is not good because it will make a web request for all files which takes long, so I should figure out a way to load them in one web request. The first thing I thought of was a spritesheet but then I thought quot what if I just zipped everything and loaded it with something like JSZip? quot I knew it was possible already (from this project that loads pixi textures from a zip) and listed what I think are potentials good and bad things Zip good points Compression meaning faster loading of assets Compression meaning smaller build size when making a build with electron Zip bad points Requires loading a separate library meaning increased loading time and using more RAM Requires decompressing in memory meaning increased loading time Spritesheet good points Doesn't has the headers of all individual image files Is much used so it is a proven technique Spritesheet bad points No compression (or at least not comparable to zipping) More than one network call due to phone limitations preventing sometimes files over 2024x2024px making it necessary to split spritesheets Empty holes as all images are not the same size and there is almost always a bit of space left in the spritesheet, meaning useless pixels that are still transfered over the network I am not a very experienced developper, so I have a few questions Did I miss a point above? Are spritesheets generally worth it? Which technique of both is more worth it? I could do both but I want to focus on one first and leave the other in a nice to have list. |
2 | setTint() on half image I'm developing a game where I need to paint half of a image when the user is either wrong or right. To paint the image, I'm using setTint() to paint the image the color I need, but it paints the whole image, is there any way I can paint only half, using setTint or another method? |
2 | How would one create a "start button" on a website similar to some Korean games? Some games have buttons that would actually let you click them and you'd log right into the game. How does the web browser get permission to do this without plugins? Perhaps the client registers a custom protocol URL? They used to be popular a few years back I can't remember any implementations off the top of my head. On desktop browsers, if your game client was installed clicking 'Play' on the home page would boot up the game begin it with you already signed in. It was popular with arcade games so you could browse the sessions on the web and then simply hit 'Start'. You didn't need any browser plugins. |
2 | Javascript and PHP for real time multiplayer? I'm wondering if combining Javascript clientside with PHP mysql serverside is a good idea for HTML5 real time multiplayer (small scale) browser games? My technical knowledge is very limited, and even though I plan on learn node.js in the future, the learning curve is rather huge right now. Since I'm already familiar with PHP I feel I would get it functioning much faster. The scale I'm thinking is 2 8 players at the time. And trying to keep the client to server message count as low as possible. The values I intend to store handle are Player name and ID. X and Y position. Health. Equipped items (maximum 8 slots, probably less). Actions (walk, attack, use etc but only 1 action player at a time). Bullet X,Y coordinates and trajectory. Guild Clan name. And some basic chat mailing function. My guess is even though it's not the best solution, but aslong as I keep the logic small, that this is completely doable. Am I right? |
2 | phaser.io mouse cursor sprite I am trying to build a game and i want people to be able to select stuff with a pointer but i don't want it to be just an ugly looking default pointer so i wrote this code to try and get a image as it first i loaded the image game.load.image('selector', 'assets img pointer.png') then I put it into my game selector game.add.sprite(game.world.centerX, game.world.centerY, 'selector') and then in my render() function i do this selector.x game.input.x selector.y game.input.y it moves fine with my mouse but with one problem my game is designed so that i have to use a camera that follows my character because the map is bigger than the view so since for some reason my sprite always starts at 0,0 it can only move 800x600px since thats all that the canvas sees the mouse in so i need a way to fix this but i'm not sure how to do this because i am new to phaser |
2 | Javascript Canvas Drawing Efficiency I have just recently started some experiments with game development in Javascript HTML5, and so far it has been going pretty well. I have a simple test scene running with some basic input handling, and a hundred ish drawImage() calls with a few transforms. This all runs great on Chrome, but unfortunately, it already chugs on Firefox. I am using a very large canvas ( 1920 x 1080 ), but it doesn't seem like I should be hitting my limit already. So on that note, I was hoping to ask a few questions 1) What exactly is done on the CPU vs. the GPU in terms of canvas and drawImage()? I'm afraid the answer is probably "it depends on the browser", but can anybody give me some rules of thumb? I naively imagined that each drawImage call results in a textured quad on the GPU with the canvas effectively being a render target, but I'm wondering if I'm pretty far off base there... 2) I have seen posts here and there with people saying not to use the translate(), rotate(), scale() functions when drawing on the canvas. Am I adding a lot of overhead just by adding a translate() call, as opposed to passing in the x,y to drawImage()? Some people suggest using "transate3d", etc., which are CSS properties, but I'm not sure how to use them within a scene. Can they be used for animated sprites within a single canvas? 3) I have also seen a lot of posts with people mentioning that pre building canvases and then re using them is a lot faster than issuing all the individual draw calls again. I am guessing that my background should definitely be pre built into a canvas, but how far should I take this? Should I maintain an individual canvas for each sprite, to cache all static image data when not animating? Thank you much for your advice! |
2 | How to make physics of motion on an inclined surface There is the following platform And a coin above it And the following code using arcade physics gravity y 100, x 10 , in config function preload () this.load.image('platform', 'assets platform.png') this.load.image('star', 'assets star.png') function create () platforms this.physics.add.staticGroup() platforms.create(400, 568, 'platform') player this.physics.add.sprite(100, 450, 'star') player.setCollideWorldBounds(true) The code is approximate, a coin above the platform, sprites in png format. But the coin falls and does not roll, but moves horizontally, after which it falls again. How to make it "roll"? UPD Will it help me? https github.com photonstorm phaser examples blob master examples arcade 20physics circle 20body.js And how to be with the platform? |
2 | Simulating Enums with Javascript When developing in Javascript, it seems useful especially for event systems to use enum likes, but not string comparison for performance considerations (also because it doesn't protect against typos). How do you use Enums in JS? Should I switch to Typescript? |
2 | Can "dumbphones" play JavaScript games? Are JavaScript games exclusive to modern smartphones, or are older phone models also able to play games written in JavaScript? |
2 | Shadows in html5 canvas game I'd like to ask for reference. I met an article about how to cast shadows in games. I'm using html5 canvas (currently without webgl) with javascript for my projects. The article mentioned above is located at http willyg302.wordpress.com 2012 11 04 2d visibility . I was thinking if this method is possible to employ with canvas (without webgl) and javascript? More precisely, I have few shapes drawn on canvas some of them are complex made by arc and similar methods. Thus I don't have a simpel way how to describe one shape with an equation where I can store only a few parametrs (i.e. circle is described as centerX, centerY, radius with these I can easily draw it but with more complex shapes I don't have such information) therefore I thought about storing the whole canvas data by pixels with context.getImageData.data, then using method described in the article (polar transformation, ..., back to cartesian system) and putting the whole scene into canvas with canvas.putImageData method. But before actually applying this I'd like to ask if it's even possible with canvas (no webgl) and javascript to create shadows dynamically (light source moving across the screen) this way without heavy fps loss (I can imagine this method works pretty good for still objects but the moment when I need to do it each time a light source moves I'm not sure if javascript canvas can handle this in reasonable time, especially when I found information that putImageData and getImageData are quite slow)? Or if anyone has tried to create dynamic shadows in different way in html5 js I'd appreciate your suggestions about these as well (I do it currently in similar way as is described in http ncase.me sight and light , though I'm experiencing some troubles with concave shapes ( ). This is getting awfully long, I hope I explained myself well enough. Thank you very much for any advice you can share and I'm sorry that my post grew so large, although I'm asking just one question. EDIT Forgot to mention, I'm looking only for 2d solution. |
2 | phaser.io mouse cursor sprite I am trying to build a game and i want people to be able to select stuff with a pointer but i don't want it to be just an ugly looking default pointer so i wrote this code to try and get a image as it first i loaded the image game.load.image('selector', 'assets img pointer.png') then I put it into my game selector game.add.sprite(game.world.centerX, game.world.centerY, 'selector') and then in my render() function i do this selector.x game.input.x selector.y game.input.y it moves fine with my mouse but with one problem my game is designed so that i have to use a camera that follows my character because the map is bigger than the view so since for some reason my sprite always starts at 0,0 it can only move 800x600px since thats all that the canvas sees the mouse in so i need a way to fix this but i'm not sure how to do this because i am new to phaser |
2 | How do I make the background color fade into a different color after hovering it? I was trying to make the starter inputs for my text rpg change the background color in a fade effect with JQuery, but I cant figure out what i did wrong. Heres the part im focusing on lt script gt (document).ready(function() Intro Inputs (' Header Intro input') Intro Inputs.hover(function() (this).animate( 'background color' ' 2E8AE5' , 'slow') ) ) lt script gt If anyone could help me out with the mistake i made i would greatly appreciate it! (The problem was that it wouldnt fade the colors in) |
2 | Intellisense with PhaserJS Library in Visual Studio Code I am trying to use Visual Studio code along with PhaserJS but am confused about why the isn't working. I've read through http www.johnpapa.net intellisense witha visual studio code am think I am doing it correctly but still don't get auto complete. When Phaser gets a green underline and lightbulb, the bulb doesn't include a create reference so I created one above manually. |
2 | align local Y to be parallel with global Y during or after slerp I am using the following function to have a globe rotate a point on its surface to face the global Z toward the camera. This works fine, but after each rotation the Y axis seen as a green line is not vertically aligned. I believe this is how slerp between two unit vectors works, it takes the shortest path. I would like to know how can I achieve this rotation whilst getting the globe to rotate itself so that Y is at least parallel to the global Y? function rotateToHub(continent) var speed 2000 var z new THREE.Vector3(0, 0, 1) point continent.position.clone().normalize() var q new THREE.Quaternion() q.setFromUnitVectors(point, z) var duration t 0 var tween new TWEEN.Tween(duration) .to( t 1 , speed) .onStart(function() slerp true ) .onUpdate(function() earthContainer.quaternion.slerp(q, this.t) ) .onComplete(function() slerp false update() ) .start() |
2 | Resizing a tiledmap when using phaser var cw window.innerWidth var ch window.innerHeight var game new Phaser.Game(cw, ch, Phaser.AUTO, 'game', preload preload, create create, update update ) function preload() game.load.tilemap('Background', 'https gist.githubusercontent.com anonymous c61b37df015a0b2af1d7 raw 172bf9c2d4c20c56699eacce263525409caaf743 54996634e4b0a35d00c9b516.json', null, Phaser.Tilemap.TILED JSON) game.load.image('tiles', 'http i.imgur.com gmWQIFK.png') game.load.image('player', 'http i.imgur.com tCCrLyh.png') var map var layer var player var keyboard var playerJumping function create() player game.add.sprite(0, ch 32, 'player') game.world.setBounds(0, 0, cw, ch) game.physics.startSystem(Phaser.Physics.ARCADE) game.physics.arcade.gravity.y 300 game.physics.enable(player, Phaser.Physics.ARCADE) player.body.collideWorldBounds true game.stage.backgroundColor ' 787878' map game.add.tilemap('Background') map.addTilesetImage('smb tiles', 'tiles') layer map.createLayer('Tile Layer 1') layer.resizeWorld() keyboard game.input.keyboard.createCursorKeys() game.camera.follow(player) function update() player.body.x 2 if ( keyboard.up.isDown amp amp player.body.onFloor()) playerJumping true player.body.velocity.y 2 else playerJumping false lt script src "http yourjavascript.com 222115941388 phaser min.js" gt lt script gt lt div id "game" gt lt div gt As you can see the tiled Map start at a height of 320px bcs originally the map have this height and if I change the game height to 320px everything works fine , but my question is if i want to make the tiledMap responsive to innerHeight and width for the screen how can i do this so the tiled map start at the bottom of the screen and not at the 320px you can see how the tiled map layer is starting in the middle of the screen . is there by any chance something i can do to make it start at the bottom of the screen |
2 | Is it more efficient to encode rotation in a spritesheet or rotate at runtime? I'm developing a game with JavaScript and HTML5 and I'm wondering about the performance implications of sprite rotations. There are two ways that I know to rotate a sprite Rotate the actual sprite based on its rotational speed and velocity, as it travels along it's trajectory. Pre compute the rotations and store them as frames within the sprite sheet to give the illusion that it's spinning when it isn't. On one hand, I can see how rotating some sprites in a spritesheet would be efficient because it's one image that is loaded, split into frames, and re used. But on the other hand, I'm not sure the calculations involved for rotating the sprite based on its velocity and rotational speed are really anything for current browsers (on computers and mobile devices) to worry about. In my game, the canvas area is 800 x 600, and the game is using 32 x 32 sprites for everything. The "map" isn't tile based. Of the two options above, which would be more efficient for runtime performance? |
2 | In JavaScript, should I write a game loop for a turn based game? I am using javascript and HTML5 canvas for turn based games (e.g., checkers, mastermind, minesweeper). Should I write a fixed timestep game loop? What are the alternatives? |
2 | "Painting" elements in html5 canvas I'm making a game in coffeescript (although for the sake of this problem that's probably not all that relevant) and html5's canvas. It's a game that involves a paint cannon, that fires circular particles of paint that can paint elements of the level and the player. The problem is I'm not sure how to accomplish the painting. The diagram below illustrates what I'm trying to accomplish Using canvas, the particles are drawn using context.arc(), the players using drawRect.arc() and the floor can be an arbitrary polygon with drawing code as follows drawingContext.beginPath() tV b2Math.AddVV(pos, b2Math.MulMV(body.GetTransform().R, vertices 0 )) drawingContext.moveTo(tV.x, tV.y) for i in 1.. vertices.length 1 v b2Math.AddVV(pos, b2Math.MulMV(body.GetTransform().R, vertices i )) drawingContext.lineTo(v.x, v.y) drawingContext.lineTo(tV.x, tV.y) drawingContext.closePath() drawingContext.stroke() drawingContext.fill() It would be too intensive to keep track of all the circles that should be painted on to objects and would soon bog down, with potentially 60 clipped circles per second being added to be drawn on top of objects. The original thought was to stack two canvases on top of each other, so then we could draw the levels once and then when ever necessary just draw the paint splat over them once and forget about it (changing the composition mode to source atop to get appropriate clipping), and since we're not redrawing it would stay there. However, this won't work on moving objects (like players) (that can also rotate and change size relative to the camera). I'm not sure how to do it, since all objects are made up of solid colour to start with there's no texture data or anything we can modify. |
2 | Get return of asynchronous callback since module export Nodejs Server require('. MovimientoJugador')() var camino4 MoverJugador(startX,startY,endX,endY,mapa2) console.log("Camino " camino4) MovimientoJugador module.exports function() var Camino "uno" this.MoverJugador function(startX,startY,endX,endY,mapa) easystar.findPath(startX, startY, endX, endY,function( path ) Camino JSON.stringify(path) console.log("C " Camino) return Camino Console Camino uno C (X 1,Y1)(X2 Y2) etc... The variable Camino has the value of one when declared. At the time that the server shows it, it does not give you time to show the last return value. How could I turn this into a promise or make a wait of x seconds? |
2 | HTML5 Canvas Drawing with Floats I'm trying to implement a game where you have car moving along a line in HTML5 Canvas. Using a little bit of trigonometrie I managed to get the right x and y coordinates to add to the coordinates of my image each frame to get to the end of the "line". Now the problem is, the image I use for the car starts to stutter in the process of rendering. The problem has to be the values I'm adding. (first I thought the problem would be the render loop but when using the render loop from paul irish the same problem occurs) My question is, how can I use floats in context.drawImage(img,...) smoothly? What I tried was rounding the values where the image should move to (e.g. context.drawImage(img, Math.round(car.x), Math.round(car.y))) but this doesn't work also. simple code example to demonstrate the issue (using a simpler loop, but like I said, the problem isn't the loop) How it looks Here is the whole thing var canvas document.getElementById("canvasID") var context canvas.getContext("2d") var car new Car(20,10) var carImg new Image() carImg.src "https i.stack.imgur.com L2XQW.png" function Car(x,y) this.x x this.y y Car.prototype.advancePosition function(x,y) this.x lerp(car.x, car.x x, 1) this.y lerp(car.y, car.y y, 1) function update() car.advancePosition(0.91,0.4) function lerp (start, end, amt) return (1 amt) start amt end function render() context.beginPath() context.clearRect(0,0, canvas.width, canvas.height) context.drawImage(carImg, car.x, car.y) context.closePath() window.requestAnimFrame (function(callback) return window.requestAnimationFrame window.webkitRequestAnimationFrame window.mozRequestAnimationFrame window.oRequestAnimationFrame window.msRequestAnimationFrame function(callback) window.setTimeout(callback, 1000 100) )() (function mainLoop() requestAnimFrame(mainLoop) render() update() )() canvasID z index 1 background eee display block vertical align middle margin 0 auto z index 1 webkit box sizing border box moz box sizing border box box sizing border box position absolute webkit transform translateZ(1) lt html gt lt head gt lt meta charset "utf 8" gt lt meta name "viewport" content "width device width, initial scale 1.0, user scalable no" gt lt link rel "stylesheet" type "text css" href "style.css" gt lt title gt test lt title gt lt head gt lt body gt lt div class "canvas wrapper" gt lt canvas id "canvasID" width "500" height "450" gt Canvas not supported, please update your browser lt canvas gt lt div gt lt script src "main.js" gt lt script gt lt body gt lt html gt I would be happy if someone could help me out Thanks edit Tried the suggestions from the comments but nothing worked. |
2 | Rectangles clear each other when moving on canvas I am having this problem after moving rectangles, they seem to delete one another. Most probably it is a problem with clearRect(...) method. This is the clean function I am using clean function(element) All default values clean all the screen if(typeof element.x 'undefined') element.x 0 if(typeof element.y 'undefined') element.y 0 if(typeof element.width 'undefined') element.width canvas.width if(typeof element.height 'undefined') element.height canvas.height In case values are entered if(element.type 'rectangle') ctx.clearRect(element.x,element.y,element.width,element.height) This is the rendering rect function(element) Check if color is defined if(typeof element.color 'undefined') element.color 'black' else ctx.fillStyle element.color Draw the rectangle ctx.fillRect(element.x,element.y,element.width,element.height) |
2 | Dividing up spritesheet in Javascript I would like to implement an object for my spritesheets in Javascript. I'm very new to this language and game developement so I dont really know how to do it. My guess is I set spritesize to 16, use that to divide as many times as it fits on the spritesheet and store this value as "spritesheet". Then a for(i 0 i lt spritesheet.length i ) loop running saving the number of sprites. Then tile new Image() and tile.src spritesheet i to store the individual sprites based on their coordinates on the spritesheet. My problem is how could I loop trough the spritesheet and make an array of that? The result should be similar to sprite.sprites Array( "0", "1" ) If possible this would be done with one single object that i only access once, and the tile array would be stored for later reference. I couldn't find anything similar searching for "javascript spritesheet". Edit 2 I've come a long bit since I first posted this question and this is what I've come up with so far function Sprite() this.size 16 this.spritesheet new Image() this.spritesheet.src 'spritesheet.png' this.spriteCount this.spritesheet.height this.spritesheet.width this.spriteIndex 0 var sprites new Array() for(i 0 i lt this.spriteCount i ) sprites.push(this.spriteIndex) Could insert pretty much whatever I want this.spriteIndex alert('spriteIndex ' sprites i ' pushed') var sprite new Sprite() The alert method is only for testing, it alerts from 0 and up giving me usable X and Y values for the drawing (when multiplyed by size). If anyone has improvements please let me know. Edit 3 I still have some trouble with the array. How would i access the index of it? For example the first sprite should give me sprite.sprites 0 second sprite sprite.sprites 1 . |
2 | How to protect source code when game is developed in HTML5 Javascript Possible Duplicate How do you prevent your JavaScript HTML5 web game from being copied or altered? If a game client is developed in Javascript, the source code can be found in browser. It's dangerous, because it's easy to hack the game, and patent can't be protected. Are there any good ways to avoid this, e.g Javascript can be compiled to binary file then browser load and run the compiled javascript? |
2 | How can I call a native mobile API in Construct 2? How can I use mobile API features in a Construct 2 game (HTML 5 JavaScrit engine)? I didn't find anything about that on the net, unlike other game frameworks like Corona Enterprise or Cocos2d. |
2 | Configurable Dice Cup Sound Effect for HTML5 Game I am developing an HTML5 javascript based game, where the players will have to roll virtual dice. I am working on a 3d model of a dice Cup and plan on having the users shake it and turn it upside down in order to roll the dice. I would like some realistic sound effects to go along with this interaction, but do not know how to achieve this. The problem is that the number of dice, the duration, intensity and speed of the dice cup shake will vary. Consequently, I don't think I will be able to create a convincing sound experience by using a prerecorded sound effect. How does one deal with making such sound effects configurable?Would I need to programmatically generate the sound using the web audio API? If so I would be grateful for any pointers as to how to do it. |
2 | How to leave trails that are equidistant apart from each other I want bunch of circles to follow the player while keeping a distance apart. So far I have this local p x 0, y 0, life x 0,y 0 , x 0,y 0 , x 0,y 0 , x 0,y 0 local last x p.x,y p.y for l in all(p.life) do l.x lerp(last.x,l.x,0.5) l.y lerp(last.y,l.y,0.5) circfill(l.x,l.y,2,7) last x l.x,y l.y end But this makes it so the circles collapse into each other and the player. I want the circles to have a distance between themselves and the player. I've also tried this l.x lerp(last.x 0.8,l.x,0.5) This leaves a distance as I want but the trail is always on the upper left, barely following player. I want the trail to stay always behind the player. Probably I can achieve this by stop following if the distance is less than threshold. |
2 | Javascript Canvas Drawing Efficiency I have just recently started some experiments with game development in Javascript HTML5, and so far it has been going pretty well. I have a simple test scene running with some basic input handling, and a hundred ish drawImage() calls with a few transforms. This all runs great on Chrome, but unfortunately, it already chugs on Firefox. I am using a very large canvas ( 1920 x 1080 ), but it doesn't seem like I should be hitting my limit already. So on that note, I was hoping to ask a few questions 1) What exactly is done on the CPU vs. the GPU in terms of canvas and drawImage()? I'm afraid the answer is probably "it depends on the browser", but can anybody give me some rules of thumb? I naively imagined that each drawImage call results in a textured quad on the GPU with the canvas effectively being a render target, but I'm wondering if I'm pretty far off base there... 2) I have seen posts here and there with people saying not to use the translate(), rotate(), scale() functions when drawing on the canvas. Am I adding a lot of overhead just by adding a translate() call, as opposed to passing in the x,y to drawImage()? Some people suggest using "transate3d", etc., which are CSS properties, but I'm not sure how to use them within a scene. Can they be used for animated sprites within a single canvas? 3) I have also seen a lot of posts with people mentioning that pre building canvases and then re using them is a lot faster than issuing all the individual draw calls again. I am guessing that my background should definitely be pre built into a canvas, but how far should I take this? Should I maintain an individual canvas for each sprite, to cache all static image data when not animating? Thank you much for your advice! |
2 | Jump handling and gravity I'm new to game development and am looking for some help on improving my jump handling for a simple side scrolling game I've made. I would like to make the jump last longer if the key is held down for the full length of the jump, otherwise if the key is tapped, make the jump not as long. Currently, how I'm handling the jumping is the following Player.prototype.jump function () Player pressed jump key if (this.isJumping true) Set sprite to jump state this.settings.slice 250 if (this.isFalling true) Player let go of jump key, increase rate of fall this.settings.y this.velocity this.velocity this.settings.gravity 2 else Player is holding down jump key this.settings.y this.velocity this.velocity this.settings.gravity if (this.settings.y gt 240) Player is on the ground this.isJumping false this.isFalling false this.velocity this.settings.maxVelocity this.settings.y 240 I'm setting isJumping on keydown and isFalling on keyup. While it works okay for simple use, I'm looking for a better way handle jumping and gravity. It's a bit buggy if the gravity is increased (which is why I had to put the last y setting in the last if condition in there) on keyup, so I'd like to know a better way to do it. Where are some resources I could look at that would help me better understand how to handle jumping and gravity? What's a better approach to handling this? Like I said, I'm new to game development so I could be doing it completely wrong. Any help would be appreciated. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.