_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
2 | Rotating a view of a chunked 2d tilemap I'm working on a top down (oblique) tile based engine. I would like for the tiles to have a definable height in the world, with Characters being occluded by them, etc. This has led to a desire to be able to "rotate" the view of the world, even though I'm using all hand drawn graphics and blitting. Therefor, I need to rotate the actual world itself, or change how the Camera traverses these arrays. How can, or should, I create individual rotations of 90 degrees, when I have multi dimensional arrays? Is it faster to actually rotate the array, to access it differently, or to create pre computed accessor(?) arrays, something like how my chunks work? How can I rotate an individual chunk, or set of chunks? Currently I establish my tile grid like this (tile height not included) function Surface(WIDTH, HEIGHT) WIDTH Math.max(WIDTH (WIDTH TPC), TPC) HEIGHT Math.max(HEIGHT (HEIGHT TPC), TPC) this.tiles this.chunks Establish tiles for(var x 0 x lt WIDTH x ) var col , ch x Math.floor(x TPC) if(!this.chunks ch x ) this.chunks.push( ) for(var y 0 y lt HEIGHT y ) var tile new Tile(x, y), ch y Math.floor(y TPC) if(!this.chunks ch x ch y ) this.chunks ch x .push( ) this.chunks ch x ch y .push(tile) col.push(tile) this.tiles.push(col) Even some basic advice on my data struct would be much appreciated. |
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 | Using a setTimeout to Jump I am trying to make a jump function. I am making a game in html5 canvas with Javascript. I have gotten the player to move. When making the jump function I decided to use a timeout to reverse the coordinates back to the original after a set time. The error is after the character moves up he does not return to the original position the character just stays there, and then upon clicking the jump (arrow key) again the player goes the other way e.g (down). class Character constructor() this.x 50 this.y 400 this.posX 0 this.posY 0 this.width this.height this.hitPoints 1 this.directionFace "right" this.jump false this.jumpHeight 23 move(e) this.x this.posX this.y this.posY if (e.keyCode 37) console.log('left') this.posX 10 else if (e.keyCode 38) console.log("UP") if (!this.jumping) this.posY this.jumpHeight this.jumping true setTimeout(function() this.posY this.jumpHeight this.jumping false , 500) else if (e.keyCode 39) console.log("right") this.posX 10 e.preventDefault() |
2 | How do I protect sending scores from HTML5 games to my server On backend I am using java. I have a game in HTML5 when user completes it I sends an Ajax call to save the score to database. Now, someone can easily use tools like Fiddler and firebug to modify this ajax request and send a much better score to the server. How do I make sure that user cannot manipulate scores ! |
2 | Unity 5 Animation attaching I have created the walking and idle animation for my fps player. I've added a JavaScript script to access it, but when I run it and press button(w), it stops and says that the animation is not attached to the object. When I drag the walking idle animation and drop to that object, it creates an animation controller. Again I run it, still same error. I can't find where to attach the animation Here's my script function Update () if(Input.GetKeyDown("w")) GetComponent. lt Animation gt ().Play("walk anim2", PlayMode.StopAll) if(Input.GetKeyUp("w")) GetComponent. lt Animation gt ().Play("idle anim2", PlayMode.StopAll) Where do I need to attach the animation? |
2 | Should I refer to browser based games as HTML5 games or Javascript games? First of all, I know that there are alternatives to both HTML5 and Javascript, but I worded the question so generally ("browser based") because if I had said "HTML5" or "Javascript" games that would already imply an answer to the question. When writing wiki posts or discussing, I usually call these games "HTML5 Javascript" games. They are written in Javascript, using the new HTML5 technology. What is the proper way to call them HTML5 or Javascript games? I see that most people opt for HTML5, why? |
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 | Throw ball distance and force I have a question, I need a formula to calculate the distance and a force based on the speed that drags the finger up on the phone. And is there any way I can get a look? And also shows the trajectory of the ball with lines ... An example is the Pokemon Go, see the image (the user presses the ball and drags the finger upwards). Are there any examples so that I can study? |
2 | How to display a tile map from a 2D array in JavaScript? I have stored my map, but the problem I am having is displaying it. My map is 100x100 tiles which are 40x40px. I have my loop running through the array but I'm having difficulty selecting the portion of the map image to relate to the tiles. This is the code which selects the portion of the image on each iteration var sx Math.floor(tileId 8 tileWidth) source x var sy Math.floor(tileId 8 tileHeight) source y I'm using Canvas and keep getting this error message INDEX SIZE ERR DOM Exception 1 Index or size was negative, or greater than the allowed value. I'm guessing the remainder or division by 8 is wrong, this is something I picked up from the net, but what exactly does that integer need to be? Thanks |
2 | 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 | 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 | Open Source HTML JS game(s) with license that would allow embedding in my app? I'm working on an educational app for kids. At the end of the sign up process, the kids must wait for a confirmation from their parents in order to gain access to the app. While they wait for this to happen, we want to let the kid play a simple game as a way to keep their interest up. Is there a marketplace or repository for games with such a license that we could either purchase (affordably) or use for free in our own app? |
2 | How To Upload JavaScript Games To Steam So I've been making this game called The Necromancer and (quick note, I am still working on the game. Also, I know this sounds similar to this question, but my question is for the general process) I wanted to publish on the Steam Store. However, I don't know what the process is, as in what you do to get your game posted on Steam. Also, how would I get a few files, and somehow put it in a virtual package that I can give to Steam. I just feel rather confused on the subject. Thank you for your time |
2 | Use JS to grab values from a dynamic Lua Table ((BACKGROUND I'm modding a game that runs using Lua and the Source2 Engine (Dota). Gameplay logic uses Lua and HUD uses JS)) I used Lua to create a global table. For instance global itemRollsManager itemID id 19, buff1 quot modifier bonus range quot , ability quot tusk ice shards quot Now I need to grab that info and display it in the HUD using JS. I've successfully grabbed the itemID inside JS, but now I need to grab that table and those values while the game is running. How do I do this? Is it even possible with just JS and Lua? |
2 | Implementing Achievement System in Javascript I understand that for more complex achievements, specific code can't be avoided, but for simple ones like (player clicked 100 times) or (player earned 30 bajillion cookies) or (player played for 1 hour) it should be as simple as abstracting the achievements to something like a list of properties values and having some event handler. My problem is that since I'm using Javascript and there's no really clean way to do pointers, how am I supposed to create an achievement class that can be iterated through procedurally? Ideally I'd like something like this Achievement class function Achievement(name, property, value, text, points) this.name name this.property property this.value value this.text text And then I'd add an achievement like so achievements.push(new Achievement("Clicktastic", amp numClicks, 1000, "You clicked 1000 times!") And have some kind of function bound to a Window.setInterval that was constantly looping through all achievements and for these simple types doing something like for (var i 0 i lt achievements.length i ) if ( achievements i .property gt achievements i .value) deal with earning achievement I'm just using some C style pointer dereferencing notation here. Basic idea is that I'm not sure how to create a generic achievement that can arbitrarily care about specific properties without pointers. |
2 | Security concerns related to HTML 5 games I would like to know if people could modify an HTML 5 game's code to harm either the server or other players whom visit the page. More specifically, whether someone could modify a simple game that doesn't have things like high scores, global stats, log in, etc. to harm other users and or the server the game is hosted on. Is this only a concern for games that retrieve data to be stored on the server itself? |
2 | How to reduce the total time spent checking against my world bounds? I'm making a game engine and currently I use a function for checking a new position after movement to prevent game objects from escaping the world const boundary function (min, max) return Math.min( Math.max(this, min), max ) I've noticed that it consumes around 9 10 of my game loop (testing with 4500 objects). Is there a better way to handle this? Do I generally need to make my world finite? To clear this up, this is not an object object collision detection question. For that I have a grid, and this grid is based on the size of the world, which is why I check that objects don't escape the world size limits. |
2 | Implement Fast Inverse Square Root in Javascript? The Fast Inverse Square Root from Quake III seems to use a floating point trick. As I understand, floating point representation can have some different implementations. So is it possible to implement the Fast Inverse Square Root in Javascript? Would it return the same result? float Q rsqrt(float number) long i float x2, y const float threehalfs 1.5F x2 number 0.5F y number i ( long ) amp y i 0x5f3759df ( i gt gt 1 ) y ( float ) amp i y y ( threehalfs ( x2 y y ) ) return y |
2 | How to make a snake game where each snake tile follows it's connected tile I want to make a basic snake game. It has a head and a series of tails that occupy a tile in a grid. The first tail in the series is adjacent to the head. and each tail that comes after is adjacent to the previous tail. Head can move in four directions and the first tail moves to head's previous position, and each other tail moves to the previous position of the previous tail, as they follow each other. How can I model this as data, and update it for movement. I've tried this but that's a little doesn't work. p x 0, y 0, tails function init tail(dx,dy) return x 0, y 0, dx dx, dy dy end Initialization add(p.tails, init tail(0,1)) add(p.tails, init tail(0,1)) add(p.tails, init tail(0,1)) local last p for tail in all(p.tails) do local tx last.x tail.dx local ty last.y tail.dy tail.x tx tail.y ty last tail end Movement local last p for tail in all(p.tails) do tail.dx last.dx tail.dy last.dy local tx last.x last.dx tail.dx local ty last.y last.dy tail.dy tail.x tx tail.y ty last tail end This is what I have so far |
2 | How do I make sure everyone sees the same distance across different resolutions? Hello game dev community. I have recently got into making games in a browser window, and me and a friend ran into a common problem. Let's say I have a game like diep.io, where users can control their tank and move across a large grid. Each player can only see a certain distance, even if they moved the window to a larger monitor, like from 1080p to a 4K monitor. I've created a game in HTML5 canvas, but the problem is that it depends on the browser's window.innerWidth and innerHeight properties. I can tell that this is an issue, because if I drew a grid, one player on a 1080p monitor could only see x distance but a player on a 4K monitor with a larger width and height could see x 2 distance (or how much larger it actually is), meaning that the player on a 4K monitor has an advantage, by seeing players in a larger distance. How exactly could I tackle this problem? My friend has the same issue, and I hope this answers it. |
2 | Canvas tile grid, hover effects, single tilesheet, etc I'm currently in the process of building both the client and server side of an HTML5, canvas, and WebSocket game. This is what I have thus far for the client http jsfiddle.net dDmTf 20 Current obstacles The hover effect has no idea what to put back after the mouse leaves. Currently it's just drawing a "void" tile, but I can't figure out how to redraw a single tile without redrawing the whole map. How would I go about storing multiple layers within the map variable? I was considering just using a multi dimensional array for each layer (similar to what you see as the current array), and just iterating through it, but is that really an efficient way of doing it? Currently the "borders" encroach on one another. I'm not sure what I'm doing wrong? If you hover over and off of the bordering "tree" tiles, you'll notice how it removes part of the neighboring tiles border. This shouldn't need to happen. Outside of the map, what would be an elegant way of adding Players to the render scene? I've seen a few places that recommend you use multiple canvas's, would you recommend that since they'll probably be moving much more? In addition to that, how can I confine player movement to the grid, similar to how in the pokemon gameboy games, when you tap the left arrow, you always move one "space" that direction. It's not a halfway type deal. Camera. What would be a good way about adding a "camera" to the equation, so the viewport can pan around a larger map area? Obstacles. In the newer version of the map, you'll notice an empty obstacles array. Assuming players get added well, what do you think would be good for adding movement obstacles? Side note The tile sheet being used for the jsfiddle display is only for development. I'll be replacing it as things progress in the engine. If you guys have any pointers for my JavaScript, feel free. As I'm more or less learning advanced usage as I go, I'm sure I'm doing plenty of things wrong. Note I will continue to update this post as the engine improves, but updating the jsfiddle link and updating the obstacles list by striking things that have been solved, or adding additions. Edit Updated link from http jsfiddle.net dDmTf 7 to http jsfiddle.net dDmTf 17 this handles the "hover" problem, and it's been striked out. Edit Updated link from http jsfiddle.net dDmTf 17 to http jsfiddle.net dDmTf 19 fixes the out of bounds issue with the tiles Edit Updated link from http jsfiddle.net dDmTf 19 to http jsfiddle.net dDmTf 20 adds multiple layers to the equation |
2 | I can't clear the paint image in my Canvas I'm trying to make the Mario move, but somehow it leaves traces behind, can anybody help??? var canvas document.getElementById("screen") var ctx canvas.getContext("2d") var mario var marioSprite var tiles var speedX 1 marioSprite Specification mario target picture specification X amp Y, Width amp Height px 276, py 44, pwidth 16, pheight 16, drawing on Canvas specification X amp Y, Width amp Height cx 16, cy 116, cwidth 16, cheight 16, draw Mario in Canvas function drawMarioSprite() marioSprite new Image() marioSprite.src 'file C Users MASTONO ALI Desktop img characters.gif' marioSprite.addEventListener('load', e gt ctx.drawImage(marioSprite, mario.px, mario.py, mario.pwidth, mario.pheight, mario.cx, mario.cy, mario.cwidth, mario.cheight) ) this.position function() this.mario.cx speedX position() drawMarioSprite() end drawTiles and tilesLoop function drawTiles() tiles new Image() tiles.src 'file C Users MASTONO ALI Desktop img tiles.png' tiles.addEventListener('load', e gt tilesLoop() ) function tilesLoop() for (let x 0 x lt 25 x ) for (let y 11 y lt 13 y ) ctx.drawImage(tiles, 0, 0, 26, 26, x 12, y 12, 20, 20) drawTiles() end function draw() drawMarioSprite() drawTiles() window.requestAnimationFrame(draw) window.requestAnimationFrame(draw) thank you |
2 | How to stop an anmation and a loop in relation to a timer? Phaser javascript I am not ajavascript or phaser expert, I just got stuck with this problem. I'll try to explain it. In this game is a 21 second timer in all this which starts AFTER a beginning 3 second animatiton. var maxTime 21 in SECOND There is a wheel (station) that spins over and over (loops) and scales up and down var init station scale 0.5 var scale station 0.40 When the game resets the station (wheel) resets function resetGame() station.scale.setTo(init station scale) station(middle anchor point). station game.add.sprite(750,195,"station") station.anchor.setTo(.75,.75) station.scale.setTo(init station scale) station.animations.add("anim") Init animations station.animations.play("anim",15,true) play Animations "anim" with 30fps, loop true Not to confuse you, but there is a lot going on in this 21 seconds, such as hint (this is hooked up with the station (wheel) hint game.add.sprite(game.world.centerX 50,game.world.centerY 100,"hint") hint.anchor.setTo(0.5) hint.animations.add("anim") hint.animations.play("anim",15,true) hint.visible false Playing a 3 second animation that only plays once at the very beginning of the game (including if game resets) also starting .play ("anim",15, true) (above (station wheel) code and looping it) after that 3 second animation console.log("FINISH ANIMATION and ADD TIMER") TIMER is referring to the 21 second timer timerEvent game.time.events.add(Phaser.Timer.SECOND maxTime, moveToEndGame, this) (also the 21 second timer) function moveToEndGame() console.log("TIMER END") var twn game.add.tween(bg).to( alpha 0 ,tween speed,"Linear",true) twn.onComplete.addOnce(function() flagGameover true ,this) if(!flagGameover amp amp !star.visible amp amp idx bullet lt bullet array.length) initBullet() else if(flagGameover) console.log("GOTO GAMEOVER") window.location ".. EndGame.html" Everything works up until the end of the 21 second timer, but station wheel keeps spinning creating an 'infinite loop" So there is nothing to stop the 'loop in the station" after the 21 second timer finishes. Coder left out a line that would do that? Some line of code needs to be added to that last block of code (or somewhere else?)to stop the loop on the station timed with the end of the 21 second timer. I think???? Or some kind of javascript kill switch i.e. stop all javascript then go to endgame.html Anyone know the answer? |
2 | Collision detection not working in Phaser 3 I am new to phaser. So I started working on a game but I am stuck at implementing collision detection. I want to do it between a static group(dot) and a Sprite(obs). function create() dot this.physics.add.staticGroup(dotx, doty, 'dot') dot.create(dotx, doty, 'dot') obs this.physics.add.sprite(obsX, obsY, 'obs') this.physics.add.collider(obs, ball, alert, null, this) |
2 | How to get the address of a nearby square on a chess board? I'm making a chess game from scratch and I got stuck. So far I have all my figures placed, I have the positions set, I've already done the collision detection and everything. When I click the figure that is in position A1 for example, I want to make two green rectangles at positions A2 and A3, and they will be used to make the figure move. Is there a method for to add 1 to the string "A1" to form the string "A2" or something? Because thats all I really need right now. Also if there's a more clever way to make the positions please let me know. As an example, here is how I currently look up my display positions using the A1, A2 etc. location codes let positions A1 10, 710 ,B1 110, 710 ,C1 210, 710 ,D1 310, 710 ,E1 410, 710 ,F1 510, 710 ,G1 610, 710 ,H1 710, 710 , A2 10, 610 ,B2 110, 610 ,C2 210, 610 ,D2 310, 610 ,E2 410, 610 ,F2 510, 610 ,G2 610, 610 ,H2 710, 610 , A3 10, 510 ,B3 110, 510 ,C3 210, 510 ,D3 310, 510 ,E3 410, 510 ,F3 510, 510 ,G3 610, 510 ,H3 710, 510 , A4 10, 410 ,B4 110, 410 ,C4 210, 410 ,D4 310, 410 ,E4 410, 410 ,F4 510, 410 ,G4 610, 410 ,H4 710, 410 , A5 10, 310 ,B5 110, 310 ,C5 210, 310 ,D5 310, 310 ,E5 410, 310 ,F5 510, 310 ,G5 610, 310 ,H5 710, 310 , A6 10, 210 ,B6 110, 210 ,C6 210, 210 ,D6 310, 210 ,E6 410, 210 ,F6 510, 210 ,G6 610, 210 ,H6 710, 210 , A7 10, 110 ,B7 110, 110 ,C7 210, 110 ,D7 310, 110 ,E7 410, 110 ,F7 510, 110 ,G7 610, 110 ,H7 710, 110 , A8 10, 10 , B8 110, 10 , C8 210, 10 , D8 310, 10 , E8 410, 10 , F8 510, 10 , G8 610, 10 , H8 710, 10 , the 0 of the arrays is x and the 1 is y, and that's also how I placed the figures. |
2 | Is it a bad idea to store functions inside components in ECS? Say I have three entities Player, Spikes, and Zombie. All of them are just rectangles and they can collide with each other. All of them have the BoxCollision component. So, the BoxCollison system would look something like this function detectCollisions () for each entity with box collision check if they collide then do something The issue is, the sole purpose of the BoxCollision component is to detect collision, and that's it. Where should I put the game rules, such as quot if the Player collided with Spikes, diminish its health quot or quot if the Zombie collided with Spikes, instantly kill the Zombie quot ? I came up with the idea that each Entity should have its onCollision function. Programming languages such as Javascript and F have high order functions, so I can easily pass functions around. So when assembling my Player entity, I could do something like function onPlayerCollision (player) return function (entity) if (entity.tag 'Zombie') player.getComponent('Health').hp 1 else if (entity.tag 'Spikes') player.getComponent('Health').hp 5 const player new Entity() player.addComponent('Health', hp 100 ) player.addComponent('BoxCollision', onCollision onPlayerCollision(player) notice I store a reference to a function here, so now the BoxCollision component will execute this passing the entity the player has collided with function detectCollisions () for each entity with box collision check if they collide onCollision(entity) onPlayerCollision is a curried closure function that receives a player, and then returns a new function that wants another Entity. Are there any flaws with this? Is it okay for components to store references to functions? What are other ways of avoiding game rules in components? Events? Thanks! |
2 | What is better for the overall performance and feel of the game one setInterval performing all the work, or many of them doing individual tasks? This question is, I suppose, not limited to Javascript, but it is the language I use to create my game, so I'll use it as an example. For now, I have structured my HTML5 game like this var fps 60 var game new Game() setInterval(game.update, 1000 fps) And game.update looks like this this.update function() this.parseInput() this.logic() this.physics() this.draw() This seems a bit inefficient, maybe I don't need to do all of those things at once. An obvious alternative would be to have more intervals performing individual tasks, but is it worth it? var fps 60 var game new Game() setInterval(game.draw, 1000 fps) setInterval(game.physics, 1000 a) where "a" is some constant, performing the same function as "fps" ... With which approach should I go and why? Is there a better alternative? Also, in case the second approach is the best, how frequently should I perform the tasks? |
2 | Game AI move towards player while avoiding an obstacle I'm trying to move enemy towards player, while enemy also tries to avoid an obstacle if it's in its path. Here's a simple illustration of what I want to do What I've tried Making circular collision around the obstacle. It works but that makes the enemy impossible to hit. I think going with an A pathfinding algorithm might be a bit overkill especially since it's designed for multiple obstacles, where in my case there is only the mouse and wall collision concerned. Moving the enemy towards the player, while also moving away from the obstacle at a slower speed. This works better because you can actually hit the enemy, but also slows down enemy if obstacle if it's in its path. My questions Is there a better way to go about doing this? Anything you would've done differently with my code to either improve or optimize? Here's the code I have currently in my game logic and a fully working example on jsFiddle. Calculate vector between player and target var toPlayerX playerPosX enemyPosX var toPlayerY playerPosY enemyPosY Calculate vector between mouse and target var toMouseX mousePosX enemyPosX var toMouseY mousePosY enemyPosY Calculate distance between player and enemy, mouse and enemy var toPlayerLength Math.sqrt(toPlayerX toPlayerX toPlayerY toPlayerY) var toMouseLength Math.sqrt(toMouseX toMouseX toMouseY toMouseY) Normalize vector player toPlayerX toPlayerX toPlayerLength toPlayerY toPlayerY toPlayerLength Normalize vector mouse toMouseX toMouseX toMouseLength toMouseY toMouseY toMouseLength Move enemy torwards player enemyPosX toPlayerX speed enemyPosY toPlayerY speed Move enemy away from obstacle (a bit slower than towards player) enemyPosX toMouseX (speed 0.4) enemyPosY toMouseY (speed 0.4) |
2 | 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 | Error with Cocos2d JS when using Skeletal animation from Cocos Studio Here is the JavaScript code var size cc.winSize ccs.ArmatureDataManager.getInstance().addArmatureFileInfo(res.skeleton) The error comes from the following line var armature ccs.Armature.create("Skeleton") armature.getAnimation().play("hit") armature.x size.width 2 armature.y size.height 2 this.addChild(armature) And at runtime I get this error Assert failed AnimationData not exist! I know that error is from the specified line, but I'm very confused as to how I can solve it. I have tried many different methods, but unfortunately those didn't work. In the resources, I load all the image files and JSON files which made by Cocos Studio, and the file path and name are correct. What could be causing this error? |
2 | Particles to Denote Movement in Space I'm currently working on a WebGL project to realise an idea I've had for some years. On my desk is book on making a space sim written 15 years ago. There I found some algorithm for particles in space. The idea is simple A cloud of particles that stay in place so they fly past the player, but reset to be in front of the player when they move past the ship. This shows the player they're moving while there's nothing else around. For this, I reworked the algorithm found in the book a little ParticleField.prototype.updateCloud function(frustum, position, direction) var s this.size, s2 s 2 for (var i 0 i lt this.vertices.length i ) if (!frustum.containsPoint(this.vertices i )) this.vertices i .set( (position.x s Math.floor(Math.random() s2)) (s direction.x), (position.y s Math.floor(Math.random() s2)) (s direction.y), (position.z s Math.floor(Math.random() s2)) ((s Math.floor(Math.random() s2)) direction.z) ) Where s is the size of cloud. I played around with the sizes, but this simple function has several weaknesses. The particles 'pop up' in front of the player when they're moving. If the player backs up and moves backwards, the particles won't reset, leaving the cloud visible popping the illusion. Particles appear to be flying through the player. Without regard of how the particles look (they're simple points right now), how can I make this look more natural? I've seen the effect in games like Elite Dangerous and Freelancer, and I'd like to be closer to them, and I'd appreciate any hint on the topic. |
2 | Are javascript MVC model implementations too slow for games? I wanted to implement a game in javascript with an MVC design pattern, with each entity's state stored in a model. So for example, In an update loop we iterate over all models and apply the velocity attribute to the position attribute of the model. A view associated with each entity model would then receive a position changed event, and update the representation of the entity. This would happen independently of the views render method being called in a requestAnimationFrame callback. What I found though, through a possibly naive implementation, is that setting attributes of a model is simply too slow. As much as I prefer the architecture of this code, the framerate was significantly lower. Should I give up on using MVC for frequently updated attributes like position? Below, I've included some code to test aspects of setting attributes of an object. The most minimal model like behaviour, in which an attribute is set only when the new value differs from the current, and a quot changed quot update event is triggered, is about 10x slower than just setting attributes directly. Output gt test(1000, 100, 10) object key 163 ms object key if changed 172 ms object key if changed amp emit backbone event 953 ms Backbone.Model 4043 ms eventsBackboneCount 100000 var test function(creations, iterations, keyCount) var eventsBackbone .extend( , Backbone.Events) var eventsBackboneCount 0 eventsBackbone.on('all', function() eventsBackboneCount eventsBackboneCount 1 ) var looper function(label, create, set) var start (new Date()).getTime() var data for(var i 0 i lt creations i ) data i create(i) for(var j 0 j lt iterations j ) for(var i 0 i lt creations i ) var key '' (j keyCount) set(data i , key, Math.random()) var end (new Date()).getTime() console.log('' label ' ' (end start) ' ms') return data looper( 'object key ', function(id) return , function(datum, key, value) datum key value ) looper( 'object key if changed', function(id) return , function(datum, key, value) if(datum key ! value) datum key value ) looper( 'object key if changed amp emit backbone event', function(id) return id id , function(datum, key, value) if(datum key ! value) datum key value eventsBackbone.trigger('changed ' datum.id, datum, key) ) looper( 'Backbone.Model', function(id) return new Backbone.Model( ) , function(datum, key, value) datum.set(key, value) ) console.log('eventsBackboneCount ' eventsBackboneCount) |
2 | Using copyrighted sprites Possible Duplicate How closely can a game resemble another game without legal problems I was thinking about making a pacman clone, I know there is a similar question here Using Copyrighted Images , but I know i can't use the original art from the game because it belongs to Namco, so if I design a character that has the shape of the slice circle it will look exactly like pacman, maybe if I use green instead of yellow? Also if the game plays like the original pacman, it is wrong? I just want to make the game as a personal project and and publish it in my site without getting in trouble |
2 | Calling function every n second javascript game I making a game and I want to call a function that runs every random second to spawn something every time. I've seen some posts that said to use the setInterval() function to keep track of the time but I don't know where to implement it because I'm using the requestAnimationFrame() to loop the game. I also tried to implement it in the update function of the classes but it doesn't seem to work. This is my main with the loop import Game from ' src game.js' let canvas document.getElementById('main') let ctx canvas.getContext('2d') const WIDTH SCREEN 800 const HEIGTH SCREEN 600 let game new Game(WIDTH SCREEN, HEIGTH SCREEN) game.start() function loop() ctx.clearRect(0, 0, WIDTH SCREEN, HEIGTH SCREEN) game.update(ctx) requestAnimationFrame(loop) window.addEventListener( quot keydown quot , (event) gt game.controller.keyListener(event)) window.addEventListener( quot keyup quot , (event) gt game.controller.keyListener(event)) requestAnimationFrame(loop) |
2 | Quaternions how to limit axis? Is there any possibility to limit quaternions to move only in x amp y axis (like in Eulers yaw and pitch, without rolling)? I's there any equation or something similar to do this? Some example Movement should behave like this http 360.art.pl experimental 1 But when I build my player on quaternions it have no limits and I don't know how to fix it http 360.art.pl experimental 2 |
2 | Separate shaders from HTML file in WebGL I'm ramping up on WebGL and was wondering what is the best way to specify my vertex and fragment shaders. Looking at some tutorials, the shaders are embedded directly in the HTML. (And referenced via an ID.) For example lt script id "shader 1 fs" type "x shader x fragment" gt precision highp float void main(void) ... lt script gt lt script id "shader 1 vs" type "x shader x vertex" gt attribute vec3 aVertexPosition uniform mat4 uMVMatrix ... My question is, is it possible to have my shaders referenced in a separate file? (Ideally as plain text.) I presume this is straight forward in JavaScript. Is there essentially a way to do this var shaderText LoadRemoteFileOnSever(' shaders shader 1.txt') |
2 | How to play multiple sounds at once without reloading data? I am making an HTML5 game, which involves one audio being played multiple times at once. I searched this issue up and found this https stackoverflow.com questions 25654558 html5 js play same sound multiple times at the same time It seemed to help, except later a question came up If I do cloneNode(), will it copy the sound AND the currently loaded audio data, or will it have to reload the data? Is there a better way to play multiple sounds while making sure no data needs to be reloaded? |
2 | Saving data in the local computer with cocos2d js Making a game with cocos2d js, is there a reliable way to create saved data in my local computer? I see that there is cc.sys.localStorage but it is removed if the user clears the browser's cache or when they simply use another browser. |
2 | How can I ensure reasonably spaced out enemies I have a simple javascript game and I'm initializing their positions on the y axis using random numbers. How can I ensure that they are reasonably spaced apart? My simple algorithm is y (Math.random() 1000 600) However I frequently get enemies almost directly on top of each other. This is a huge problem for the game, since it's a word game and the enemies have text on their center, that if overlapped makes them impossible to kill since you can't see the words. Any advice would be appreciated! I'm pretty new to making games in general so this has all been a learning experience for me! |
2 | How to disable touch in Quintus? I'm trying to build card game using the Quintus game engine. I have objects called Card. I can touch and drag it in the screen but I want just to touch and drag it one time but I can't figure out how to disable the touch after I dragged the card and I try to Google it but no luck. My code Q.Sprite.extend("Card", init function(p) this. super(p, asset "Queen OF Hearts.png", x Q.el.width 2, y Q.el.height 120 ) this.on("drag") this.on("touchEnd") , drag function(touch) this.p.dragging true this.p.x touch.origX touch.dx this.p.y touch.origY touch.dy , touchEnd function(touch) this.p.dragging false put a line on the screen if the card pass it put the card in the new position if not put the card in the orginal(old) postion if(touch.origY touch.dy gt Q.el.height 200) define the line that the card should pass if the amount of draged gt the screen line in Q.el.height 200 put the card in the same old postion if is not pass the line this.p.x touch.origX this.p.y touch.origY else put the card if it pass the line in the new postion this.p.x Q.el.width 2 this.p.y Q.el.height 280 ) so in the else statement in the touchEnd I'm trying to do some thing like that this.p.touch false but is not working. |
2 | Resizing the map in HTML5 canvas Say I have a big map for my HTML5 game. And it is drawn with an image repeatedly. I want my map to be able to resize and respond to player's behaviors. Now I can resize my map, I just multiply a scale to my maps coordinates (map.x and map.y) and the pattern image will become smaller. However I have two problems that I don't know how to resolve. Let's see what I have got so far. My Sprite class use paintX and paintY to represent the drawing position. And they are defined as followed get paintX() return map.scale this.x frame.x get paintY() return map.scale this.y frame.y where frame is the view that follows my player when my player moves. In my game my player stays at the middle of the screen and the screen will move with my player. So when the map resizes the player's position will also change but it will stay in the middle of the screen. In Frame class its x and y coordinates will change when the scale is updated. init(config) const self this this. x config.x this. y config.y map.on('scale changed', () gt self. x map.scale self. x self. y map.scale self. y ) get x() return this. x set x(val) this. x val get y() return this. y set y(val) this. y val The Problems 1 I have thousands of sprites on the map. After resizing the map some sprites still stay in the same location but they are supposed to render at a scaled location. ( I use very large scale change to test so the change is like 0.2 to 0.3 just to see the result more clearly) 2 If I use very small scale change number such as 0.01 I can still see the change but I can also see some hiccups refreshing the map, then it renders OK again, but overtime it becomes messy and presents problem 1. Without scaling none of these problems exists. I am scratching my head to find a solution for this resizing problem. Is there a standard and not so complicated solution for this map resizing problem? |
2 | Questions for QueryAABB I'm currently having trouble getting my head around QueryAABB, and hope to find some answers here. The LowerBound of an AABB the upper left corner (and vice versa). Why is that and what idea is behind that? When exactly does an object count as inside the AABB and is therefor found by a query? |
2 | Implementing an efficient method of server side checking I'm making a web based action RPG game. I don't want players to cheat, but I also don't want the game to constantly pause to wait for the server to respond. I made it so the game is played on the client side (for responsiveness) and the server does routine checking to validate the game state. But the system is very cumbersome. The server has to calculate every single frame and compare the entire game state to the game state sent from the client. If anything in the game states are different form each other, the server kicks the player off. However, this means the game has to send 30 requests a second, and the server must calculate it all in time. If many people are playing the game, I don't think my one free Heroku dyno can handle that. How do I implement an efficient and elegant way of validating players' moves on the server side? |
2 | mat3x4 in webGL shaders I am porting the IQM bone animation format to Javascript and have run into a problem... The vertex shader is failing to compile and the only error message I get out is 'mat3x4' syntax error on the first occurance of mat3x4 in the file. Its the very data type name itself that is unsupported, it seems. This happens on all machines I have access to for testing, which have a variety of Intel and ATI cards and run Linux with Firefox. (Chrome is not available.) If I change all mat3x4 to, say, mat3 then my shader compiles fine. does webGL support mat3x4? (I can find nothing via Google) how can I work around this? How can I package the bones into mat4, for example, and keep the code working correctly? |
2 | Changing balls direction in Pong I'm making a Pong game to get started with game developement but I've run into a problem that i can't figure out. When trying to change the balls direction it doesn't change. This is the relevant code function moveBall() this.speed 2.5 this.direction 2 if(this.direction 1) ball.X this.speed else if(this.direction 2) ball.X this.speed function collision() if(ball.X 500) moveBall.direction 2 if(ball.X 300) moveBall.direction 1 Why doesn't it work? I've tried many different ways, and none of them seem to work. The moveBall.direction changes though, since it alerts the new direction once it reaches the defined ball.X position. If someone could help me I would deeply appreciate it. I've included a JSFiddle link. http jsfiddle.net hustlerinc y4wp3 |
2 | Equalling the rotation of an image with its object. Box2dweb I have some hard time making the rotation of an image equal to the rotation object that the image belongs to. Simply put it, I don't know how to do it properly but i am not asking for a how to guide but for some tips hint and or infos that i am not aware of... I was able to align perfectly the image with the object, and so if the object moves in a linear fashion the image is at all times on top of the object and everything is smooth and perfect. But how is it possible to make the rotation of the image be the same as of the object it belongs to. No matter what i tried it is always somewhat off or the rotation of the image behaves weird when in the end the object stops rotating. I tried using using GetAngle(), GetAngularVelocity(), combinations of both, but never succeeded. function Draw and Rotate() for (b world.GetBodyList() b b b.GetNext()) var angle ((b.GetAngle() 180) (Math.PI)) SCALE var angle vel ((b.GetAngularVelocity() 180) (Math.PI)) SCALE var pos b.GetPosition() console.log((angle)) if (b.GetUserData() "bo img") ctx.save() save the ctx state prior changing it.This method pushes the current state onto the stack. ctx.translate(pos.x SCALE , pos.y SCALE ) ctx.rotate(angle) ctx.drawImage(box img, (box img.width 2), (box img.height 2)) ctx.restore() restoring ctx state.This method pops the TOP state on the stack, restoring the context to that state. this is the part that deals only with one body and its image. If someone needs some more clarification please ask.... |
2 | How to Prevent Entities Snapping Through Platforms I am using crafty.js to make a platformer. I assigned the main player entity the default jumping controls and movement with .twoway() and used .checkHits() against the obstacles ("obs") the player will jump on. The problem is that when the player jumps, if the top of the player entity hits the bottom of the obstacle, the player entity "snaps" to the top. How do I make it so that this movement does not happen? The intended effect is that the player entity will only land on the obstacle if the player entity lands on the top. Here is the code window.onload function() Crafty.init(600, 400) Crafty.background(' 07A6FF') obstacle platform entities 'obs' means obstacle var obs Crafty.e('obs, 2D, DOM, Collision, Color') .attr( x 100, y 250, w 400, h 45 ) .color(' E88D0C') var obs2 Crafty.e('obs, 2D, DOM, Collision, Color') .attr( x 200, y 150, w 45, h 45 ) .color(' E88D0C') player entity var player Crafty.e('player, 2D, DOM, Color, Collision, Twoway, Gravity, Jumper') .attr( x 50, y 50, w 60, h 40 ) .color(' 0035AB') .twoway(200, 150) .checkHits('obs') .gravityConst(200) .gravity('obs') lt script src "https github.com craftyjs Crafty releases download 0.7.1 crafty.js" gt lt script gt |
2 | How can I scale zoom to a point in canvas in the game? I am using html5 canvas to build a MMO game. When I scale my background by default it scales to (0, 0) which is the top left corner of the background. If I have other sprites on the screen they all will look like they are shifting to the bottom right a little bit. Suppose my sprite(player) is at (x,y) of the map and it is placed center on the canvas.How can I make the background scale or zoom to (x,y) instead of (0,0)? Its world position is (x,y) but its screen position is always (canvas.width 2, canvas.height 2). I think in this way the sprites around my player wouldn't shift their position to unexpected places. But I don't know how to do this. |
2 | How can I repeat only a portion of an image in Javascript? So I'm trying to repeat a portion of my spritesheet as a background. So far, I have attempted this var canvas (" board") 0 , ctx canvas.getContext("2d"), sprite new Image() sprite.src "spritesheet.png" sprite.onload function() ctx.fillStyle ctx.createPattern(spriteBg, "repeat") ctx.fillRect(0, 25, 500, 500) As you can see, it repeat the whole image, not just a part of it, and I just can't figure out how to do that last part. |
2 | HTML5 Jump and Run Game Performance issues we're developing a HTML5 Javascript jump and run game and therefore we have developed our own gameframework. It consists of following most important structures Stage Scene Layer divs ObjectEntites Rectangle Sprite canvas In the gameloop things get moved by calculating an offset value e.g. if we place a coin and this coin moves through the screen, it gets a new offset in each gameloop call. The dirty area of the coin is cleared in the canvas and the coin is repainted. We pay attention that we just draw at int values (no floating point). Unfortunately we have some performance issues now and can't figure out why our macbook pro's are running hot while playing the game. Are the drawing operations so crucial? We have layered Canvas, so just moving stuff gets repainted and even not the whole canvas but just dirty areas get cleared. IStat shows following values while playing the game Memory module A1 and Heatsink B get up to 60 and the rpm Value of the Fans increases up to 3000 4000. In firefox we see these values And chrome shows us this, where we also see how cpu increases Do you have any idea how to check performance of our game, how to find bottlenecks or general tips? We have searched for canvas performance, used firebug profiler... We'd be grateful for any advice! |
2 | How can I clear explosions in my function? Hi I have a function to place bombs, and a for loop that places explosions on the tiles where possible. My problem is that I can't remove the explosions after a while. I've tried everything I can come up with so now I turn here as a last resort. The function looks like this function Bomb() var placebomb false if(placeBomb amp amp player.bombs ! 0) map player.Y player.X .object 2 var bombX player.X var bombY player.Y placeBomb false player.bombs setTimeout(explode, 3000) function explode() var explodeNorth true var explodeEast true var explodeSouth true var explodeWest true map bombY bombX .explosion 1 delete map bombY bombX .object for(i 0 i lt player.bombRadius i ) if(explodeNorth amp amp map bombY i bombX ) if(!map bombY i bombX .wall) if(!map bombY i bombX .object) map bombY i bombX .explosion 1 else var explodeNorth false delete map bombY i bombX .object map bombY i bombX .explosion 1 else var explodeNorth false if(explodeEast amp amp map bombY bombX i ) if(!map bombY bombX i .wall) if(!map bombY bombX i .object) map bombY bombX i .explosion 1 else var explodeEast false delete map bombY bombX i .object map bombY bombX i .explosion 1 else var explodeEast false if(explodeSouth amp amp map bombY i bombX ) if(!map bombY i bombX .wall) if(!map bombY i bombX .object) map bombY i bombX .explosion 1 else var explodeSouth false delete map bombY i bombX .object map bombY i bombX .explosion 1 else var explodeSouth false if(explodeWest amp amp map bombY bombX i ) if(!map bombY bombX i .wall) if(!map bombY bombX i .object) map bombY bombX i .explosion 1 else var explodeWest false delete map bombY bombX i .object map bombY bombX i .explosion 1 else var explodeWest false player.bombs If anyone can think of a good way to remove the explosion after a delay please help. |
2 | How do I implement side scrolling in a javascript platformer? I'm building a side scrolling platformer with Javascript and the canvas element for a school project. I have the character all sorted out. He runs left and right, and has a different sprite set for standing still. The game has gravity, and I can jump. Now what I can't get my head around is how to implement side scrolling. The game world will be tile based. Each tile will be 20x20 pixels. When the character gets to the edge of the screen, it should scroll with the character to explore the level further. Can anyone point me in the right direction to a resource that explains how to programmatically do this? Language specific to Javascript would be good, but anything would be a help. |
2 | Structure game database to store player info and items Recently I started developing my tiny html5 multiplayer game made in Node.js, Express.js, MongoDB(Mongoose), Socket.io and using Phaser.js. I am quite new to these frameworks and especially new to database structuring management. My struggle comes when I think about how can I structure the database to store things as player username, password and general preferences (basic user info) and then things as player equipment such as items and currency. I can figure out how to do the code part but what I do not know how to handle is the process I should follow. I thought of the structure like so Users Document " id" "randId", "username" "ArthurConan", "password" "aquamarine12345", "credits" 20, "equipment" "name" "Sword of the Forsaken", "equiped" true, "slot" "weapon", "id" "itemId", , "name" "Meteor Katana", "equiped" false, "id" "itemId" Items Document " id" "itemId", "name" "Sword of the Forsaken", "atk" 1400, "value" 500 , " id" "itemId", "name" "Meteor Katana", "atk" 200, "value" 50 As I am using MongoDB the structure would be more or less similar to that. With the code above then I would do the following Player Registers and his basic info(username, password, ...) is added to the database and he will also get one weapon to start with. Player adventures into my world and gathers credits and equipment. Those items are stored in his inventory. Player can equip use sell destroy upgrade some of those items. Upgraded items will have its stats upgraded based on preset stats. As a side note I would like you to know I am not the best at explaining myself, I hope you understand what I am trying to achieve. Also any suggestions are appreciated, have a good day ) |
2 | How To Animate A JavaScript Function I've been making this game where one of the characters, The Bandit, runs away from you mistaking you for a zombie. However, I can't seem to be able to animate the bandit. Is there a way I could use this w3schools example and make it fit with this canvas function? The code for bandit is here or the second site function drawBanditFacingDown() His face ctx.fillStyle " FFDE7A" ctx.fillRect(banditX, banditY, 25, 25) His left eye (your left not his) ctx.fillStyle "black" ctx.fillRect(banditX 5, banditY 5, 5, 8) His right eye (again your right) ctx.fillRect(banditX 15, banditY 5, 5, 8) His bandit thing on his mouth? I don't know what it's called ctx.fillStyle "red" ctx.fillRect(banditX, banditY 15, 25, 10) His shirt ctx.fillStyle "black" ctx.fillRect(banditX 5, banditY 25, 16, 25) His arms His right arm (YOUR RIGHT!!!!) ctx.fillStyle " FFDE7A" ctx.fillRect(banditX 21, banditY 25, 8, 20) His left arm (On your left side) ctx.fillRect(banditX 3, banditY 25, 8, 20) His pants His right pant leg (ur right) ctx.fillStyle " 11226B" ctx.fillRect(banditX 12, banditY 49, 8, 20) his left pant leg ctx.fillRect(banditX 5, banditY 49, 8, 20) ctx.fillStyle "black" ctx.fillRect(banditX 11, banditY 53, 3, 15) his shoes 200 LINES!!!!!! ctx.fillStyle "black" ctx.fillRect(banditX 5, banditY 68, 15, 5) |
2 | using delta timing is causing shake I am using delta timing to account for potential drop in frame rate. Only trouble being when I do this, I can notice an ever so slight wobble. I checked out the following JSFiddle coming from a tutorial on the subject and I can even see the wobble there, specifically on the 30fps example. http jsfiddle.net straker bLBjn my code is var delta now 0, last 0, difference 0, time 1000 60 var d function(val) return val delta.time delta.difference Then further down at the game loop delta.last Date.now() animate() function animate() delta.now Date.now() delta.difference delta.now delta.last delta.last delta.now update a sprite platform.x d(10) requestAnimationFrame( animate ) How can I keep the animation smooth? |
2 | Online board game engines I would like to create an online implementation of a board game. What engines could I use to write the game and make it easily accessible to as many people as possible? I would like it to be as widely accessible as possible, so it would be best if the user interface would run in a browser, not in a separately downloaded app. Likewise, it should be cross platform, not limited to a single platform pure JavaScript HTML would be best, as that would allow it to be usable on the iPad as well, though Flash or Java may be acceptable. Silverlight doesn't have the market penetration (I don't have it installed, for instance) and XNA is far too limited. Other features that would be nice would be good chat and social features (or integration with other chat or social network systems), leaderderboard or tournament systems, and easy integration of bots to provide AI opponents in case there aren't enough human players around. Game timers, to keep people moving at a reasonable rate, would also be good. Saving game records, and allowing people to replay and review records for study, would be nice too, though I'm not expecting much as those types of features tend to only show up in purpose built engines for games like chess or Go. Being free open source software would be a big plus, so I could extend it myself, though closed or hosted solutions might be acceptable if they provide enough of the above features or provide some means for extending them. Are there any such systems that meet my needs? Or any that are close even if not exactly matching? Some similar systems, that don't quite meet my needs, would include Yahoo Games, which is web based, but I can't write my own games for it (or any of many similar servers in that category). Volity, which is built on SVG and XMPP. It's open source, designed to be an open standard, has support for bots, etc, but it requires a separate client download, and seems not to be actively developed or used any more. SuperDuperGames, which is an open source, online system for doing turn based (play by mail style) games. That is, it's not live or real time, but instead you submit your moves, and wait for someone to submit theirs, within the next day or so. It's an active community, but I want something where I can play games live, not over the course of weeks or months. |
2 | Approaches for storing grid like information I am drawing this simple grid on my NodeJS server var grid for(var x 0 x lt 20 x ) grid x for(var y 0 y lt 20 y ) grid x y 0 console.log(grid) The outcome looks like this I know, pretty right?! 0 is supposed to indicate FREE, thus if a player requests to move to a field with 0, he will! The problems come when I want to add more then just Free Occupied, for instance I would like to give each Array Element an ID number for the Client Updates, or certain features on the field to be stored. I tried to assign something N, something2 N But thought it looked rather performance expensive in the long run. (On a big Grid) I read about using a single Object for several elements, but I cannot find this any more.. Should I perhaps use an Array of Objects, or an Additional Array inside each X,Y element? Any performance convenience anything goes tips are welcome D Edit Thank you for the ideas so far, I was now thinking to perhaps using Strings. Storing Variable A "," Variable B and then later using the .split to use the information. Any thoughts on this? |
2 | Timers and performance for mobile JS I'm using the Three.js JavaScript library to do some things in WebGL, and I wonder how the graphic aspects of timers are done on mobile. I was creating numbers with geometries and just replacing them when needed. This was fine on desktop (or so I think, lol). Recently, I've been playing around with mobile and the previous method is far too slow. |
2 | Drawing adding shape objects with the mouse on html canvas I've started with the canvas paint tutorial from link which worked fine with a few problems that can be fixed later. I've been checking a lot of posts on drawing shapes on the canvas but they all use draw functions in a gameloop or intervals but I do not want to use draw() in an interval or gameloop for now, I just need to update the content on userinput. I am trying to create a drawing software that paints objects instead of just bitmaps. I've been debugging for a while now and can't find the problem I have problems accessing the objects in the pointsArr array. I was only able to add rectangles to the screen by using contextVar.strokeRect(50,50,50,50) directly with the mouseDownVarso far. Yes I know that the addFilledCircleFunc creats rectangles, for now I just want everything to work properly. to do add gameloop and draw with gameloop? stroke line in resize fix collission check detection objects functions to draw detection objects implement resize? Varibale declration var canvasVar document.getElementById('canvasHtmlElement') var contextVar canvasVar.getContext('2d') var pointRadiusVar 10 var mouseButtonHeld false var pointsArrPosition 0 Arrays var pointsArr Varibale declration end canvas setup canvasVar.width window.innerWidth canvasVar.height window.innerHeight canvas setup end resize fix window.onresize function() var tempImageVar contextVar.getImageData(0,0, canvasVar.width, canvasVar.height) canvasVar.width window.innerWidth canvasVar.height window.innerHeight contextVar.putImageData(tempImageVar, 0,0) resize fix end contextVar.lineWidth pointRadiusVar 2 Line Width functions Objects function pointObject () this.x 0 this.y 0 this.w 10 default width and height? this.h 10 this.fill ' 444444' this.stroke stroke "skyblue" this.strokewidth strokewidth 2 function addFilledCircleFunc(x, y, w, h, fill) var filledCircle new pointObject filledCircle.x x filledCircle.y y filledCircle.w w filledCircle.h h filledCircle.fill fill pointsArr.push(filledCircle) Objects end create circle on mouse clicked point while mousebutton is held var addPointToCanvasVar function (e) if(mouseButtonHeld) addFilledCircleFunc(e.clientX, e.clientY, 10, 10, ' 444444') old drawing code contextVar.lineTo(e.clientX, e.clientY) contextVar.stroke() contextVar.beginPath() contextVar.arc(e.clientX, e.clientY, pointRadiusVar, 0, Math.PI 2) contextVar.fill() contextVar.beginPath() contextVar.moveTo(e.clientX, e.clientY) MAKE SURE that lines work when drawn over the edge of the canvas function clearPathIfMouseCursorLeavesCanvasFunc(e) contextVar.beginPath() clears the path so buttonpresses dont connect the line mouseButtonHeld false end mouse Up Down Switch var mouseDownVar function(e) alert("mouseDown") contextVar.strokeRect(e.clientX, e.clientY,50,50) draw() mouseButtonHeld true addPointToCanvasVar(e) add point on first click, not just when mousebutton is held var mouseUpVar function() alert("mouseUp") mouseButtonHeld false contextVar.beginPath() clears the path so buttonpresses dont connect the line mouse Up Down Switch end functions end listeners canvasVar.addEventListener('mousemove', addPointToCanvasVar) canvasVar.addEventListener('mouseup', mouseUpVar) canvasVar.addEventListener('mousedown', mouseDownVar) canvasVar.addEventListener ('mouseout', clearPathIfMouseCursorLeavesCanvasFunc) listeners end draw function function draw() alert('drawing') contextVar.strokeRect(pointsArr pointsArrPosition .x,pointsArr pointsArrPosition .y,pointsArr pointsArrPosition .w,pointsArr pointsArrPosition .h) pointsArrPosition draw function end |
2 | Mouse position to grid position not working I have a function which converts my mouse position to grid position in the game but it is not working properly... its slightly off. I have two functions one which converts from grid to screen position (this particular one, works fine) and the code is function mapToScreen(gridX,gridY,screen) var grid 64 var x (gridX gridY) (grid 2) x screen.offsetX camera scroll offset X axis x grid 2 centre of the iso tile on X axis var y (gridX gridY) (grid 4) y screen.offsetY camera scroll offset Y axis y grid 4 centre of the iso tile on Y axis return x,y So my function to do the opposite looks like this function screenToMap(pixelX,pixelY,screen) var grid 64 pixelX screen.offsetX pixelX grid 2 pixelY screen.offsetY pixelY grid 4 var gridX Math.floor((pixelX (grid 2) pixelY (grid 4)) 2) var gridY Math.floor((pixelY (grid 4) (pixelX (grid 2))) 2) return gridX, gridY The problem is as shown below in the image, it doesn't return the correct number. The first corner tile should be 0,0 . Also notice the co ordinate doesn't change correctly with the tile border. I don't know how to solve that either. |
2 | How can I detect mouse events on sprites in a canvas? I'm making an HTML 5 game. I want mouse clicks on sprites drawn in a canvas element cause events that my code can react to. At the moment, I'm doing it by checking through all of my sprites in a for loop on each click. Is there a way to do that by adding an event listener to a sprite so it would respond just like that? Are Javascript's custom events useful in this situation? I know it's possible with KinectJS, but I don't have any experience with it and really I'd like to learn how to do this myself without the help of a library. |
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 | 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 | Loading chunks of the terrain relative to the player's position I'm making a small voxel based multiplayer WebGL game with a Node.JS server which handles player positions and sends terrain chunk data to the clients. This is an example of how I'm currently sending the chunks var viewDistance 6 for (var x playerPosX viewDistance x lt playerPosX viewDistance x ) for (var z playerPosZ viewDistance z lt playerPosZ viewDistance z ) for (var y playerPosY viewDistance y lt playerPosY viewDistance y ) client.send( getChunk(x, y, z) ) This simply loads and sends the chunks within the view distance, however I'm looking for a way to prioritize sending the chunks nearest to the player first. Obviously it's no good loading chunks that are far away before loading the one the player is standing on. Assuming playerPosX, playerPosZ and playerPosY store the positions of the player and client.send( getChunk(x, y, z) ) will send the chunk, does any one have any ideas how I would do this? Thanks. |
2 | How can I fix sprite vibrating randomly which is moving towards the mouse while using camera.position set to the sprite as the center? So, when I use camera.position.x player.x camera.position.y player.y to set the center of camera to my sprite, the code doesn't work as intended to. It's slightly hard to explain so i made this video(https youtu.be afCamx wB 4) in which I show how it should work and the difference problem when using camera.position The code related to this is function setup() createCanvas(displayWidth,displayHeight) level new Level player createSprite(100,100,10,10) edge createEdgeSprites() player.speed 5 function draw() background(255) level.play() player.rotation Math.atan2(mouseY player.y, mouseX player.x) 180 PI drawSprites() player.collide(edge) this part is from level.play() var run mouseX player.x var rise mouseY player.y var length sqrt((rise rise) (run run)) var unitX run length var unitY rise length player.x unitX player.speed player.y unitY player.speed Also if you notice, when using camera.position, the vibration happens at specific distance of the sprite from the mouse, and the patter is that the distance is 0 right at the center of the canvas and keeps increasing as you move away from the center. |
2 | Limit rotation to certain angles for transform.rotate I'm working on a small project to learn Blender and Unity, and one issue I recently came across is that while I can have the turret of my tank rotate on the z axis based on mouse movements, I can't for the life of me figure out how to lock it to certain angles. My current approach was to use Mathf.Clamp to limit the range of values that I could pass to the rotate function, but that doesn't seem to have done anything at all, even though when outputting the value Clamp produces, I can tell it doesn't go over my specification. The code I have enum RotationAxes MouseX, MouseY, MouseXandY var axes RotationAxes private var MouseX RotationAxes.MouseX var sensitivityX float 15F var minimumZ float 35 var maximumZ float 35 function Update () if (axes MouseX) yRotation Input.GetAxis("Mouse X") transform.eulerAngles Vector3(0, 0, yRotation) transform.Rotate(0, 0, Mathf.Clamp (Input.GetAxis("Mouse X") sensitivityX, 30, 30)) function Start () |
2 | How to access files in Chrome So, I am making a game like html file that needs to load a few assets. I have a loading animation which uses the timing of the loading files to create a progress bar. This all goes fine. The files all load, and the app launches. However, none of the files can access each other as they are all in different script tags. And I cannot merge them because the JS is never actually put into the html. So what I need to do is to access the local file system (it uses the file prototype) and read the file, then stick the text into a script tag. However, all of the examples I have found on the web throw this error Xhtmlrequests can only access (list of protocols not including file) What I need is a JS way to access the files with no input from the user (other than opening the application). How can this be done? |
2 | How to handle transparent pixels in a spritesheet I am trying to correctly handle transparent pixels. I have a spritesheet that gave me the following The green body is the ground physics body and the gray body around the sprite is the sprite's physics body calculated with the bounds of the sprite. I plan on having images for the ground body of the same size, and wanted the sprite's feet to touch the ground. I was able to achieve this by repacking the images in a new spritesheet with TexturePacker, without any transparent pixels However, now my problem is other animations, like crouch for example As you can see, the sprite's feet are once again off the ground. Doing this animation in the game looks silly because the sprite crouches by lifting his feet off the ground body. The output metadata in JSON from TexturePacker looks like this "filename" "Crouch soldier crouch 1.png", "frame" "x" 712,"y" 867,"w" 353,"h" 425 , "rotated" false, "trimmed" true, "spriteSourceSize" "x" 49,"y" 42,"w" 353,"h" 425 , "sourceSize" "w" 433,"h" 500 , "pivot" "x" 0.5,"y" 0.5 , ... This is a problem for several of my animations with this and other sprites. Repacking with TexturePacker allows me to remove the transparent pixels and have a more accurate physics body (which was really the goal, I'd like the most accurate collision detection once I start having projectiles) but now the animations look funny. How is something like this handled in game development? |
2 | JavaScript 2D Top down Tile Collision Detection I am developing a small Top down Game (Much like the old Zelda Games) and I'm having an issue in terms of Collision detection (The actual theory itself rather than assigning Tiles as solid, etc.) I have a function called "checkTileCollision" which takes two parameters, X and Y, and is called through the Player's Move function. X and Y are the location of the player AFTER they have moved, as it's suppose to check the position the player is moving to for a solid Tile(s), and if it finds any, returns true to stop movement. My Player is larger than a Tile (For examples sake, let's say each Tile is 32x32 and the Player is 26x60) and I need to know an efficient way to detect whether or not the player is attempting to step on to a Solid tile. The Player doesn't move on the Grid and is free moving, so X and Y are true positions and not Tile co ordinates. Please note I am aware of things such as Box2D but I'm wanting to do this without the use of third party libraries. Any help is appreciated! |
2 | How do I get an attribute of a function? function randArray(arrayName) arln arrayName.length arst arrayName Math.floor(Math.random() arln) return arst create function() starts physics engine game.physics.startSystem(Phaser.Physics.ARCADE) player game.add.sprite(width 2, height 2, 'player') randSpawnItem game.add.sprite(10, 10, randArray(randItem)) randSpawnItem2 game.add.sprite(50, 50, randArray(randItem)) So the randArray function works, and there is nothing wrong with the create. I'm using Phaser, and I'm trying to spawn items randomly (kind of like in Binding of Issac.) I forsee a problem in the future, when I'm detecting for collison, I need to know what item spawned to give the right kind of item to the player. How would I get that third attribute of randSpawnItem or randSpawnItem2, or is there another way to go at this completely? Sorry if that's a noobie question! Didn't know how to word it and didn't find it anywhere else. Thanks in advance for your time. |
2 | How to save and update modifications done by the player in my procedurally generated JavaScript game? I am making a game and I need the world to be generated and saved. I used Perlin noise to generate the terrain (and other stuff like trees), but cannot figure out the best way to save and recall actions done by the player, e.i. if a tree is cut down or a mineshaft is used I want that entity to either be updated or deleted. How could I accomplish this? More info I am making this in JavaScript and eventually want to implement Node.js to implement multiplayer features in the future. The player also has a very limited view and this is a 2D top down kind of game. I am also making this basically from scratch. Any and all help is appreciated! |
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 | Line strokes also adding borders to other shapes? When you run the project, you can see that the first circles have a black border around them. When I remove the Game.drawLines(), the circles don't have the border around them anymore. Any help is appreciated! |
2 | HTML5 game obfuscation HTML5 games have viewable source code. Is there a way to make them like swf file? How to hide the game algorithm? What do you think of the Firefox JavaScript Deobfuscator Plugin and obfuscation? |
2 | Best resources for Canvas Html 5 development I am at a competition at work for who can make the best canvas game. Theme is a top down shooter... Winner gets dinner for free. Anyways I have been looking around looking for some good resources on game deving on the canvas. Any body got any good ones? |
2 | How do I maintain an online users list? In a multiplayer JavaScript game client, is it a good idea to poll the server periodically to refresh online user list, or keep track of joined left users? Is there a better option? |
2 | Rotate arrow on canvas I need to draw a flow dynamically based on some user choices. In that flow I want to draw the choices (blue circles with number) and the directions of that choices (line and arrow). For example node 1 to node 2. JSFiddle Example To draw the direction I draw a arrow in the end of the line but I can't make the arrow rotate around itself. JS code (document).ready(function () drawOnCanvas() ) function drawOnCanvas() var canvas document.getElementById('myCanvas') if (canvas.getContext) var ctx canvas.getContext("2d") var circle1 x 75, y 75, r 15 var circle2 x 225, y 50, r 15 var arrow h 5, w 10 drawCircle(ctx, circle1, "1") drawCircle(ctx, circle2, "2") var ptCircle1 getPointOnCircle(circle1.r, circle1, circle2) var ptCircle2 getPointOnCircle(circle2.r, circle2, circle1) var ptArrow getPointOnCircle(circle2.r arrow.w, circle2, circle1) drawLine(ctx, ptCircle1, ptCircle2) drawArrow(ctx, arrow, ptArrow, ptCircle2) function drawArrow(canvasContext, arrow, ptArrow, endPt) var angleInDegrees getAngleBetweenPoints(ptArrow, endPt) canvasContext.beginPath() first save the untranslated unrotated context canvasContext.save() move the rotation point to the center of the rect canvasContext.translate(ptArrow.x, ptArrow.y) rotate the rect canvasContext.rotate(angleInDegrees) canvasContext.moveTo(endPt.x, endPt.y) canvasContext.lineTo(endPt.x arrow.w, endPt.y arrow.h) canvasContext.lineTo(endPt.x arrow.w, endPt.y arrow.h) canvasContext.closePath() canvasContext.fillStyle "rgb(72,72,72)" canvasContext.stroke() canvasContext.fill() restore the context to its untranslated unrotated state canvasContext.restore() function drawCircle(canvasContext, circle, text) canvasContext.beginPath() come a ou reinicia o desenho de algo canvasContext.fillStyle "rgb(43,166,203)" canvasContext.arc(circle.x, circle.y, circle.r, 0, 2 Math.PI, false) cria arcos canvasContext.fill() atribui estilos drawText(canvasContext, circle, text) function drawText(canvasContext, circle, text) canvasContext.font '8pt Calibri' canvasContext.fillStyle 'white' canvasContext.textAlign 'center' canvasContext.fillText(text, circle.x, circle.y 3) function drawLine(canvasContext, startPt, endPt) canvasContext.moveTo(startPt.x, startPt.y) canvasContext.lineTo(endPt.x, endPt.y) canvasContext.stroke() function getPointOnCircle(radius, originPt, endPt) var angleInDegrees getAngleBetweenPoints(originPt, endPt) Convert from degrees to radians via multiplication by PI 180 var x radius Math.cos(angleInDegrees Math.PI 180) originPt.x var y radius Math.sin(angleInDegrees Math.PI 180) originPt.y return x x, y y function getAngleBetweenPoints(originPt, endPt) var interPt x endPt.x originPt.x, y endPt.y originPt.y return Math.atan2(interPt.y, interPt.x) 180 Math.PI I think the problem is in drawArrow() method in the lines canvasContext.translate(ptArrow.x, ptArrow.y) canvasContext.rotate(angleInDegrees) I already tried every possible values for the rotation and the translation but arrow still don't rotate properly around itself. Can anyone help me? |
2 | In an asynchronous server environment where player input and timed events modify data is using an in memory array problematic? So let's say I have a server running on node.js, and there is an array of player objects... At an interval, all of these player objects are looped and processed for events and changes that are based on time, such as fuel or food consumption and movement. However players can also trigger things from the client that could modify player data as well. Now what I'm trying to determine is if I am going to run into any problems with timing, such as if we are mid loop and somebody changes something and it throws some other calculation off balance. Will I need to implement some kind of locking mechanism I can use as needed or is there a better way to hold this data in memory? |
2 | Limiting Framerate and Input So I have been learning HTML5 canvas recently and ran into a bit of a snag. I created a proof of concept that builds a block based 2d map that you can move a character inside of using arrow keys. This works well because everything is free moving (character moves 1 pixel per frame, so the movement is fluid and looks good). I am trying to fork off of this code to create another concept that forces grid based movement (like in a typical roguelike). I have updated my movement code to move in chunks equal to tile size.. but the issue is that the refresh rate is so fast that it just seems like the character is moving at super speed. Here is a snippet of my code that handles animations function gameLoop() ctx.clearRect(player.x,player.y,PLAYER SIZE,PLAYER SIZE) getInput() ctx.fillStyle ' 000000' player.draw(ctx) window.requestAnimationFrame(gameLoop) Is using requestAnimationFrame() for this sort of movement not a good idea? Is it better to just setInterval() for this sort of thing? I found a article via Google that talks about using variables for time, delta, fps, etc to limit the framerate... but Im not sure I understand how to do that in conjunction with requestAnimationFrame(). Should I somehow hold my gameLoop() from hitting requestAnimationFrame() until some time interval is hit? That seems like it would just be a waste because I would need to force a loop of some kind... doesnt seem too elegant |
2 | 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 can I delete an object when it's not stored in an array? I have a boss appearing in my game, but since it's only one character I didn't put it in an array. Now I'm trying to make disappear if its health is less or equal to 0 but I don't know how to do that. Is there a way to remove the object? I only know how to remove a property of an object. Here's the boss object function Boss1(x, y) this.sprite boss1Sprite this.x x this.y y this.imgWidth 160 this.imgHeight 224 this.frameWidth this.imgWidth 4 this.frameHeight this.imgHeight 4 this.health 1500 this.directionMode 1 this.currentFrame 0 this.SPEED 1 this.delta 1 this.updateFrame function () this.currentFrame 0.2 this.showHealth function () ctx.fillStyle "red" ctx.fillRect(this.x,this.y 10,(this.health 100) 3.3,5) ctx.strokeRect(this.x, this.y 10, (100 100) 50, 5) this.show function () this.updateFrame() this.walkingMode Math.floor(this.currentFrame) 4 ctx.drawImage(this.sprite, this.walkingMode this.frameWidth, this.directionMode this.frameHeight, this.frameWidth, this.frameHeight, this.x, this.y, this.frameWidth, this.frameHeight) target hero position this this.move function () this.dx hero.x this.x this.dy hero.y this.y this.length Math.sqrt(this.dx this.dx this.dy this.dy) if (this.length) this.dx this.dx this.length this.dy this.dy this.length this.x this.dx this.delta this.SPEED this.y this.dy this.delta this.SPEED enemy wave object function random(min, max) return Math.random() (max min) min function Enemy(x, y) this.sprite enemySprite this.x x this.y y this.imgWidth 128 this.imgHeight 192 this.frameWidth this.imgWidth 4 this.frameHeight this.imgHeight 4 this.toDelete false this.dx random(1, 3) this.enemiesHealth 100 this.directionMode 1 this.currentFrame 0 this.updateFrame function() this.currentFrame 0.2 this.showHealth function () ctx.fillStyle "red" ctx.fillRect(this.x,this.y 10,(this.enemiesHealth 100) 50,5) ctx.strokeRect(this.x, this.y 10, (100 100) 50, 5) this.show function() this.updateFrame() this.walkingMode Math.floor(this.currentFrame) 4 ctx.drawImage(this.sprite,this.walkingMode this.frameWidth, this.directionMode this.frameHeight, this.frameWidth, this.frameHeight, this.x, this.y, this.frameWidth, this.frameHeight ) this.move function() this.x this.x this.dx this.deletion function() this.toDelete true this is when the boss is spawning the game loop function draw() bullets bullets.filter((bullet) gt bullet.x lt viewLimit) enemies enemies.filter((enemy) gt enemy.x gt viewLimit1) while (enemies.length lt enemiesPerTick amp amp kills lt 5) var enemy new Enemy(canvas.width, random(0, canvas.height 60)) enemies.push(enemy) for (var v 0 v lt enemies.length v ) enemies v .showHealth() ctx.clearRect(0, 0, canvas.width, canvas.height) hero.show() hero.update() hero.showHealth() for (var i 0 i lt bullets.length i ) bullets i .show() bullets i .move() for (var j 0 j lt enemies.length j ) enemies j .show() enemies j .move() for (var t 0 t lt enemies.length t ) enemies t .showHealth() collision() drawScore() if (enemies.length 0) boss1.show() boss1.move() boss1.showHealth() requestAnimationFrame(draw) console.log(enemies, bullets) draw() |
2 | How can I get a 4x4 matrix from a bullet quaternion? I'm trying to make a game using JavaScript with Ammo.js ( an implementation of bullet ) and Sylvester to do my matrix maths. The problem is I don't know how to turn the WXYZ that bullet gives into the 4x4 matrix Sylvester needs. If there is a way to just get Bullet Physics to give me the 4x4 matrix please tell me! I am completely lost here. |
2 | Why can't i change the background color in Phaser? what is wrong with my code? i'm using game.stage.backgroundColor but the screen remains black. main.js var demo demo demo.game new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '') demo.game.state.add('state1', demo.state1) demo.game.state.add('state2', demo.state2) demo.game.state.start('state1') state1.js var demo demo demo.state1 function() demo.state1.prototype preload function() , create function() game.stage.backgroundColor " 4488AA" , update function() |
2 | Tile Map Coordinates I am have now this code http jsfiddle.net DK67k 2 In here is 2D tile map and when you click on tile you get coordinates on alert. But for get precises coordinate you need click on top left tile(tiles is 16x16) and if I click on bottom right tile I am get second tile coordinates. Maybe anyone have idea how to fix this? |
2 | Implement Fast Inverse Square Root in Javascript? The Fast Inverse Square Root from Quake III seems to use a floating point trick. As I understand, floating point representation can have some different implementations. So is it possible to implement the Fast Inverse Square Root in Javascript? Would it return the same result? float Q rsqrt(float number) long i float x2, y const float threehalfs 1.5F x2 number 0.5F y number i ( long ) amp y i 0x5f3759df ( i gt gt 1 ) y ( float ) amp i y y ( threehalfs ( x2 y y ) ) return y |
2 | UV texture mapping with perspective correct interpolation I am working on a software rasterizer for educational purposes and I am having issues with the texturing. The problem is, only one face of the cube gets correctly textured. The rest are stretched edges You can see the running program online here. I have used cartesian coordinates, and all I do is interpolate the uv values along the scanlines. The general formula I use for interpolating the uv coordinates is pretty much the one I use for the z buffering interpolation and looks like this (in this case for horizontal scanlines) u Slope (right.u left.u) (triangleRight x triangleLeft x) v Slope (right.v left.v) (triangleRight x triangleLeft x) ... new u left.u ((currentX onScanLine triangleLeft x) u Slope) new v left.v ((currentX onScanLine triangleLeft x) v Slope) Then, when I add each point to the pixel buffer, I restore z and uv z (1 z) uv.u Math.round(uv.u z 100) 100 because my texture is 100x100px uv.v Math.round(uv.v z 100) Then I turn the u v indexes into one index in order to fetch the correct pixel from the image data (which is a 1 dimensional px array) var index texture.width uv.u uv.v and the rest is unimportant imagedata index .RGBA bla bla The interpolation formula is correct considering the consistency of the texture (including the straight stripes). I must get some sleep now, but before I get into further dissecting of every single value to see what goes wrong, Can someone more experienced guess why might this be happening, just by looking at the cube? "I have no idea what I'm doing" (it's my first time implementing a rasterizer). Did I miss an important stage? Thanks for any insight. PS My UV values are as follows u 0, v 0 , u 0, v 0.5 , u 0.5, v 0.5 , u 0.5, v 0 , u 0, v 0 , u 0, v 0.5 , u 0.5, v 0.5 , u 0.5, v 0 EDIT The uv values were to blame, and pixel 50 being in the second zone, as Victor pointed out. My new uv values u 0, v 0 , u 0, v 1 , u 1, v 1 , u 1, v 0 , u 1, v 0 , u 1, v 1 , u 0, v 1 , u 0, v 0 To some extent this was "a bug in my code", but also I had overlooked an important part of the process the uv values should not just be assigned to the 8 corners of the cube. |
2 | Chrome Angry Birds engine? Was Chrome AngryBirds game made using html5 canvas? And if yes what kind of engine did they use? |
2 | Confused about Max Vertex Uniform Vector limit While coding my WebGL app I've encountered an interesting phenomena On my first PC (with GPU Radeon HD 5850), BrowserLeaks (link) tells me that in my browser Google Chrome Version 36.0.1985.143m the Max Vertex Uniform Vectors value equals 1024 which is true, when I try to create inside the shader an attribute array bigger than 1024, the browser throws an error too many uniforms, which f.e. in my case let's me draw about 85 simple cubes in a single draw call. Meanwhile on my other PC (with GPU Intel X3100) with Opera Next Version 12.15 installed, where BrowserLeaks shows a value 4096 next to the Max Vertex Uniform Vectors field, I can init an array of size 250 000 and even bigger, I can draw 20 000 cubes in a single draw call and everything works fine (except a very low framerate). So now my question is Why those numbers varies so much, why in the second case the upper limit value does not seem to be valid? How would I find the true upper limit value (and read it inside my WebGL app at the runtime)? EDIT Ok, I've found out how to get this parameter inside a WebGL app gl.getParameter(gl.MAX VERTEX UNIFORM VECTORS), but the question now is how would I adapt it to shaders... |
2 | Which free HTML5 based game engine meets these requirements? I am experienced with traditional JS and HTML but new to HTML5. I want to develop games in HTML5 so that it can work on all devices and browsers, including IE. Additionally, I require the following features Physics Engine Animation Some AI Vector drawing and manipulation Better user player controls, et cetera I know there are many options, but just want some one that can give most flexibility... so I want some thing that can also be compiled to achieve maximum functionality. One that is in my mind is GameKit but please tell what you guys would suggest that meets my requirements. |
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 | 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 | 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 | Javascript Audio solution still has issues. Flash works but... requires flash (an issue for iOS). What do you use in Javascript for audio? |
2 | Lighting effects with 2D sprites I would like to know how to best achieve lighting effects with 2D. I guess the only way is to make sprites of the area to be lit in specific colors? Say I have a streetlamp, and around this place sprites to make it appear lit? Is there a better way? Edit Found a good screenshot of what I'm looking for http www.saltgames.com wp content uploads 2009 11 multipleLights.png |
2 | How do I write a simple 2 player server? I've recently started learning JavaScript and HTML and developed simple 2 player game such as tick tack toe, battleship, and dots amp boxes. However, these 2P games can only be played on one computer (i.e. the 2 players must sit together). I want them to be able to play with a friend on a different computer. Would anyone have a general, simple working example of a web game server? |
2 | How to implement map scrolling inertia formulae I'm looking for a mathematical formulae to calculate map scrolling inertia. Basically I have an HTML5 Canvas displaying part of a map and I capture the mousedown mousemove mouseup to calculate my new offset. And when I scroll the map I want the map to continue scrolling for a few moments after the user stopped dragging the cursor. I do have a sample implementation but I'm not really satisfied with it. I'd be looking for a nice clean math formulae to achieve this. I'd like my map to behave for example like in Civ 5 when you scroll the map around. Here is part of my implementation (working jsfiddle https jsfiddle.net CowWarrior dkxnj5d8 1 ) mouseup stopMapDrag function (e) var movementX (e.pageX this.startX) var movementY (e.pageY this.startY) this.mapOffsetX parseInt(this.mapOffsetX) movementX this.mapOffsetY parseInt(this.mapOffsetY) movementY this.isDragging false this.displayMap() calculate last vector ui.vectorX parseInt(e.pageX ui.absStartX) ui.vectorY parseInt(e.pageY ui.absStartY) show inertia setTimeout(function() ui.dragInertia(2) , 30) console.log("(vectorX " ui.vectorX ", vectorY " ui.vectorY ")") (' canViewport').css('cursor', 'default') , need to find a good formulae for inertia dragInertia function (factor) var movementX parseInt(ui.vectorX factor) var movementY parseInt(ui.vectorY factor) ui.mapOffsetX parseInt(ui.mapOffsetX movementX) ui.mapOffsetY parseInt(ui.mapOffsetY movementY) ui.displayMap() if (factor lt 8) setTimeout(function() ui.dragInertia(factor 1.2) , 30) , |
2 | Why my canvas isn't showing anything after I put code in the loop for tile map? My canvas stop showing anything when I want to display a tile 25 times. No errors. Here is the code var canvas document.getElementById("canvas") var context canvas.getContext("2d") 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) image.onload function() context.drawImage(image, sx, sy, swidth, sheight,x, y, width, height) var Loader function(src) this.image new Image() this.image.src src this.image.onload function() var sprite new StyleSheet(background, 16, 16) for (i 0 i lt 25 i ) for (j 0 j lt 25 j ) sprite.draw(background, 30, 30, 36, 36, i 36, j 36, 36, 36) return this.image var background new Loader("https opengameart.org sites default files PathAndObjects.png") console.log(background) |
2 | How to work with edge Texture Im not sure if i use the right terms, but im not able to find something to start with. Im trying to develop a little HTML5 game. I have a ground with a texture and now I want to make a surrounding texture. The texture is an image wich should be bend around the ground. At the moment im using easelJS for display my images textures. So im looking for some sort of Tutorial Script Advice. Im not even sure if I can bend a image in javascript. So the worst case I can think of is split the image in 100 pieces and then put it back together and rotate each piece. for example like this |
2 | How to get the center of a rotated rectangle regardless of point of rotation I need help working out the centre coordinate of a rotated rectangle regardless of the point of rotation (i.e. the rectangle doesn't rotate around its center). I do not know the coordinates of the corners, so it's not a simple case of dividing those. It's easier to show than tell, so here's example 1 http gametest.mobi rotate index.php?f point1.js amp d tests Click to start stop the rotation. In this example I've got my sprite with the rotation point set to the bottom right corner of it. If you click you'll see it rotate around that. I need to find a way to work out the coordinates of the center of the rectangle (represented by the middle red cross hairs.) Here is another example, this one is set to rotate at 0.3 x 0.8 into the rectangle http gametest.mobi rotate index.php?f point3.js amp d tests You can see I added the circle into each demo, this is positioned on the sprites x y coordinate and the radius was calculated from the distance of the center of the rectangle to the rotation origin. I can visually see the correlation between the point of rotation and the circle, and I can see it tracks the centre of the rectangle beautifully on the circles perimeter! But I'm falling at the last hurdle in trying to calculate the actual value, so desperately need a fresh set of eyes on it please. |
2 | Eliminate isolated cave in procedural cave generation I've got an algorithm that generates a cave procedurally, the map is modeled in the data as a 2d array of 0s (empty space) and 1s (wall). The algorithm works just fine, but I've got quite some isolated small caves on the scene, which I would like to avoid. That's how the map looks that gets generated. Is there some efficient algorithm to remove the black holes in the white wall sections? I was thinking of something like For every closed cave, check if there is a bigger cave and if so, close it. But that seems insanely inefficient since I'd have to loop over the map a lot in order to do this for all small caves. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.