HTML5 clicking objects in canvas I have a function in my JS that gets the user's mouse click on the canvas. Now lets say I have a random shape on my canvas (really its a PNG image which is rectangular) but i don't want to include any alpha space. My issue lies with lets say i click some where and it involves a pixel of one of the images. The first issue is how do you work out the pixel location is an object on the map (and not the grass tiles behind). Secondly if i clicked said image, if each image contains its own unique information how do you process the click to load the correct data. Note I don't use libraries I personally prefer the raw method. Relying on libraries doesn't teach me much I find.


What is wrong with my Dot Product? I am trying to make a pong game but I wanted to use dot products to do the collisions with the paddles, however whenever I make a dot product objects it never changes much from .9 this is my code to make vectors vector make function(object) return object.x object.width 2,object.y object.height 2 , normalize function(v) var length Math.sqrt(v 0 v 0 v 1 v 1 ) v 0 v 0 length v 1 v 1 length return v , dot function(v1,v2) return v1 0 v2 0 v1 1 v2 1 and this is where I am calculating the dot in my code vector1 vector.normalize(vector.make(ball)) vector2 vector.normalize(vector.make(object)) dot vector.dot(vector1,vector2) Here is a JsFiddle of my code currently the paddles don't move. Any help would be greatly appreciated


Retrieving JSON return value from function and parsing in Construct 2 I would like to know how to parse a JSON object and parse each value into either an array, or something that I can use to set values of several global variables in my project file. I want to avoid editing the Javascript file itself, so please try to provide an approach that can be done in Construct itself rather than an external way. Code sample axonify.game gameData function() data name 'Block Mania', timeLimit 30, addedTimePerQuestion 0, addedTimePerCorrectQuestion 15, questionCount questionCount return data ,


Node.js V8 as a Platform for High End Local PC Game Development? As a Web UI dev rapidly expanding into more wide open generalist territory, the more I learn about how its done in other languages, the more I love JS for architectural and basic messaging event driven concerns. For the record I am most certainly not a full blown game dev (although I did once write for a major gaming mag which is like saying I pretended to be friends with game devs on TV, although you guys were always my favorite folks to talk to). Anyway, since it's fairly easy to bind C and C to JavaScript via Node (or perhaps more specifically V8), how reasonable would it be to assume you could write a decent 3D engine that exposed outcomes of things like collision calculations as events to the JS with the intention of getting the dynamic first class function party language benefits (assuming you see such things as benefits I do) to higher level architecture and AI logic concerns without a crippling loss in performance? Node, as I understand it, basically exposes a C event loop to JavaScript handled by V8. The JS is single threaded, meaning any attempt to do anything calculation IO intensive with the JS would be foolish, but you get the advantage of not really having to sweat threads, queuing etc... since you're ideally never trying to muck with the same data at the same time. Most code would of course be heavily event callback driven. All the file I O concerns and other processor intensive stuff is basically C or C under the hood telling you when its done. Not to mention handling UI concerns directly out of the JavaScript via a webkit layer slapped on top of everything. I'd be delighted to hear why you love hate the idea but the core question is is it feasible and why not? And no, I seriously doubt my own ability to do this all by myself, although plugging an existing 3D engine in might not be outside of the realm of possibility but I'd still be learning a lot of new stuff to make that happen I'm sure.


How do I generate terrain like that of Scorched Earth? I'm a web developer and I am keen to start writing my own games. For familiarity, I've chosen JavaScript and canvas element for now. I want to generate some terrain like that in Scorched Earth. My first attempt made me realise I couldn't just randomise the y value there had to be some sanity in the peaks and troughs. I have Googled around a bit, but either I can't find something simple enough for me or I am using the wrong keywords. Can you please show me what sort of algorithm I would use to generate something in the example, keeping in mind that I am completely new to games programming (since making Breakout in 2003 with Visual Basic anyway)?


How do I go from a simple html5 tic tac toe game to an online 2 player game? I've been working on an online 2 player Tic Tac Toe solution for blackberries. both old and new. And so far I have html5 code that has a 3 x 3 layout that switches between x and o for the game mechanics. I believe I'm still missing a check for win function but my question is about the server side of this game. I'm not sure how to go about learning what exactly I want. how do you take what I have now, and make this into a functioning online game? I've been told WAMP is a good solution, as well as IIS. and its all really over my head, so i'm hoping to get a little more clarity as far as what I should focus on to bring this game to life.


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


Receiving keyboard events on a canvas in Javascript I need to receive keyboard events in a canvas element. Click events are received but key presses aren't. Here is my code which doesn't handle key events var canvasElm ('canvas') Event.observe('canvas', 'keypress', function(e) console.log('Key event is received!!') console.log(e) ) How can I make it handle those key events?


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?


Orientation while rotating around a point I am using this formula to rotate around a point. X originX sin(angle) Size Y originY cos(angle) Size In cartesian cordinates how would I keep the objects orientation in relation to the origin object as it moves around the origin. Any one know where I could look for answer to that?


Cocos2D JS Windows App in fullscreen mode (Win32) I've been looking for a way to make my Cocos2D JS app go into fullscreen mode, but there doesn't seem to be much documentation on Cocos2D JS (or Cocos2D x js as some seem to call it.) This app is to be exported into a Windows Desktop platform (Win32), and so fullscreen mode should work there as well. I checked the Cocos2D JS Online API and found cc.screen, which has a method called requestFullScreen, so I tried this cc.screen.requestFullScreen(document.documentElement, function() cc.log('Requesting full screen...') ) However, this didn't work on either of the platforms I tested it on (web browser and win32). Since document does not exist when you export the app into win32, I then tried changing it for cc. canvas cc.screen.requestFullScreen(cc. canvas, function() cc.log('Requesting full screen...') ) But this did not work either. Is there a way to make the app run in fullscreen mode? PD My apologies for any wrong tags I may have included to this question. I added the ones I thought were related to this problem.


What is this JavaScript gibberish? I am studying how to make a 2D game with JavaScript by reading open source JavaScript games and I came across this gibberish... aSpriteData " " " " " " C " " " P7 OK u " lt a a bM ", 0 ground "a ' ! 7 b mt lt N 7z OR f 7l ,tl , XN Sb bl Y ! ", 1 qbox "!A , n amp X lt 8 Prc'U Z'H' "is amp 08 (", 2 mario " !A. H q8 e n oW amp X a lt amp bbX LWP41 k 3 q 1f RQ 4 ", 3 mario jump " 40 q !hWa n Y a ,0 aaPw cmY lt mq GBagaq amp q 0 0t0 ", 4 mario run " hP ", 5 pipe left " ,6 lt R ", 6 pipe right " amp ,' hP? gt ' ! . y pX a hP? gt ' ! . Ba a", 7 pipe top left " , ! " , 8O 7a amp !c 9 P amp O ,4 e", 8 pipe top right " ! ,! P!!vawd XO 8 ' P '9 "P Pa (! 5!N (4 b!Gk(a", 9 goomba " Xu X5 ou! a Z q. u xv H'WOJ! a Nu J lt J a", 10 coin yui " amp !MX L "y P 5a K w !L "y P a 4 a", 11 ebox yui " , " aN! amp 7 " aN!XH " aN!X 8 " aN!X (", 12 bricks " !N I lt P .8 "h,!Cg r H a4X lt P .H I a!u !q", 13 block makeSpace(20) "4a 0 N( w " N! aa", 14 bush left " r " y!L aN zPN NyN L cy N" makeSpace(18) " ", 15 bush mid makeSpace(18) " !R a!x6 amp 6 87L 6 P 8 (", 16 bush right " pq 7 gt " s" makeSpace(25) " ", 17 cloud bottom left "a a .Q ' b 8. 7!X "K 5cqs (" makeSpace(18) "0", 18 cloud bottom mid "bP L P 8 a, a J" makeSpace(22) "(", 19 cloud bottom right "", 20 mushroom "", koopa 16x24 "", 22 star "", 23 flagpole "", 24 flag "", 25 flagpole top " 6 a 0 ( " ! a 0 ( " ", 26 hill slope "a "m 8 P!MF 5la "y P" makeSpace(18) "(", 27 hill mid makeSpace(30) " " t!DK "q", 28 hill top "", 29 castle bricks "", 30 castle doorway bottom "", 31 castle doorway top "", 32 castle top "", 33 castle top 2 "", 34 castle window right "", 35 castle window left "", 36 castle flag makeSpace(19) "8 (9F RSf.8 A ! 040HD", 37 goomba flat " (! q Yp lt g amp 'PaS Sbq lt I Ld Ryd e8H8bf 0a", 38 mario dead " b 'N Z Z Z Z Z Z Z Z Z Z Z Z q 0", 39 coin step 1 " ? q e ' ! a N0 ?( e ' a "", 40 coin step 2 " gt ! a gt ! 'a "", 41 coin step 3 " 7 gt "p !Ga t I 4 gt "p Oa "" 42 coin step 4 , What does it do? If you want to look at the source file, here it is. Beware, there is more gibberish inside. I can't seem to make sense of any of it.


Game loop with fixed timestep gives strange result So I've read the famous article at http www.koonsolo.com news dewitters gameloop comment page 2 comments which describes different methods of implementing a game loop. I've tried to implement the final method that is described in the article in Javascript (ignoring interpolation for the time being) var Timer pastTime 0, currentTime 0, started false, starts the timer start function() if(!this.started) this.started true this.pastTime new Date().getTime() , gets the time in MILLSECONDS getTime function() return new Date().getTime() this.pastTime , stops the timer but does not reset it (i.e. getTime() can still be called to get the time between start() and end()) end function() if(this.started) this.currentTime new Date().getTime() this.started false return this.currentTime this.pastTime , resets the timer reset function() this.pastTime 0 this.currentTime 0 this.started false var maxFrameSkip 5 var nextTick new Date().getTime() var TICKS PER SECOND 25 var tickTimeMillis 1000 TICKS PER SECOND var ticksPerSecondReal 0 var ticksCounter 0 var timer Object.create(Timer) var loops 0 function gameLoop() loops 0 timer.start() while(new Date().getTime() gt nextTick amp amp loops lt maxFrameSkip) update() ticksCounter nextTick tickTimeMillis loops draw() if(timer.getTime() gt 1000) ticksPerSecondReal ticksCounter ticksCounter 0 timer.reset() console.log(ticksPerSecondReal) window.requestAnimationFrame(gameLoop) gameLoop() So the problem that I'm having is that the console.log(ticksPerSecondReal) should always be giving me 25 because that's the constant ticks per second that I want and have set up. What I end up getting is an alternating number that is 25 and 26. So periodically ( 1 second) it will be 25 and then 26 and then 25 and so on. And sometimes (much less frequently) it will even give a result of 27. It keeps switching back and forth when it should be constant at 25. What is the issue here?


I need a map generation algorithm for towerdefense I'm making a simple JavaScript tower defense game, I've experimented on some map generation my self, i seem to get one that works properly. What I want is for you to provide a start point (possibly an end point) and an algorithm to generate a random path between them in a tower defense like style. Examples


Are commercial javascript games sensible? So I love javascript as a language and how it is able to be run anywhere. I'm gonna enumerate my concerns Does it make sense to make money from javascript? I mean, the second I publish my game online, people can download it, and post it on their own site and put their own ads into the game. There are rumors that Facebook is working on an HTML5 platform. Still, even if you require the use of secret keys with your online part of the game, people can still just download the source code and implement their own online version. It's a little inconvenient, but the game itself didn't lose any value. They just need to build their own community now which should be easy with a great game. I don't have a smartphone, can someone explain if it's possible to view the source if I publish my game as a javascript application? (maybe it's wrapped into native code by the marketplace, I would appreciate the information) I know Flash is somewhat similar, but it's my understanding that good obfuscators can effectively make the source code so ugly that it would be a mountain of work to modify. Native games can be cracked too of course, but that doesn't mean they have the source code. They'll still rely on my online part and my updates to the game. Tell me I'm not paranoid ) How can someone justify spending resources on a javascript game?


Tween keeping a constant velocity at different distances I am using a tweening library to move my units around. The problem is that the speed varies depending on the distance that the unit has to move because of the tweening var time 1000 var tween new TWEEN.Tween( x startX, y startY ) .to( x endX, y endY , time) .start() No matter the x and y values it will always take the same amount of time. I tried fixing this by dividing the distance by the speed distance speed time time distance speed var x endX startX var y endY startY var distance Math.sqrt(x x y y) var time distance speed dt var tween new TWEEN.Tween( x startX, y startY ) .to( x endX, y endY , time) .start() However it still doesn't move at the same speed! Grr! I made a snippet that shows a square endlessly moving in a rectangle, when done correctly ( which this isnt... ) it should move at the same velocity no matter the distance. var rect document.getElementById("rect") var pos 0, 0 , 200, 0 , 200, 50 , 0, 50 var i 0 var time 1000 var speed 10 1000 10px per second var tweenStart x 0, y 0 var tweenEnd x pos i 0 , y pos i 1 var tween new TWEEN.Tween(tweenStart) .to(tweenEnd, time) .onUpdate(function () rect.style.top this.y "px" rect.style.left this.x "px" ) .onComplete(function () tweenStart.x pos i 0 tweenStart.y pos i 1 i 1 if (i gt pos.length) i 0 tweenEnd.x pos i 0 tweenEnd.y pos i 1 time distance speed var x tweenEnd.x tweenStart.x var y tweenEnd.y tweenEnd.y var distance Math.sqrt(x x y y) time distance speed dt tween.start() ) setTimeout(initiate, 0) var now, then, dt function tick() now perfNow() dt now then then now TWEEN.update() requestAnimationFrame(tick) var perfNow (self.performance amp amp self.performance.now) ? self.performance.now.bind(performance) Date.now function initiate() var x tweenEnd.x tweenStart.x var y tweenEnd.y tweenEnd.y var distance Math.sqrt(x x y y) time distance speed dt tween.start() then perfNow() tick() body margin 0 overflow hidden div position absolute width 10px height 10px background color black lt script src "https dl.dropboxusercontent.com u 53738503 tween.min.js" gt lt script gt lt div id "rect" gt lt div gt


2d array with empty elements I am working on a game with a number of different grid components. Each grid would be about 15 squares wide by 15 squares tall. Each of the squares may either contain an item or not. Is there any way to create this array and only include the components that have a value. Example (for a 5x5 array) 5,3, , ,3 , ,1,0,2,2 , , , , , , 5, , ,2, , , , , ,1 Is there any way to do this in JavaScript or should I just add a bunch of NULL values to the array? A simplified version of this, might be an Xs and Os game. Before the game starts all squares are empty. Over time, some of the grid may have either Xs or Os in specific squares.


Securing JavaScript PHP game data Followup to securing http data from a javascript game to server. I'm working on something similar, in that I have a PHP backend and a JavaScript frontend, which plays around with the HTML5 canvas element for drawing. There will be some heavy client server communication required, as the player will get timely updates from the server with regards to actions that other players are taking. In turn, the client will update the server with his actions that have been taken. My question is what is the best way to secure such data? Since the client is basically JavaScript, what are some good ways to secure my game data game states from being tampered with. I had a thought (spurred by answers to the previous question), about generating a hash based on the currently active session, storing that in a game state database, and validating it server side. However, I would imagine that any data sent back to the server via AJAX can be scrubbed for any key that I send back.


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.


How to open box item animation? I want make 2d open box animation. Like cs go open keys or other random box. I need the basics of implementation it and i want get more information about it. Thanks. Upd Steps. I have array of elements. I press to button and shuffle array. I get random element from array by weight. All elements in array have images. So , after i press button all images start move with some accelerate to left or right. 6 images move to left. And what is next ? I need get random items images while acceleration is not end ? Or what ? I need logic example. My example realization(I don't know working it or not) I need add to array new items while acceleration is enable or what ? Or after i get random item by weight, i need sort array and past it item to last position and add other random items to this array. And after all i need loop to this array to last item. And when loop in last position i show it item in screen ? I really don't understand how it working.. D


How can I convert screen coordinates from a click to 2D scaled world coordinates? I need a way to convert screen coordinates obtained from mouse clicks to world coordinates in my 2D game. To create a zoom effect controlled by the user, before drawing a model I will scale all of it's points by a world scale value. The screen origin (0,0) is at the top left corner while the world has it's center (0,0) at the center of the screen (width 2, height 2). I need a function to convert the coords obtained by mouse clicks (screen coords) to the corresponding scaled world coordinates, so that I can determine what world element is clicked by the user in this scaled world. Any of my approaches worked as required and unfortunately none of the found solutions where aplicable to my case. This is a very simple example JS Bin Use the mouse wheel to zoom in out Click on the screen to set a point Thanks!


How to make physics of motion on an inclined surface There is the following platform And a coin above it And the following code using arcade physics gravity y 100, x 10 , in config function preload () this.load.image('platform', 'assets platform.png') this.load.image('star', 'assets star.png') function create () platforms this.physics.add.staticGroup() platforms.create(400, 568, 'platform') player this.physics.add.sprite(100, 450, 'star') player.setCollideWorldBounds(true) The code is approximate, a coin above the platform, sprites in png format. But the coin falls and does not roll, but moves horizontally, after which it falls again. How to make it "roll"? UPD Will it help me? https github.com photonstorm phaser examples blob master examples arcade 20physics circle 20body.js And how to be with the platform?


custom SetInterval function in javascript i am trying to make an custom set interval function for my game but everytime i tried, i end up with a infinite loop. I can't use the default javascript's set interval because it can not take the random number. any idea?


Calculating bullet travel knowing coordinates and radian I have a player sprite that has a x and y coordinate and also a radian. The radian determines which way the sprite faces in a top down game interface. In this case, the radian points from the player sprite to the mouse cursor, so the player is always facing the mouse. I'm calculating it like this this.radian Math.atan2(inputs.mousey this.ypos, inputs.mousex this.xpos) Now I want the player to be able to fire bullets. The bullet sprite is 5x5 pixels, and I want it to fire directly away from the player in the players direction (so it's basically firing in the direction of the mouse cursor). The bullets the player fires are held in an array called (conveniently) bullets. It's a 2 dimensional array that looks like this var bullets xpos, ypos, radian , first bullet xpos, ypos, radian , second bullet xpos, ypos, radian third bullet The bullet is to travel 5 pixels on each game tick, in the direction determined by the radian. But I'm having trouble working out the math for this. I already have the bullet being drawn to the canvas, and I can make it move, but have no idea how to make it follow the direction the radian is pointing. Could anyone lend a hand, perhaps a code sample? Thanks.


Representation of trains on a simplified rail grid I'm working on a hobby game, basically about train dispatcher's job. (stack Typescript, phaser.js) My map is based on a grid, each tile can hold 1 rail tile (well, except junctions, but we can simplify it for now, since junctions are just multiple tiles, from which only one is active). Example (black is grid, white is rail) As you can see, we have basically three different tiles straight rail, 45 degree turn and diagonal rail (which can be also considered straight rail). I don't plan to add more tiles, as you can already build pretty complex setups from these tiles. On these rails, trains would drive. Each carriage has two "wheels" positions, where it snaps to a track. This may be seen on the following example from my prototype However the existing system (see below) has some issues when a train travels diagonally, sometimes it's x and y coordinates fit in a field than it should (example traveling from 1 1 to 2 2, but at one point the train's coordinates correspond to the field 1 2 or 2 1). axles sometimes get closer or futher away from each other. This has almost no effect on resulting simulation (as the carriage is centered between those two axles), but may cause carriages to be closer or futher away from each other (this effect is visible on the prototype as weell) moving the train in a certain direction is handled by a big chunk of code that essentially lists all possibilities of directions and handles it. I'm interested if there's a better way to do it, so I could simplify the code. I decided that I would improve the core. I'm wondering, what would be the best way to do this? What I am looking for how to save the rail pieces on the map? how to move train (I know it's x, y, speed and acceleration)? how to have the train continue to the next piece on the grid? Current solution (broken in some edge cases, also not ideal) each rail piece has it's class (CurvedRail, StraightRail) each rail piece class has method movePoint, that accepts x, y, direction and distance and returns new point (that is distance away from the original point, but also considering track turns). It may also return delta, if the movement reached edge of the tile and it needs to be moved futher (on another piece). This is handled by a separate class, that finds the following rail piece and calls movePoint with the delta instead it has issues, because sometimes trains passing diagonal connection don't exactly follow the diagonal, so they instead of ending up on the next diagonal piece, they end up on neighboring horizontal or vertical piece and derail. One of the issues I may be facing is that tiles are 32x32 pixels, so it's hard to travel exactly in the "middle" of the piece, because it's "between two pixels", and although I'm using decimals, it may be a problem. Is it better to have a grid from odd sized tiles?


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)


Animating sprites at different speed than what the game runs at I am building a Javascript canvas platformer game, and it's coming along nicely. The only problem I've really run into where I can think of any solution at all is the animation of my player sprite. The game loop is running every 16ms, which equates to 60fps. On every game loop, I'm using a method of my player class (called draw) to draw the player sprite. The sprite looks like this http i.imgur.com uM3Un.png On every call of the draw method, I am advancing the "frame" of the player sprite, to give the illusion that the player is moving. As far as I know, this is common practice. However, due to my draw method being run every 16ms with the game loop, my player sprite is animating extremely quickly, and it doesn't look realistic at all. Is there a way to slow this down to a pre defined speed, or will I have to resort to adding loads of duplicate frames to my player sprite? Obviously that's not a great solution, as to make it look realistic at a game speed of 60fps I'd need to have a LOT of frames. Here's my relevant code Sets off the main game loop setInterval("gameLoop()", gameSpeed) function gameLoop() Updates player.update() Draw c.clearRect(0, 0, canvas.width, canvas.height) player.draw() Then in my player class... this.draw function() if(this.state "idle") c.drawImage(this.idleSprite, this.idleSprite.frameWidth this.idleSprite.frameCount, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, this.xpos, this.ypos, this.idleSprite.frameWidth, this.idleSprite.frameHeight) if(this.idleSprite.frameCount lt this.idleSprite.frames 1) this.idleSprite.frameCount else this.idleSprite.frameCount 0 else if(this.state "running") var height 0 if(this.facing "left") height 37 c.drawImage(this.runningSprite, this.runningSprite.frameWidth this.runningSprite.frameCount, height, this.runningSprite.frameWidth, this.runningSprite.frameHeight, this.xpos, this.ypos, this.runningSprite.frameWidth, this.runningSprite.frameHeight) if(this.runningSprite.frameCount lt this.runningSprite.frames 1) this.runningSprite.frameCount else this.runningSprite.frameCount 0


Any social gaming services for JavaScript games? I'm currently planning on building a HTML5 JavaScript game for the various platforms (Browser, iOS, Android, and WinMo7). I, obviously, would like there to be simple multiplayer (1v1, asynch), leaderboards, etc. Finding a service that provides this for native applications is easy (Scoreloop, Gree, etc.) but I have yet to find one that allows access through JavaScript. So with that said, does such a service platform exist or am I looking at creating my own (probably with node)?


Changing JavaScript Player Object based on keypress I'm currently working on a basic JavaScript top down shooter and I've run into a dilemma. I'm trying to implement a basic toggle weapon system however when I press the key it changes the weapon properly but when I press it again to toggle back it doesn't work. I don't think it's an issue with the rendering because the drawing function is able to detect the different weapons properly. I feel it's an issue with the actual toggle system code. Here's the code for the player class class Player constructor(set) this.cx set.x this.cy set.y this.r set.r this.color set.color this.angle 0 this.toAngle this.angle this.state 1 this.up false this.down false this.right false this.left false this.bind() bind() const self this c.addEventListener('mousemove', (e) gt self.update(e.clientX, e.clientY) ) window.addEventListener('keydown', (e) gt if(e.keyCode 81) if(self.state 1) self.state 0 if(self.state 0) self.state 1 ) toggle code window.addEventListener('keyup', (e) gt if(e.keyCode 81) if(self.state 1) self.state 0 if(self.state 0) self.state 1 ) update(ex, ey) this.toAngle Math.atan2(ey this.cy, ex this.cx) canv() if(this.angle ! this.toAngle) clear() ctx.save() ctx.translate(this.cx, this.cy) ctx.rotate(this.toAngle this.angle) ctx.translate( this.cx, this.cy) drawPlayer(this.cx, this.cy, this.r, 0, 180, this.color, this.state) this.angle this.toAngle drawing code (above this one in the complete file) function drawCircle(x, y, rad, startAngle, endAngle, color) ctx.fillStyle color ctx.beginPath() ctx.arc(x, y, rad, startAngle, endAngle) ctx.fill() function drawPlayer(x, y, playerR, playerStartAng, playerEndAng, color, state) left hand start if(state 0) ctx.fillStyle color ctx.beginPath() ctx.arc(x 15, y 15, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() end right hand start ctx.beginPath() ctx.arc(x 15, y 15, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() if(state 1) right hand start ctx.beginPath() ctx.arc(x 7, y 21, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() ctx.fillStyle color ctx.beginPath() ctx.arc(x 7, y 17, 10, 0, 180) ctx.fill() border ctx.strokewidth 10 ctx.strokeStyle "brown" ctx.stroke() gun start ctx.fillStyle "black" ctx.beginPath() ctx.ellipse(x, y 20, 3, 25, 0, 0, 2 Math.PI) ctx.fill() gun border ctx.strokewidth 10 ctx.strokeStyle "black" ctx.stroke() end draw player drawCircle(x, y, playerR, playerStartAng, playerEndAng, color)


solid color to sprite (javascript game) Hi I recently created a javascript game, in this game, math random is used to pick a random shape. The shapes are in strings, and the associated numbers within the string are then used to show a color. Is there any way to replace the simple hex colors with an image? For example else if (shape quot H quot ) return 8,8,8 , 8,8,8 , 8,8,8 The quot 8 quot ties into the following string to get the F10B38 color. const color null, quot FF2D00 quot , quot FF9300 quot , quot 51FF00 quot , quot 00FF93 quot , quot 0087FF quot , quot 4E49A7 quot , quot 9649A7 quot , quot F10B38 quot


In a browser, is it best to use one huge spritesheet or many (10000) different PNG's? I'm creating a game in jQuery, where I use about 10000 32x32 tiles. Until now, I have been using them all separately (no sprite sheet). An average map uses about 2000 tiles (sometimes re used PNG's but all separate divs) and the performance ranges from stable (Chrome) to a bit laggy (Firefox). Each of these divs are positioned absolutely using CSS. They do not need to be updated every tick, just when a new map is loaded. Would it be better for performance to use spritesheet methods for the divs using CSS background positioning, like gameQuery does? Thank you in advance!


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?


Same scroll speed across devices with different DPI I am creating a simple game in JS, something like the flappy bird ) For pipe scroll, I am using a linear tween. I noticed that the speed of the pipes are different across different smartphone screens, so the game has different difficulty. I observed that this has to do with different screen sizes and different pixels densities. What I did is I defined a duration per pixel, which is multiplied by the number of pixels the screen has. The duration per pixel, pixel duration is constant. So basically tween duration number of horizontal pixels pixel duration But this gives same speed in different sized browser windows on the (same) computer screen. If I use this approach on some device that has higher pixel density, the pipes will move slower, because there are more pixels, so this tween duration value gets larger, so tween gets slower. Then I learned of the devicePixel ratio value which can be used. So I try to factor this in the equation tween duration number of horizontal pixels pixel duration devicePixelRatio This devicePixelRatio is higher as screen DPI's goes higher and should solve my problem according to the docs, right? https developer.mozilla.org en US docs Web API Window devicePixelRatio However, this only helps a bit. There is still a noticable speed difference. Why is this not working, and how can I get the same scroll speed across devices in JS (in browser window) perhaps some other approach would do?


How to apply toastr notifications when user get leveled up? This question is about when user get leveled up the toastr will pop up. What I want to do is i want to put the toastr.js inside my script but I don't have idea how to implement. Link and Script lt link rel "stylesheet" href " asset("css toastr.min.css") " gt lt script src " asset('js toastr.min.js') " gt lt script gt Profile.blade lt script gt if(Session has('success')) toastr.success(" Session get('success') ") endif lt script gt Controller use Session while( user gt curr exp gt user gt exp needed) if( user gt level 10 user gt level 15 user gt level 20) user gt reward token 1 user gt curr exp user gt exp needed user gt prev exp user gt exp needed if( user gt level lt 19) user gt exp needed user gt prev exp 1.4 elseif( user gt level gt 20 amp amp user gt level lt 39) user gt exp needed user gt prev exp 1.1 elseif( user gt level gt 40 amp amp user gt level lt 59) user gt exp needed user gt prev exp 1.05 elseif( user gt level gt 60 amp amp user gt level lt 79) user gt exp needed user gt prev exp 1.04 elseif( user gt level gt 80 amp amp user gt level lt 99) user gt exp needed user gt prev exp 1.03 elseif( user gt level 100) user gt exp needed user gt exp needed 0 user gt level 1 Session flash('success','You leveled up!') user gt save() I'm using laravel framework 5.4.36 version. I'm confused how to display a live notifications on the user's profile every time they leveled up. Any ideas? Thank you


HTML5 game fps render lag I am currently creating a flappyBird like HTML5 game using Proccessing.js You can see current work here http files.tips4design.com flappySlothRelease The problem is that even though the FPS is 60 (or constant) there is an obvious shuttering in rendering. I have read a lot of game loop articles to solve this issue, but neither with Processing.js draw loop, browser's requestAnimFrame nor constant delta time the problem was solved. Now I use the variable deltaTime approach and Processing.js default draw() loop. delta now lastTime ... position position velocity delta I have been stuck for two days with this problem, and ca not really figure out how to fix the shuttering. Any help would be greatly appreciated! Thank you!


Launch event at the end of an animation with phaser 3 I'm starting to develop in Phaser 3, and I'm really a begginer. I'm trying to make an attack move of an archer sprite, but I cannot make it work right... This is how I have defined the things related to combat class Jugador extends Phaser.Physics.Arcade.Sprite constructor(escena, x, y) super(escena, x, y, quot jugador quot ) this.escena escena this.escena.add.existing(this) this.escena.physics.add.existing(this) this.createVariables() this.createControls() this.createAnimations() createAnimations() this.defineAttackAnimation() Some others... defineAttackAnimation() this.attackAnimation this.attackAnimation.key quot attack quot this.attackAnimation.frames this.escena.anims.generateFrameNames( quot attack quot , prefix quot attack quot , start 1, end 6 ) this.attackAnimation.frameRate this.attackFrameRate this.attackAnimation.repeat 1 var atkListener () gt this.arrow() this.escena.anims.create(this.attackAnimation) this.escena.anims.get( quot attack quot ) .addListener( quot animationcomplete quot , atkListener) arrow() console.log( quot arrow quot ) attack() if(this.body.onFloor() amp amp this.attackButton.isDown) this.setVelocityX(0) this.setVelocityY(0) this.play( quot attack quot , true) update() if ( this.body.onFloor() ) this.setVelocityY(0) this.facing() this.idle() this.walk() this.jump() this.attack() if (this.body.velocity.y lt 0) this.play( quot jump quot ) else if (this.body.velocity.y gt 0 amp amp !this.body.onFloor()) this.play( quot falling quot ) What I want to do is Player pushes the attack button. Attack animation plays. I would like it to be played untill it ends, but now I have to keep pushing the attack button. When attack animation ends, the function quot arrow quot is executes in order to make an arrow appear. Thanks in advance.


Double buffering on HTML5 Canvas game? My simple canvas game seems to work fine on Chrome and FF on Mac Linux. I haven't had chance to test it on smart phones or Windows environments yet. It doesn't use double buffering but I have seen some JS Canvas examples using it. When is the use of the double buffering recommended? Does it make difference only for specific browsers? Is there a significant performance hit? Thanks!


A logic error. canvas balls physics, bounce Hi I was making a program that simulate a bunch of balls bouncing, but the problem is some balls got stuck to the floor. Since it's a logic error, it is kind of difficult to find. Can someone help, I let the snipper code below thanks. var output document.getElementById('output') var canvas var ball canvas.obj document.getElementById('canvas') canvas.ctx canvas.obj.getContext('2d') canvas.width canvas.obj.width canvas.height canvas.obj.height canvas.clear function() canvas.ctx.clearRect(0, 0, canvas.width, canvas.height) canvas.preferences function() canvas.ctx.strokeStyle 'rgb(210,210,210)' canvas.ctx.lineWidth 1 const FRICTION .9 const MIN ACCELERATION 1 const FRICTION INCREASE .015 const DIST 20 const N BALLS 50 BALLS NUMBER const GROUND canvas.height var Object function() this.yVel 0 this.gForce 0.2 this.friction FRICTION this.full false this.run true this.draw function() canvas.ctx.beginPath() canvas.ctx.arc(this.x, this.y, this.radio, 0, Math.PI 2) canvas.ctx.stroke() this.physics function() this.y this.yVel if (this.y this.radio lt GROUND) this.yVel this.gForce else if (this.y this.radio gt GROUND amp amp this.yVel gt MIN ACCELERATION) this.yVel this.friction this.y GROUND this.radio this.friction FRICTION INCREASE else this.yVel 0 this.y GROUND this.radio this.run false var generateBalls function(p) var i, random for (i 0 i lt N BALLS i ) p i new Object() random Math.floor(Math.random() 18) 5 p i .radio random random Math.floor(Math.random() 22) 1 p i .x DIST random random Math.floor(Math.random() 15) 1 p i .y DIST random var drawBalls function() var i for (i 0 i lt N BALLS i ) ball i .draw() var applyPhysics function() var i for (i 0 i lt N BALLS i ) ball i .physics() generateBalls(ball) canvas.preferences() var program setInterval(function() canvas.clear() drawBalls() applyPhysics() , 1000 60) canvas border 1px solid rgb(210, 210, 210) body background black color rgb(210, 210, 210) lt canvas id "canvas" width "450" height "400" gt lt canvas gt lt p id "output" gt lt p gt


How to handle keyup events in game loop? I'm writing a simple game in JavaScript, which already handles basic keyboard input like so var input while (!done) handleInput(input) update() render() document.onkeydown function(e) input e.keyCode true document.onkeyup function(e) input e.keyCode false Now I need the game to handle key combos (like CTRL X for example). I would like it to accept such combos on keyup only. Two possible solutions that come into my mind are exposing an array containing a list of keyup events (object with "main" key plus modifiers). The handleInput function would be responsible for draining the queue every time it polls it keeping track of possible key combos inside handleInput (watching for held down modifier keys) and trigger the combo behavior when the "main" key goes up (I actually don't like this that much) Would you suggest me an elegant way to extend the current functionality?


Securing HTTP data from a JavaScript game to server Suppose I am doing a JavaScript game, and I wish the game to update the server if the user has successfully completes the game and his outcome. How should I ensure that the request came from the JavaScript game, and that the data sent has not been tampered with. I am using PHP as the server side language. I do understand that no strategies are going to be 100 fool proof, and any measures taken is more of a deterrence than absolute protection. On Edit Let's supposed we're not using server verification of each user's step (as in a traditional MMO). The game could be a mini game as part of a web game or educational game (space invaders or a real time game, for example) and requiring a server side component for each of those games could be tedious. Example Supposed, when the game is completed, a request is sent to the server via. AJAX game finished.php?user id 1 amp outcome success amp score 88 A user could 'fake' the server in believing that the game has been completed correctly by sending that request to game finished.php. How could this be made more difficult?


A Start path finding in HTML5 Canvas I'm trying implement A Start path finding in my games(which are written with JavaScript, HTML5 Canvas). Library for A Start found this http 46dogs.blogspot.com 2009 10 star pathroute finding javascript code.html and now I'm using this library for path finding. And with this library, I'm trying write a simple test, but stuck with one problem. I'm now done when in HTML5 canvas screen click with mouse show path until my mouse.x and mouse.y. Here is a screenshot (Pink square Player, Orange squares path until my mouse.x mouse.y) Code how I'm drawing the orange squares until my mouse.x mouse.y is http pastebin.com bfq74ybc (Sorry I do not understand how upload code in my post) My problem is I do not understand how to move my player until path goal. I've tried 'http pastebin.com nVW3mhUM But with this code my player is not beung drawn.(When I run the code, player.x and player.y are equals to 0 and when I click with the mouse I get the path player blink and disappear) Maybe anyone know how to solve this problem? And I'm very very very sorry for my bad English language. )


How do I check if one square is overlapping another in HTML5 canvas I have a little program that goes like this Whenever somebody presses space, a blue square appears. The blue square shouldn't overlap with any other blue square. But the function that is checking the overlap is not working! Can somebody please help? window.onload function() Starts the program when the page is loaded. var canvas document.getElementById("paper") var background canvas.getContext("2d") var squareDisplay canvas.getContext("2d") canvas.width window.innerWidth canvas.height window.innerHeight var xAndYvaluesOfSquares Makes a randint() function. function randint(min, max) return Math.floor(Math.random() (max min 1)) min function checkForOccupiedAlready(testXPos, testYPos) if (xAndYvaluesOfSquares.length ! 0) for (valuePair in xAndYvaluesOfSquares) if ( ( valuePair 0 20 ) lt testXPos amp amp ( valuePair 0 20 ) gt testXPos amp amp ( valuePair 1 20 ) lt testYPos amp amp ( valuePair 1 20 ) gt testYPos) If in the same area return false return true Makes a new square function makeNewsquare() var checkingIfRepeatCords true DO loop that checks if there is a repeat. do Makes the square x y positions var squareRandomXPos randint(50, canvas.width 50) var squareRandomYPos randint(50, canvas.height 50) Tests if that area is already occupied if (checkForOccupiedAlready(squareRandomXPos, squareRandomYPos) true) xAndYvaluesOfSquares.push( squareRandomXPos, squareRandomYPos ) checkingIfRepeatCords false while (checkingIfRepeatCords true) function resetBoard() for (i 0 i lt xAndYvaluesOfSquares.length i ) var XYvalue xAndYvaluesOfSquares i squareDisplay.beginPath() squareDisplay.fillStyle "rgb(50, 50, 125)" squareDisplay.rect(XYvalue 0 , XYvalue 1 , 50, 50) squareDisplay.fill() document.addEventListener("keydown", function (event) if (event.keyCode 32) Space key makeNewsquare() resetBoard() )


What Javascript game engines are out there, other than Impact? Does anybody know of a decent (meaning preferably free )) alternative to Impact? Any suggestions are very much appreciated!


Separating .js elements .js element communication So I have 2 questions regarding the code below function goldClick(number) gold gold number document.getElementById("gold").innerHTML gold function buyMiner() var minerCostG Math.floor(100 Math.pow(2.1,miner)) var minerCostW Math.floor(10 Math.pow(3.1,miner)) if(gold gt minerCostG) if(wood gt minerCostW) miner miner 1 gold gold minerCostG wood wood minerCostW document.getElementById('miner').innerHTML miner document.getElementById('gold').innerHTML gold document.getElementById('wood').innerHTML wood var nextCostMG Math.floor(100 Math.pow(2.1,miner)) document.getElementById('minerCostG').innerHTML nextCostMG var nextCostMW Math.floor(10 Math.pow(3.1,miner)) document.getElementById('minerCostW').innerHTML nextCostMW window.setInterval(function() goldClick(miner) , 1000) Question 1 Is it possible to separate these functions (goldclick, buyminer, window interval,) into their own documents so that if I have say, 50 different XXXXclick functions, and 50 buyXXXX functions and 50 interval functions, I have just 3 .js documents instead of 50. Question 2 If it is possible to separate them, how would I ensure that they are communicating with each other and variable values are not being confused or sent to the wrong lt span gt in the displaying html.


How do I play audio with Javascript? I want to add a short audio track to a game of concentration I'm coding. I want the sound to occur when the user has won the game. How do I go about doing this? I would really appreciate the help, thank you.


cocos2d js displays only one type of tile from a tmx file I am using Tiled to produce a tmx which I use in my code using cocos2d js. The problem is that when I run it on the browser, a wrong tile gets displayed, the first one of the image (0,0) and repeats for the whole map. The relevant js code is this this.farm new cc.TMXTiledMap(res.farm tmx) this.addChild(this.farm) where res.farm tmx the path to the tmx file. What could be the source of the problem? And how do I fix it? It seems to me that it is specific to my code. I do not find any other reports of the same problem.


How to update and render an 2D endless runner that goes bothways I want to make an 2D endless runner, that also allows player to go backwards. So I have to create random world as the map goes, also keep the old map in case player goes back. I ask about how to update and render this program. I am thinking having a generate function that takes an x value and generates world from x to (x chunk size) and when camera reaches x chunk size, call this function again to generate more map function source(x) generate world for x value And maybe use this function like let worldThings push the world from 0 to chunk size worldThings.push(...source(0)) called every frame to update world function update() if (camera.x gt chunkSize) generate more world worldThings.push(...source(chunkSize)) To render these something like object pooling for rendering things in view let renderPool new Pool() function render() release all objects renderPool.releaseAll() take things that are visible let renderThings worldThings.filter(thingsInCameraView) for everything allocate a resource in the render pool renderThings.each(renderPool.allocate) render the pool renderPool.each(renderThing)


Three.js camera turning leftside right In Three.js I am trying to implement an orbiting camera can be rotated around the x and the y axis. I am using these two functions function rotateX(rot) var x camera.position.x, y camera.position.y, z camera.position.z camera.position.x x Math.cos(rot) z Math.sin(rot) camera.position.z z Math.cos(rot) x Math.sin(rot) camera.lookAt(scene.position) function rotateY(rot) var x camera.position.x, y camera.position.y, z camera.position.z camera.position.z z Math.cos(rot) y Math.sin(rot) camera.position.y y Math.cos(rot) z Math.sin(rot) camera.lookAt(scene.position) Now the x rotation works fine but the y rotation does not. Once I go over the top of the model as in that the camera's z position becomes negative then suddenly the lookAt method rotates the camera by PI amount on the Z axis and suddenly the left side of the model is on the right and vice versa. Now I can fix this by checking for a negative Z and then just fixing the camera's rotation but this then causes a malfunction when using x ad y rotation at the same time, the x then suddenly gets this inverting behavior. How should I go about fixing this?


Optimize DOM game performance I am working on a game developed on DOM using Crafty JS framework, and Greensock GSAP JS (http www.greensock.com gsap js ) for animations. It is my first time working with these technologies. I have a problem with FPS going down to 15 and less while animations are performed on bigger DOM elements. After investigating the issue with Chrome Developer Tools Timeline I discovered that 80 of bottleneck events time are Image Resize(non cached) I assume it is caused by the fact that I am using CSS Transform scale() for the game to adjust to browser size. Performance is acceptable once the scaling is disabled. Is there any way to cache the resized images in browser to improve performance? The game will only be used on a local computer. Any help and advice will be greatly appreciated.


Path finding with identical values I have been reading up about path finding and find it all very confusing, however this is probably the best I have found for a logical explanation Path If the cost of two nodes has the same value, I'm not sure how the path would be worked out though. How would it be worked out?


How can I tweak this A search pathfinding algorithm to handle different terrain movement values? I'm creating a 2D map based action game with similar interaction design as Diablo II. In other words, the player clicks around a map to move their player. I just finished player movement and am moving on to pathfinding. In the game, enemies should charge the player's character. There are also five different terrain types that give different movement bonuses. I want the AI to take advantage of these terrain bonuses as they try to reach the player. I was told to check out the A search algorithm (http en.wikipedia.org wiki A search algorithm). I'm doing this game in HTML5 and JavaScript, and found a version in JavaScript http www.briangrinstead.com blog astar search algorithm in javascript I'm trying to figure out how to tweak it though. Below are my ideas about what I need to change. What else do I need to worry about? When I create a graph, I will need to initialize the 2D array I pass in passed on with a traversal of a map that corresponds to the different terrain types. in graph.js "GraphNodeType" definition needs to be modified to handle the 5 terrain types. There will be no walls. in astar.js The g and h scoring will need to be modified. How should I do this? in astar.js isWall() should probably be removed. My game doesn't have walls. in astar.js I'm not sure what this is. I think it indicates a node that isn't valid to be processed. When would this happen, though? At a high level, how do I change this algorithm from "oh, is there a wall there?" to "will this terrain get me to the player faster than the terrain around me?" Because of time, I'm also debating reusing my Bresenham algorithm for the enemies. Unfortunately, the different terrain movement bonuses won't be used by the AI, which will make the game suck. I'd really like to have this in for the prototype, but I'm not a developer by trade nor am I a computer scientist. D If you know of any code that does what I'm looking for, please share! Sanity check tips for this are also appreciated.


Can "dumbphones" play JavaScript games? Are JavaScript games exclusive to modern smartphones, or are older phone models also able to play games written in JavaScript?


Creating an Isometric tile map with HTML5 I'm trying to create an isometric tile map using HTML5 Canvas. Everything I've found online points me towards using a pre built engine. I'd like to learn how to do this without using an engine. Is it possible to do this? If so, how? Would I need to look into WebGL?


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?


Implement resolution scaling HTML5 canvas I'm building an hmtl5 real time game using socket.IO and node.js. If you've heard of the classic game "pong", I'm going for that. When you consider the gameplay for this game, it becomes apparent that resolution scaling is something I'll have to implement. I'm running one instance of the game on the server (no graphics rendering, only physics), and of course once for every client. Each client's canvas is the size of the browser window so could be any resolution. What I'm wondering is how I should keep track of positions, velocities, etc. in the core game code. Should I use percentages and then multiply them by the respective screen sizes? Like x 0.5 to store a position halfway across the screen? What's the best standard way of doing this? Thanks so much.


Image Not Loading Crafty.js I am experimenting with Crafty.js, and I have called .image() on an entity, and the image is not loading. When I look through the web inspector, I can see that the cloud entity exists, and that the cloud image is found, but it is not showing up. What is the proper way to load an image on an entity, and what is wrong with my code? mainCrafty.js Crafty.e('myCloud, 2D, DOM, Image') cloud .attr( x 300, y 10, w 45, h 30 ) .image('images cloud.png') Here is the directory structure index.html images cloud.png scripts crafty.js mainCrafty.js


For timed levels, how do you determine time steps that are less than 1 (frames per second)? I have made a simple HTML5 racing game. The laps are timed. I am running the game are 40 frames per second, each frame represents 40 milliseconds. There for my timer will increase in 0.025 increments. My question is how can I get my timer to record lap times more accurately, without running at 100 frames per second! How do other games do it? Could it be to do with gauging the distance from the car to the finish line in the frame before and after it crosses the finish line?


How do I make sure my tic tac toe AI always plays to a draw? I'm working on a little project. The aim is to play Tic Tac Toe against an AI, but I require that the game always results in a draw against the AI opponent. How can I implement the AI to ensure that?


Simulating Enums with Javascript When developing in Javascript, it seems useful especially for event systems to use enum likes, but not string comparison for performance considerations (also because it doesn't protect against typos). How do you use Enums in JS? Should I switch to Typescript?


Online Multiplayer cheating w delta time movement I'm making a multiplayer game with basic linear movement and interpolation. I've read gabriel's article about client side prediction and server reconciliation and have tried applying it to my own. My server is supposed to be authoritative, but I am worried clients can still exploit the system. The system works like this the client sends timestamped input to the server at 60hz the server runs at 30hz. Each tick it applies all the input since last tick and uses a time delta calculated from the client side input packets to determine movement (e.g. entity.x message.delta speed). The server then sends a timestamped state back to all clients. the client receives a timed state from the server and applies the "authoritative" positions. My concern is with step 2. Because player movement relies on the client's delta time, I'm afraid they can cheat by sending a "fake delta time" to the server and additionaly spam input messages quicker to make them move faster in game. If I remove the delta time altogether, the game will appear "jumpy". How can I resolve this issue?


How would I process accelerometer data to use it for camera rotation? I'm using Three.js to make a web based 3D first person game. I would like the player to be able to control the camera rotation with their device's accelerometer. The sensor data is received via the DeviceMotionEvent event listener. Here is an example of what it returns How should I proceed with this?


PhaserJS Detecting intersection I'm making a card game to get my legs with phaser. I have an row of overlapping, face down cards. I want to detect when any card is covered by another card. The deck is shuffled before being placed on the board, so the order is known card 1 thru card 54 . It goes card.events.onInputDown.add(tap, this) on each card during setup to detect interaction, and then calls tap(this) function tap(pointer) console.log(pointer.z) let zpos pointer.z if (Phaser.Rectangle.intersects(pointer, abovecard )) console.log("covered") else pointer.play("front") anim to show the card back (abovecard is asterisked as a placeholder because I'm not sure what to put there) A simple boundary overlap check seems to be the model to use. But when I go abovecard card zpos 1 , it doesn't see a card above it. Even when I do in the console Phaser.Rectangle.intersects(card 37 , card 38 ), which are visibly overlapping, it says false. Primary question What am I missing here? 2ndary question Is there a better way, than what I've described, to detect if one sprite is overlapping another sprite (whether the other sprite is known or not)?


How to do monster AI movement and attacks server side? I have my web based rpg game already created. Inventory management, equipment system, character stats, skill tree, and etc. It's almost complete. For the game world, I am creating a top down rpg character movement and combat. With point and click. You click on a part of the map (in this case, it's a image, and your character .png image transitions to that spot). It's with Javascript and PHP. I'm using a PHP Websocket server. I have it where players can only move up to 200 pixels per each click. Each click is essentially a packet being sent to my gameserver. Then the gameserver validates if it's a valid input (1235x1235) format, and spits it out to other players in that specific game. (So it's a consistent world map). This works perfect. My question is If I want to incorporate a monster that has AI and starts to attack the character... I can do that with javascript easily with setInterval or setTimeout functions (to make the mob move and then attack the character). But how do I do that serverside? Because a user could just press F12 and edit the javascript to stop the mob from attacking. But, I need the mob to attack the player every xxx milliseconds serverside as well. How is this done with PHP? I feel like I need some type of heartbeat going on where it's a constant check between client and server every xxx seconds? I might be going off on the deep end and I'll stop talking lol. But I hope you get the jist of it. Any ideas are greatly appreciated. Another thought Think of Diablo 2 or Path of Exile, and using a hack that just stops mobs from moving towards your character and attacking it. Is that just an illusion? And the "auto attacking" is done serverside regardless if you've stopped that mob on the client, right? If so, how to accomplisgh this with a PHP Websocket server, and some JS? I'm not looking for code, just an application theory or design process would help! ) P.S. It's either I go this route, or the game becomes a simple real time strategy pokemon style combat. Which I really, really don't want...


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


Check legal movement on grid map i'm trying to develop a simple multiplayer turn base game, i'm start creating the grid map, i have already write the javascript script to display the range movement for the specific unit, but my problem is how to check if the grid position sent to server by the client is a valid position, i think this is a operation to do on server side (i use php) because javascript is easy editable by the user, my first throught is to save in a database each tile and its data (example is a water tile, a forest tile...), so when the position is send to server i can read the db and check if the position is valid, but i think this method is very slow and require a lot of server resources, so there is a better way to do this? (i don't know if this is the correct site or is a question for StackOverflow)


Anti cheat Javascript for browser HTML5 game I'm planning on venturing on making a single player action rpg in js html5, and I'd like to prevent cheating. I don't need 100 protection, since it's not going to be a multiplayer game, but I want some level of protection. So what strategies you suggest beyond minify and obfuscation? I wouldn't bother to make some server side simple checking, but I don't want to go the Diablo 3 path keeping all my game state changes on the server side. Since it's going to be a rpg of sorts I came up with the idea of making a stats inspector that checks abrupt changes in their values, but I'm not sure how it consistent and trusty it can be. What about variables and functions escopes? Working on smaller escopes whenever possible is safer, but it's worth the effort? Is there anyway for the javascript to self inspect it's text, like in a checksum? There are browser specific solutions? I wouldn't bother to restrain it for Chrome only in the early builds.


How do I change the level of my game by changing the file loaded? I am making this 2d canvas game in JavaScript and I want to switch to file level2 level2.html when the boss of level 1 (level1 level1.html) is dead. This way I can have my stuff organized better. This is the condition statement where I want to put the file change. if(e.bosshealth lt 0) enemies alert("LEVEL 1 COMPLETED") I want the file switch to be here if possible.


Configurable Dice Cup Sound Effect for HTML5 Game I am developing an HTML5 javascript based game, where the players will have to roll virtual dice. I am working on a 3d model of a dice Cup and plan on having the users shake it and turn it upside down in order to roll the dice. I would like some realistic sound effects to go along with this interaction, but do not know how to achieve this. The problem is that the number of dice, the duration, intensity and speed of the dice cup shake will vary. Consequently, I don't think I will be able to create a convincing sound experience by using a prerecorded sound effect. How does one deal with making such sound effects configurable?Would I need to programmatically generate the sound using the web audio API? If so I would be grateful for any pointers as to how to do it.


How do I fix these touch events? Events respond if there are 2 fingers but not 1 I am making a simple game of mine mobile friendly. The goal is to Make character walk if a touchstart event is sensed on right half of screen. Stop character if a touchend event is sensed on the right half. Jump the character if a touchend event happens on the left half of the screen. I have the logic working perfectly for mouse up and down events so I'm pretty sure it's something to do inside the touchstart and end functions. If two fingers are used as one press it seems to work fine. If only one finger is used it doesn't work properly touching anywhere starts the movement but nothing will stop it. Here is the code for the touch inputs and associated function CheckWhichScreenHalf function(e) loc WindowToCanvas(e.pageX, e.pageY) onScreenY loc.y gt 0 amp amp loc.y lt gameCanvas.height leftSideX loc.x gt 0 amp amp loc.x lt gameCanvas.width 2 rightSideX loc.x gt gameCanvas.width 2 amp amp loc.x lt gameCanvas.width if (onScreenY amp amp leftSideX) return 'left' else if (onScreenY amp amp rightSideX) return 'right' else return 'neither' TouchMove false TouchJump false gameCanvas.ontouchstart function(e) if (imagesHaveBeenLoaded) e.preventDefault() for (var i 0 i lt e.touches.length i ) var side CheckWhichScreenHalf(e.touches.item(i)) if (side 'right') TouchMove true gameCanvas.ontouchend function(e) if (imagesHaveBeenLoaded) e.preventDefault() for (var i 0 i lt e.touches.length i ) var side CheckWhichScreenHalf(e.touches.item(i)) if (side 'right') TouchMove false else if (side 'left') playerJumping true The game can be played here http webstudentwork.com jgossling MMWD mp2 mp2.html


Phaserjs, filters, save to image cache I've tried to apply a Pixi filter to a image and save it to cache but the image doesn't get saved with the filter. colorMatrix new PIXI.ColorMatrixFilter() colorMatrix.matrix 0,0.0,0.5, 0.2, 0,0,1.0, 0.2, 0.0,0.0,0.5, 0.2, 0.0,0.0,0.0,1 image game.make.bitmapData() image.load("testImage") image.filters colorMatrix game.cache.addBitmapData("testImageWIthFilter", image) Is it not possible to save it to cache? The only thing I see is the original image when using the code down below messageImage game.add.sprite(0, 0, game.cache.getBitmapData('testImageWIthFilter'))


What audio method works across all web browsers and mobile for HTML5 JavaScript? I have looked at a number of ways to trigger audio in HTML5 JavaScript, but each time I find something that might be workable, I find web browsers and mobile devices it doesn't work on at all. What is considered the best method that works across all web browsers and mobile for creating a game with sound using HTML5 JavaScript? What do experienced interactive game programmers do? Do you check the user's web browser or mobile device and serve up different code to make it work? Or do you have a single solution for this? Or do you warn the user by supplying a list of web browsers and mobile devices the software is known to work with? Additional Information I found out that audio in some web browsers, like Safari on the Mac, it will load the audio file each time it is triggered, which causes a problem. I saw once solution using what is called Audio Sprites https phaser.io examples v2 audio audio sprite This way, you load one audio containing all your sounds needed, and then you pass a pointer to where in the audio file to start playing the sound and where to stop. That sounded like a solution, but this doesn't work on the Safari web browser, it produces no sound at all. Then I looked into Web Audio API, and this is impressive https forestmist.org share web audio api demo While this worked on the Mac for Safari, Firefox and Google Chrome, and the iPhone, it doesn't work on Windows with Internet Explorer (or Safari on Windows either). I've not tested Web Audio API on the android phone yet, because I don't have access to one at the moment. So I was wondering what experienced interactive programmers do to provide audio to work across most or all platforms? It seems a huge step backwards to have to alert visitors to a website that they can only use the functions on it by using a short list of web browsers. The issues as I see it seem to have to do with being able to load the audio file and not have it re loaded over the internet each time it is referred as play(). I realize Web Audio API might provide much more capability than most of us needs, but is that the current gold standard for audio in a HTML5 JavaScript game? Here is a simple example, using audio that works on Google Chrome Mac, but it doesn't work on Safari Mac https rawgit.com mehaase js typewriter master example3 typewriter index.html


Collision detection between two arrays with nested loops why do I get a crash? I'm creating a game where waves of enemies are coming to me and I have to kill them. So far, I'm doing great it took me hours to come up with this nested loop to check for collision detection and when I ran it the game was running great... but for a few kills only. Sometimes I manage to play it even for a few minutes until it crashes, sometimes I shoot twice and it crashes, and I always get this error "Uncaught TypeError Cannot read property 'x' of undefined at collision (collision.js 6)" I just cannot figure out whats going on. If someone can help me I will be so grateful, I saw similar topic but I couldn't find the answer there. function collision() for(var l bullets.length 1 l gt 0 l ) for( var k enemies.length 1 k gt 0 k ) var e enemies k var b bullets l if(b.x gt e.x amp amp b.x lt e.x e.imgWidth 4 amp amp b.y gt e.y amp amp b.y lt e.y e.imgHeight 4 ) e.enemiesHealth 50 b.deletion() basically assigns true to b.toDelete e.deletion() basically assigns true to e.toDelete else if (b.toDelete) bullets.splice(l, 1) else if(e.toDelete amp amp e.enemiesHealth 0) enemies.splice(k, 1) kills 1


Why is my spritesheet displaying all messed up in game? I'm having an issue I don't quite understand, where my spritesheet is looping strangely and not showing the full sprite I want, even though I feel like I'm specifying it correctly. My code is in phaser.js. Example https imgur.com a xJ95Qbj My code for it is as follows this.load.spritesheet('dude', 'assets bunny.png', frameWidth 32 , frameHeight 42 ) this.anims.create( key 'left', frames this.anims.generateFrameNumbers('dude', start 56, end 64 ), frameRate 5, repeat 1 ) this.anims.create( key 'turn', frames key 'dude', frame 4 , frameRate 20 ) this.anims.create( key 'right', frames this.anims.generateFrameNumbers('dude', start 40, end 48 ), frameRate 5, repeat 1 ) Look fine on the 'turn' frame, but not so fine on movement. For reference, here's the spritesheet I'm attempting to use https imgur.com Rzi5i7Z


How to trim a sprite? I have a spritesheet var spriteSheet new createjs.SpriteSheet( ... frames width 520, height 600, regX 260, regY 300 ... ) I am computing it's physics body as follows var bounds entity.sprite.getTransformedBounds() halfWidth bounds.width 2, halfHeight bounds.height 2, ... Create the physics body The result The ground is a solid body, and the sprite is dynamic. I would like the sprite's feet to touch the actual ground and get rid of the whitespace around the sprite (above, below and sides). The problem is that there is whitespace in the spritesheet. Each frame is 520x600 in the sheet. I have lots of frames and I would rather not go through each of them to figure out each one's exact dimensions. Is this possible? Also I'm new to game dev, it's very fun. Is this what applications like TexturePacker are for?


is this approach correct to make my game framerate indipendent in javascript? this is what i did my game loop is run every REFRESH milliseconds loop setInterval(tick,REFRESH) in the loop i calculate how much time is passed since last tick and subdivide that for how much time i expected to be passed var now performance.now() var elapsedTime now lastTick var delta time REFRESH lastTick now and every time based action that should happen every tick is "scaled" with the delta factor, for example my movement code var distance ball.dest.x ball.x var movement distance speed ball.x movement will have movement multiplied with delta


How to find and send data about on screen players to a client in a real time multiplayer game? I'm surprised I couldn't find much information on this. I am making a top down browser game in which the players see a small section around their player (see the image). Since the player doesn't need to render the players far away that they can't see, it would be unnecessary to send data about them. I want to know how the server should calculate who is near enough to the client that they appear on their screen and therefore receive data from the server about those players. The way my problem differs from what I have found is that I need to track many players (at least 50 and preferably up to 100) and many can be on screen at one time (assume a maximum of 10 on screen at any one time). Some assumptions considerations that are made The players are always moving and positions constantly changing Must handle at least 50 players at one time (preferably up to 100) Players can drop in and out at random locations so should be able to adapt to this quickly Screen sizes vary Player input is just movement (but there should be scope for other simple actions) Data sent over TCP as will be browser based Node.js server Initially I thought about sending data for all the positions of the players to each player but this seems like a terrible idea with so much unnecessary data being sent from what I understand the server should be sending as little as possible. My current strategy (shown in the image) is to have the server periodically (every second for example) calculate the distances between all players to determine those near enough to each other to appear on screen. For the next second, data will only be sent to the client regarding those near it. After the next second, new distances are calculated to decide what to send (and render) for each player. Some problems to take into account A lot of calculations must be performed by the server for all the players Extra information would need to be sent about players just outside the screen to account for any movement between updates Interpolation would probably be required Different screen sizes will mean that some players can see more than others (the fairness isn't the issue here, but tracking to what distance to let players see) The main issue is the ability of the server to process all of this with everything else that it must already do. I am not convinced this is a very good way. This is trivial for off screen entities in a single player game, however for multiplayer games with many players moving at once this becomes much more difficult. How can I figure out what players are on screen efficiently and what data should be sent regarding this? Or please point me to where I can find information on this.


Passing a list of existing entities to a new client when using a component system? My game server uses entities containing components to represent everything in the game world. This has worked great so far but I've run into a problem now that I'm allowing clients to connect to the server. Basically the server needs to tell the connecting client about all the existing entities in the game, Since the player, the monsters, the trees etc. are all instantiated from the same Entity class I currently have no way of telling the client what each entity actually is. What would be the best way of sending the entities to the client so that the client knows what components to add to each? The only thing I can think of is having a string "name" on the entity and then sending packets like this to the client... 'action' 'create entity', 'data' 'entity type' 'dragon', 'x' 300, 'y' 40, So now the client would know to call the "createDragonEntity" function to create the correct entity. Any better suggestions?


canvas ball physics animation I want to animate ball in html canvas like this. ctx.beginPath() ctx.arc(75, 75, 10, 0, Math.PI 2, true) ctx.closePath() ctx.fill() start position is left top corner and ball's maximum height position is always the same also I don't want to use javascript physics libraries thanks


What happened with server code on deployment to Heroku I'm starting to learn about making games on the web and am using this agario clone on GitHub to help. I've succeeded in setting up a version on Heroku using the instructions from here. I've never used Heroku before, so I'm a little lost on a few more things. The link from the instructions allowed the files to be directly transferred from GitHub. However, I can't seem to view them at all from Heroku I can only run the client with 'Open app' (which works). What exactly happened when I deployed the app? Did Heroku immediately start running the server code and will it continue to indefinitely do so even if no clients are connected?


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!


How do I rotate individual shapes on an html5 canvas? So I am doing a basic Asteroids clone as an intro to HTML5 canvas. I want to be able to rotate the main player while leaving the other objects on screen alone. Currently I am using transform and rotate on the canvas to allow the player to move, which works well.. but since it rotates the entire canvas it affects other shapes on screen. Is the general way to do this, to instead have each shape keep track of its own positions and perform manual transformations on the shape itself while leaving the canvas alone? Can I possibly give my shape a CSS class and control it on its own that way? Should I be using more than 1 canvas so that I can control rotations individually? Not sure what the accepted way is to handle multiple on screen images shapes all with their own movement and rotation patterns simultaneously. My gut is telling me to have each shape track its own positions and just perform the math on the shape object itself... but then I would not be using the Canvas APIs rotate at all. My app currently https jsfiddle.net 0o2pwLhn And a code snippet for the rotation player draw test function drawShip() ctx.beginPath() ctx.moveTo(shipStartX, shipStartY) ctx.lineTo(shipStartX 8, shipStartY 20) ctx.lineTo(shipStartX, shipStartY 15) ctx.lineTo(shipStartX 8, shipStartY 20) ctx.lineTo(shipStartX, shipStartY) ctx.translate(shipStartX, shipCenterY) ctx.rotate((Math.PI 180) shipMoveDegree) ctx.translate( shipStartX, shipCenterY) ctx.stroke() ctx.closePath() Do the save() and restore() methods on the CanvasRenderingContext2D maybe come into play here? I have tried experimenting with it but havent gotten anywhere. I tried using save() and restore() but the issue is that once I restore, the player just gets set right back to its original spot.. since I am never actually changing its position... just rotating the entire canvas. The similar question here Is it possible to rotate an image on an HTML5 canvas, without rotating the whole canvas? explains how to use save() and rotate() which I think is on the right track.. but does not solve the issue I have because the player location is reset back to the start when the key is lifted, because I set the degrees back to 0 on keyup. How can I maintain the current rotation of a single shape regardless of the rest of the canvas?


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.


HTML5 canvas screen to isometric coordinate conversion I am trying to create an isometric game using HTML5 canvas, but don't know how to convert HTML5 canvas screen coordinates to isometric coordinates. My code now is var mouseX 0 var mouseY 0 function mouseCheck(event) mouseX event.pageX mouseY event.pageY which gives me canvas coordinates. But how do I convert these coordinates to isometric coordinates? I am using 16x16 tiles.


align local Y to be parallel with global Y during or after slerp I am using the following function to have a globe rotate a point on its surface to face the global Z toward the camera. This works fine, but after each rotation the Y axis seen as a green line is not vertically aligned. I believe this is how slerp between two unit vectors works, it takes the shortest path. I would like to know how can I achieve this rotation whilst getting the globe to rotate itself so that Y is at least parallel to the global Y? function rotateToHub(continent) var speed 2000 var z new THREE.Vector3(0, 0, 1) point continent.position.clone().normalize() var q new THREE.Quaternion() q.setFromUnitVectors(point, z) var duration t 0 var tween new TWEEN.Tween(duration) .to( t 1 , speed) .onStart(function() slerp true ) .onUpdate(function() earthContainer.quaternion.slerp(q, this.t) ) .onComplete(function() slerp false update() ) .start()


Isometric tilemap circle around object I am developing an isometric game like Anno 1602. I have an isometric tilemap. The default tilesize is 64x31. My goal is to show the area a building has influence to. For that I want to show a circle in isometric style around that building. Look at the picture below I need to find an algorithm which turns information about a building (width, height, radius in tiles) into a polygon containing screen coordinates of the outer parts of the dark area (see picture, I want the red points). For example, the data for the picture above would be w 2 h 2 r 3 I tried creating circles with midpoint algorithm for each tile of the building. Merging all points together and running concave hull algorithm to get the outer most points. But this did not yield nice results. What could be an approach to get points to create a polygon which resembles an isometric area around an object.


Getting an object to move in another objects direction I have a player and an enemy, both have x and y values, and I want to move the enemy to the player and have them 'touch' over time in a speed that I can determine, I tried calculating the angle between the enemy, the player, and the 0, 0 point on the canvas using trigonometry but it just doesn't work right, most the times the angle is Not A Number(NaN) or goes in a direction different that the player. The code is not in the same file, I copy pasted the relevant parts of the code and pasted them together. Here is my code, any help would be greatly appreciated Creating a visual triangle and storing the length of it's vertices distance(size) line(enemy.x, enemy.y, 0, 0) lineOne dist(enemy.x, enemy.y, 0, 0) line(player.x, player.y, 0, 0) lineTwo dist(player.x, player.y, 0, 0) line(player.x, player.y, enemy.x, enemy.y) lineThree dist(player.x, player.y, enemy.x, enemy.y) Calculating the angle itself using the cosine rule angle acos((lineThree lineThree lineOne lineOne lineTwo lineTwo) (2 lineThree lineTwo)) Function to move the enemy(based on a suggestion made in this website) this.move function() if(angle ! NaN amp amp angle gt 0) this.x 2 cos(angle) sin(angle) 2 this.y 2 sin(angle) cos(angle) 2 The if statement that checks if the angle is not a NaN value is required because it happens a lot for some reason, it also checks if it is bigger or equal to zero, because if it isn't the enemy just doesn't show at all. Thank you for your time!


JavaScript canvas remove image I'm writing a platformer and I want to implement own art, now I know how to display it and this isn't my question. It rather is how do I remove it? I tried drawing a rectangle over it and removing it, but that doesn't seem to work, here's my code function clearImage(id) for (var i 0 i lt 6 ) if (img id i id) console.log(img loc x i ) console.log(img loc y i ) ctx.fillRect(img loc x i , img loc y i , "1000", "1000") ctx.clearRect(img loc x i , img loc y i , "1000", "1000") img loc x i null img loc y i null img id i null console.log("Cleared image with id " id " succesfully!") else i I'm using some arrays to store the image data such as the location and an id form management, but I didn't implement a method yet to get the dimensions of it, thats why I'm giving it the size parameters. (Strangely it works if I enter the fillRect and clearRect commands in the console)


How to add a collision function to a game Ive tried a few things but i cant get a working function if player collides with object set speed to 0( stop moving) ive tried to use the function under "game over " and change the things to make speedx 0 and speedy 0 but i couldnt format it correctly. https www.w3schools.com graphics game obstacles.asp my code lt html gt lt head gt lt meta name "viewport" content "width device width, initial scale 1.0" gt lt style gt canvas border 4px solid d3d3d3 background color f1f1f1 lt style gt lt head gt lt body onload "startGame()" gt lt script gt var myGamePiece var endGoalPiece function startGame() myGameArea.start() myGamePiece new component(30, 30, "red", 0, 0) endGoalPiece new component(30, 30, "black", 450, 240) myObstacle new component(10, 200, "green", 300, 120) var myGameArea canvas document.createElement("canvas"), start function() this.canvas.width 480 this.canvas.height 270 this.context this.canvas.getContext("2d") document.body.insertBefore(this.canvas, document.body.childNodes 0 ) this.interval setInterval(updateGameArea, 20) window.addEventListener('keydown', function (e) myGameArea.key e.keyCode ) window.addEventListener('keyup', function (e) myGameArea.key false ) , clear function() this.context.clearRect(0, 0, this.canvas.width, this.canvas.height) function component(width, height, color, x, y) this.gamearea myGameArea this.width width this.height height this.speedX 0 this.speedY 0 this.x x this.y y this.update function() ctx myGameArea.context ctx.fillStyle color ctx.fillRect(this.x, this.y, this.width, this.height) this.newPos function() this.x this.speedX this.y this.speedY function updateGameArea() myGameArea.clear() myGamePiece.speedX 0 myGamePiece.speedY 0 if (myGameArea.key amp amp myGameArea.key 37) myGamePiece.speedX 1 left if (myGameArea.key amp amp myGameArea.key 39) myGamePiece.speedX 1 right if (myGameArea.key amp amp myGameArea.key 38) myGamePiece.speedY 1 up if (myGameArea.key amp amp myGameArea.key 40) myGamePiece.speedY 1 down myObstacle.update() endGoalPiece.update() myGamePiece.newPos() myGamePiece.update() lt script gt lt p gt use the arrow keys on you keyboard to move the red square. lt p gt lt body gt lt html gt https jsfiddle.net tmanrocks999 e6w9br2s 178 I expect when the player hits the obstacle for them to stop moving. but at the moment they go through it i have 1 amp amp that prevents it from going past the x location of obstacle but that doesn't work right


Having trouble swapping elements I'm trying to visualize a simple Hanoi solver that uses an algorithm, and I'm swapping elements on array to visualize it. Here's my code let A let B let C let moveCount 0 let once true hanoi(3, A, C, B) 3, how many disk A C B are rods alert(A '. n' B '. n' C '.') function hanoi(n, start, target, other) if (once) once false for (var i 1 i lt n i ) start.push(i) if (n lt 1) let temp start n 1 start n 1 target target.length start start.filter(Boolean) target target.length temp target target.filter(Boolean) console.log('Moving disk ' n ' from rod ' start ' to ' target ' rod') moveCount else hanoi(n 1, start, other, target) let temp start n 1 start n 1 target target.length start start.filter(Boolean) target target.length temp target target.filter(Boolean) console.log('Moving disk ' n ' from rod ' start ' to rod ' target) moveCount hanoi(n 1, other, target, start) The C value should be expected 3, 2, 1 but only shows 2. I also checked A and B and 1 is nowhere to be found How do I make this properly so the output would be 3, 2, 1 Imagine 3 is the largest disk and so on...


How to determine where on a path my object will be at a given point in time? I have map and an obj that is meant to move from start to end in X amount of time. The movements are all straight lines, as curves are beyond my ability at the moment. So I am trying to get the object to move from these points, but along the way there are way points which keep it on a given path. The speed of the object is determined by how long it will take to get from start to end (based on X). This is what i have so far get now() returns seconds since epoch var timepassed get now() myObj id .start seconds since epoch for departure var timeleft myObj id .end get now() seconds since epoch for arrival var journey time 60 this means 60 minutes total journey time var array 650,250 way points along the straight paths if(step 0 step lt array.length) var destinationx array step 0 var destinationy array step 1 else if( step array.length) var destinationx 250 var destinationy 100 else var destinationx myObj id .startx var destinationy myObj id .starty step When the user logs in at any given time, the object needs to be drawn in the correct place of the path, almost as if its been travelling along the path whilst the user has not been at the PC with the available information i have above. How do I do this? Note The camera angle in the game is a birds eye view so its a straight forward X Y rather than isometric angles.


determine collision angle on a rotating body update new diagram and updated description I have a contact listener set up to try and determine the side that a collision happened at relative to the a bodies rotation. One way to solve this is to find the value of the yellow angle between the red and blue vectors drawn above. The angle can be found by taking the arc cosine of the dot product of the two vectors (Evan pointed this out). One of my points of confusion is the difference in domain of the atan2 function html canvas coordinates and the Box2d rotation information. I know I have to account for this somehow... SS below questions Does Box2D provide these angles more directly in the collision information? Am I even on the right track? If so, any hints? I have the following javascript so far Ship.prototype.onCollide function (other ent,cx,cy) var pos this.body.GetPosition() collision position relative to body var d cx pos.x cx var d cy pos.y cy length of initial vector var len Math.sqrt(Math.pow(pos.x cx,2) Math.pow(pos.y cy,2)) body angle can over rotate hence mod 2 Pi var ang this.body.GetAngle() (Math.PI 2) vector representing body's angle same magnitude as the first var b vx len Math.cos(ang) var b vy len Math.sin(ang) dot product of the two vectors var dot prod d cx b vx d cy b vy new calculation of difference in angle NOT WORKING! var d ang Math.acos(dot prod) var side if (Math.abs(d ang) lt Math.PI 2 ) side "front" else side "back" console.log("length",len) console.log("pos ",pos.x,pos.y) console.log("offs ",d cx,d cy) console.log("body vec",b vx,b vy) console.log("body angle ",ang) console.log("dot product",dot prod) console.log("result ",d ang) console.log("side",side) console.log(" ")