Taking a 2D slice of a 3D volume I have a regular 3D polygon and I'd like to display 2D slices of it. What is the best way to achieve this? (Preferrably in OpenGL, but a general algorithm tecnique would be good as well). I've already tried by using a camera with narrow z near z far values, but that doesn't seem like a good solution. I don't know if this could be implemented with a custom shader. Edit An example of what I'd like to do Kind of the opposite of what is commonly known as 'Volume Rendering'. Here's an older example http answers.unity3d.com questions 941826 2d slice from a 3d cross section slice.html


Normal Mapping space confusion I've been reading today about normal mapping. Up to now, the only normal mapping I encountered was with maps already in world space so I just extracted the info from the texture and transformed them with the normal matrix. Now I wanted to try to use a normal map that is in tangent space, but I immediately became really confused. What I've in my code up to now is Vertex Shader ... passedPosition modelViewMatrix vec4(vertexPosition,1.0) ... Fragment Shader vec3 V normalize( passedPosition .xyz) Eye vector ... vec3 L dir passedPosition .xyz lights i .lightPosition.xyz vec3 L normalize(L dir) ... And then proceed with my lighting calculations. All the tutorial I came across change all the light directions and the view vector into tangent space (in the vertex shader) and then extract the normal from the texture and keep going (in fragment). My issue here is that I'd like to avoid to access all my lights informations in the vertex shader, so my questions are Does make sense to pass to the fragment shader the t,b,n vectors so that I transform the light directions there? Should I consider access all my lighting informations in vertex shader (I have an array of Light struct which has more than just the position) and then passed them on to the fragment shader? Is something I'd like to avoid, but if is much better I can think of it. There is a way to perform normal mapping that is more compatible with what I've now (snippets above posted). Should I consider change my calculations from view space to world space? In that case, how can I perform normal mapping? Thanks


How to render a curved horizon when rendering terrain far away For games with long view distance, it might look at bit weird when you fly high above the ground and the horizon is all flat. So, how can I make a crumb bend effect, when I fly high above the surface? Can this be done in the shaders? If you're not sure what I mean, heres a picture A more clear example, though it might be captured with fish eye. What would this best way to do this? I believe you could rotate and move (using transformationMatrix) all vertices a tiny little bit according to how far they are from the camera. But would this even create the desired effect, and would it be too resource extensive? Or maybe you know a whole another way to do it.


Image speeds up while moving and or rotating instead of constant speed I'm having a problem with rotating moving an image. I've set one of my images to rotate on it's z axis buy updating the angle, but when I run my game, the image starts slowly starts to rotate from a stationary position as if to build up momentum. Once it reaches a certain speed, it begins to slow down to almost a stop, then repeats the process over. Furthermore, when it starts to rotate, it's rotating clockwise. But halfway before it stops, it's now rotating counter clockwise. If I were to only update it's x or y position or both, the image will move slow, then speed up to the desired speed, instead of moving at the desired speed at start. Lastly, if I were to rotate AND move the image, the image shakes erratically while rotating. My suspicion is that I'm calculating something wrong. Within Shader uniform mat4 projection uniform mat4 view uniform mat4 model .... gl Position projection view model vec4(position, 1.0) init() projection glm ortho(LEFT, RIGHT, BOTTOM, TOP, ORTHO NEAR, ORTHO FAR) mSprite.init("res texture foo.png", 1.0f) mSprite.setPosition(mPosition) mSprite.setRotation(rot, glm vec3(0, 0, 1)) glm vec3 pos(1.5, 0.5, 0.0) mSprite2.init("res texture bar.png", 1.0f) mSprite2.setPosition(pos) mSprite2.setRotation(0.0f, glm vec3(0, 1, 0)) update() mPosition.x 0.000005f mPosition.y 0.000005f mSprite.setPosition(mPosition) rot 0.0005f mSprite.setRotation(rot, glm vec3(0, 0, 1)) render() mShader gt start() mShader gt LoadProjectionMatrix(projection) mSprite.draw(mShader, view) mSprite2.draw(mShader, view) mShader gt stop() draw(Shader shader, glm mat4 amp view) (mSprite) shader gt LoadViewMatrix(view) shader gt LoadTransformMatrix(mModel) shader gt connectTexture(mTexture.id) Draw image... void setPosition(glm vec3 position) mModel glm translate(mModel, position) void setRotation(GLfloat angle, glm vec3 axis) mModel glm rotate(mModel, angle, axis)


Opengl create tunnel TRIANGLES and texture coords on a 3d path I have a path, lets say a bezier, or a circle. I d like to make a continously 3d cylinder (tunnel) on it (R 0.5f) How can I calculate tha TRIangles (TRIANGLE STRIP) coordinate, and the texture coords right?


Techniques for managing vertex buffer memory I'm learning OpenGL and I haven't seen any advice on managing vertex buffers in all of the tutorials I've read. The basic problem is that I have some memory allocated as a buffer B in which I'm going to store vertex data to send to the graphics card. Then I have the data that represents my domain D. This is the data that the game's simulation is run against. Let's say in a simple case it's just a list of 100,000 circles that will be moving around. Let's also assume that all of the data can, but might not, change every frame. Nothing is necessarily static. I'm looking for the techniques people use to efficiently fill B with D. I could create a new B each frame, but I imagine that would be very expensive. I could give every object in D a pointer to a location in B and have it update that pointer directly, but that strikes me as error prone as then I have to manage all of these pointers. I could also traverse D and fill a reused B every frame. This is what I'm currently leaning towards. The only problem here is that I'm forced to update every vertex in B every frame (because the location of the vertex data for a particular D could change within B) unless I come up with a more sophisticated scheme that guarantees that that an object in D always gets the same spot in B. So I can think of several options, but I'm wondering what people typically do. I imagine almost everyone has to solve this problem at some point.


Slick2D shader crashes, but only after a while I'm using Slick2D's ShaderProgram for shader based drawing in my game. Some players report that after 3 10 minutes, the game inevitably crashes hard during what appears to be a setUniform4f operation that's happened thousands of times before error occurred during error reporting (printing native stack), id 0xc0000005 Java frames (J compiled Java code, j interpreted, Vv VM code) J org.lwjgl.opengl.ARBShaderObjects.nglUniform4fARB(IFFFFJ)V J com.zarkonnen.airships.Appearance.draw(Lcom zarkonnen catengine Draw DDDDILcom zarkonnen catengine util Clr Z)V Full Log Why might this happen? Is it a transient problem, or maybe a driver issue? I'm confused that this happens not when the shader is bound, or when textures are set, but at the point of this utterly mundane operation of setting a 4f value. I'm in fact pretty lost here, as I can't even repro this on any of my own machines. This is the culprit function in its entirety public void draw(Draw d, double x, double y, double w, double h, int ms, Clr tint, boolean flipped) if (shaderLoadFailed) drawFallback(d, x, y, w, h, ms, tint, flipped) return if (tex null) tex loadTex(SPRITESHEET) if (tex null) shaderLoadFailed true if (sp null) try sp ShaderProgram.loadProgram( AGame.getGameDirectoryPath("data passthrough.vert"), AGame.getGameDirectoryPath("data frag.frag")) catch (Exception e) e.printStackTrace() shaderLoadFailed true if (shaderLoadFailed) return sp.bind() glActiveTexture(GL TEXTURE0) glBindTexture(GL11.GL TEXTURE 2D, tex.getTextureID()) sp.setUniform1i("tex", 0) if (tint null) sp.setUniform4f("tint", 1.0f, 1.0f, 1.0f, 1.0f) else sp.setUniform4f("tint", tint.r 255.0f, tint.g 255.0f, tint.b 255.0f, 1.0f) Img img frames.get((ms interval) frames.size()) glBegin(GL QUADS) if (flipped isFlipped) glTexCoord2d(img.srcX, img.srcY) glVertex2d(x w, y) glTexCoord2d(img.srcX, img.srcY img.srcHeight) glVertex2d(x w, y h) glTexCoord2d(img.srcX img.srcWidth, img.srcY img.srcHeight) glVertex2d(x, y h) glTexCoord2d(img.srcX img.srcWidth, img.srcY) glVertex2d(x, y) else glTexCoord2d(img.srcX, img.srcY) glVertex2d(x, y) glTexCoord2d(img.srcX, img.srcY img.srcHeight) glVertex2d(x, y h) glTexCoord2d(img.srcX img.srcWidth, img.srcY img.srcHeight) glVertex2d(x w, y h) glTexCoord2d(img.srcX img.srcWidth, img.srcY) glVertex2d(x w, y) glEnd() sp.unbind() TextureImpl.bindNone() And the shaders FWIW passthrough.vert void main() gl TexCoord 0 gl MultiTexCoord0 gl Position gl ModelViewProjectionMatrix gl Vertex frag.frag uniform sampler2D tex uniform vec4 tint void main(void) gl FragColor texture2D(tex, floor(gl TexCoord 0 .st) 1024.0) tint As you can see, there's very little to them.


Calling function every n second javascript game I making a game and I want to call a function that runs every random second to spawn something every time. I've seen some posts that said to use the setInterval() function to keep track of the time but I don't know where to implement it because I'm using the requestAnimationFrame() to loop the game. I also tried to implement it in the update function of the classes but it doesn't seem to work. This is my main with the loop import Game from ' src game.js' let canvas document.getElementById('main') let ctx canvas.getContext('2d') const WIDTH SCREEN 800 const HEIGTH SCREEN 600 let game new Game(WIDTH SCREEN, HEIGTH SCREEN) game.start() function loop() ctx.clearRect(0, 0, WIDTH SCREEN, HEIGTH SCREEN) game.update(ctx) requestAnimationFrame(loop) window.addEventListener( quot keydown quot , (event) gt game.controller.keyListener(event)) window.addEventListener( quot keyup quot , (event) gt game.controller.keyListener(event)) requestAnimationFrame(loop)


How to post player s score on Facebook (with js) I have my game made with Phaser (and compiled with cocoon.io) and on the leadersboard state I want to let the user to post his score on Facebook. Well, I created an App on Facebook and I m not finding a good solution to create this simple post, something like "I scored 10 points on this riduculous game..." Pretty easy on Twitter and not so easy on Facebook, I can find information about posting links and that stuff but I m not finding a proper way to create a simple post just with text. How do you guys do this? I guess I m missing something, it shouldn t be so complicated. (I already tested this link and it s not working for me Simple way to post score from my game to Facebook and Twitter? API Error Code 191 API Error Description The specified URL is not owned by the application Error Message redirect uri is not owned by the application.)


Map scrolling around the world I am developing an TBS (turn based strategy) game. I have created a simple canvas renderer to render hexagonial map. I already implemented scrolling on the map. My current problem is that I want to make it like in the civilizations games that you can scroll around the world. But I am kind of stuck on how to implement that. I had the idea of checking if a tile was rendered and if there is still space to the left render next sibling and so on, but this would turn out into long loops. My map array (2d) holds all the tiles and every tile has a member which holds all the siblings. How would you solve this? This is a screenshot from the example. You can check it out on http civ.minerjs.com. The code is also available to browse on the site using developer tools. Thanks for reading!


I keep coming across an error "Cannot read property 'innerHTML' of undefined" I'm new to game designing and have to create a game for my project but I keep coming across an error to do with index.html 93 Uncaught TypeError Cannot read property 'innerHTML' of undefined at drawMissiles (index.html 93) at gameLoop (index.html 140) Any idea how to fix this problem? drawMissiles() function drawMissiles() document.getElementsByTagName('missile') 0 .innerHTML lt (index.html 93) for(var i 0 i lt missiles.length i ) document.getElementById('missile').innerHTML lt div class 'missile1' style 'left missiles i .left px top missiles i .top px' gt lt div gt


2d grappling hook for platformer? What are the options and mechanics for creating a grappling hook in a 2D game? In the prototype for this feature, the person runs around in a platformer world and can throw the hook at any wall, where it sticks and shows a line to the player sprite. So that part (the easy part) is solved. But what options are available now for getting a rather good looking (not necessarily "correct") Tarzan style grappling hook going, e.g. one allowing some kind of neat looking swings? (I understand several different approaches of how the mechanics could work are available I'm looking for a simple one that may make some compromises and not be entirely physical, e.g. perhaps something which attracts the player to the hook center for a while or so while keeping to a certain rope min distance or such.) I'm using JavaScript ImpactJS, by the way. Thanks!


PHP and Javascript HTML5 Collaboration I've recently been working on a fairly complicated game. I've stored information with local storage, but that allows the player to edit it, and does not transfer from computer to computer. The two scripts run on a single server, and I use the following to ping the php server function initiateLoginSequence() var isnewplayer prompt("Hello! Are you new?(Y N)") if(isnewplayer.equalsIgnoreCase("N")) var username prompt("Enter username.") var password prompt("Enter Password.") parsing code goes here later. else var username prompt("Enter a username. This will be used for future logins.") var password prompt("Enter a password. This will be used for future logins."," ") var req new XMLHttpRequest() req.open('POST', 'http 69.144.34.106 Scores.php', true) req.send("returning false" " amp name " username " amp pw " password " amp level " lvl " amp save true") req.send() I then process the results with this lt ?php returning POST "returning" save POST "save" password POST "pw" username POST "name" score POST "lvl" connection mysql connect("localhost 3306"," "," ") if( returning "false" amp amp save "true") mysql select db("userdata", connection) sqlcmd "CREATE TABLE ". username."( Username varchar(". username.") Password varchar(". password.") Score varchar(". score.") )" mysql query( sqlcmd) else if( save false) sqlcmd "SELECT FROM userdata" result mysql query( sqlcmd) while( row mysql fetch array( result)) if( row 'Username' username amp amp row 'Password' ) echo row 'Score' else if( save true) sqlcmd "SELECT FROM userdata" result mysql query( sqlcmd) while( row mysql fetch array( result)) row 'Username' username row 'Password' Password row 'Score' Score ? gt But after creating the mysql database, nothing is populated. So my basic question is, Am I doing this right? If not, what am I missing?


Javascript game to Phonegap for android game? me and a friend of mine are in the process of building a javascrip HTML5 game and I'm running into a few questions about the process of using converting it to an android game. I plan on using Phone gap as it appears to be fairly simple and does what I'm looking for it to do. I've done a little research, but there is still a few questions I have about the whole process. Can I run the app offline? I want to be able to post the app to app store and allow people to download and play offline. Given the fact there will be no server requests can I make the game function offline? As I make the game for the computer I'm relying on the keyboard as input to move around. Obviously, once I port it to mobile this won't be practical. What is the easiest way to go about doing this? I'm considering simply changing the game to have a click on screen which moves the character to that location or even a simple movement pad in the corner of the screen. Would these on screen clicks change correctly over to mobile. Lastly, what is the easiest way to handle save data. On the computer side I plan to use HTML5 local storage to store game data. Does this convert to mobile or is there a better way? I appreciate any help in this matter.


Javascript create a new bullet instance every time a user event is triggered Basically I have a function that I need to create an object of every time the user presses space(event listeners not shown here). function arrow() this.x playerXPos 40 this.y playerYPos 40 this.init function() var arrowImg new Image() arrowImg.src "arrow.png" c.drawImage(arrowImg,this.x,this.y) this.x 10 if(this.x gt 500) keySpace false if(keySpace) arrowObj.init() This works great, but I can only have 1 arrow on the screen at once, which is rather limiting. Is there some way to create a new object every time the if statement is true, and store it in an array or something?


User input in game loop I am building a simple multi player fly around a 3D world game in Javascript webGL websocket (Chrome, Firefox mostly). How should I handle and process user input? My preliminary design (untested) is to first just track which keys are down in the event handler var keys document.onkeydown document.onkeyup function(evt) keys evt.charCode evt.type "keydown" keys CTRL evt.ctrlKey keys SHIFT evt.shiftKey websock.send(JSON( time (new Date()).gettime(), down evt.type "keydown", key evt.charCode, shift evt.shiftKey, ctrl evt.ctrlKey )) and then, in my requestAnimationFrame callback, compute how many time slices (say 20 per second?) have elapsed since the last render callback, and then compute that many time steps using the booleans in the keys array to determine if to apply a left bank, right bank, up down and accelerate and so that time step for each player. How effective responsive is this? Is there a better way? And is there a neater way to deal with latency than just backdating changes for other user's ships?


How to make Pong ai paddle? I'm trying to make an ai so the paddles will move to position before the ball reaches it. I'm not sure how to go about it in this case. Here's the game http cssdeck.com labs ping pong game tutorial with html5 canvas and sounds Function to increase speed after every 5 points function increaseSpd() if(points 4 0) if(Math.abs(ball.vx) lt 15) ball.vx (ball.vx lt 0) ? 1 1 ball.vy (ball.vy lt 0) ? 2 2 Track the position of mouse cursor function trackPosition(e) mouse.x e.pageX mouse.y e.pageY Function to update positions, score and everything. Basically, the main game logic is defined here function update() Update scores updateScore() Move the paddles on mouse move if(mouse.x amp amp mouse.y) for(var i 1 i lt paddles.length i ) p paddles i p.x mouse.x p.w 2 Move the ball ball.x ball.vx ball.y ball.vy Collision with paddles p1 paddles 1 p2 paddles 2 If the ball strikes with paddles, invert the y velocity vector of ball, increment the points, play the collision sound, save collision's position so that sparks can be emitted from that position, set the flag variable, and change the multiplier if(collides(ball, p1)) collideAction(ball, p1) else if(collides(ball, p2)) collideAction(ball, p2) else Collide with walls, If the ball hits the top bottom, walls, run gameOver() function if(ball.y ball.r gt H) ball.y H ball.r gameOver() else if(ball.y lt 0) ball.y ball.r gameOver() If ball strikes the vertical walls, invert the x velocity vector of ball if(ball.x ball.r gt W) ball.vx ball.vx ball.x W ball.r else if(ball.x ball.r lt 0) ball.vx ball.vx ball.x ball.r If flag is set, push the particles if(flag 1) for(var k 0 k lt particlesCount k ) particles.push(new createParticles(particlePos.x, particlePos.y, multiplier)) Emit particles sparks emitParticles() reset flag flag 0 Function to check collision between ball and one of the paddles function collides(b, p) if(b.x ball.r gt p.x amp amp b.x ball.r lt p.x p.w) if(b.y gt (p.y p.h) amp amp p.y gt 0) paddleHit 1 return true else if(b.y lt p.h amp amp p.y 0) paddleHit 2 return true else return false Do this when collides true function collideAction(ball, p) ball.vy ball.vy if(paddleHit 1) ball.y p.y p.h particlePos.y ball.y ball.r multiplier 1 else if(paddleHit 2) ball.y p.h ball.r particlePos.y ball.y ball.r multiplier 1 points increaseSpd() if(collision) if(points gt 0) collision.pause() collision.currentTime 0 collision.play() particlePos.x ball.x flag 1 Function for emitting particles function emitParticles() for(var j 0 j lt particles.length j ) par particles j ctx.beginPath() ctx.fillStyle "white" if (par.radius gt 0) ctx.arc(par.x, par.y, par.radius, 0, Math.PI 2, false) ctx.fill() par.x par.vx par.y par.vy Reduce radius so that the particles die after a few seconds par.radius Math.max(par.radius 0.05, 0.0)


Javascript Isometric draw optimization I'm having trouble with isometric tiles drawing. At the moment I got an array with the tiles i want to draw. And it all works fine until i increase the size of the array. Since I draw ALL tiles on the map it really affects the game performance (obviously) D. My problem is I'm no genius when it comes to javascript and I haven't managed to just draw what is in viewport. Should be fairly simple for an expert though because its fixed sizes etc. Canvas is 960x480 pixels, each tile 64x32. This gives 16 tiles on first row, 15 on the next etc. for a total of 16 rows. Tile 0,0 is in the top right corner. And draws X up to down and Y right to left. Going through the tiles on the first row from left to right as X Y. Here is the relevant part of my drawMap() function drawMap() var tileW 64 Tile Width var tileH 32 Tile Height var mapX 960 32 var mapY 16 for(i 0 i lt map.length i ) for(j 0 j lt map i .length j ) var drawTile map i j var drawObj objectMap i j var xpos (i j) tileH mapX var ypos (i j) tileH 2 mapY Place the tiles isometric. ctx.drawImage(tileImg drawTile ,xpos,ypos) if(drawObj) ctx.drawImage(objectImg drawObj 1 ,xpos,ypos (objectImg drawObj 1 )) Could anyone please help me how to translate this to just draw the relevant tiles? It would be deeply appreciated.


I'm having very negative thoughts, can you help me? I'm 27 years old and I recently started vocational studies for app development. The first year is mostly about introduction to c programming and also a light introduction to html and javascript. I have never studied anything related to coding before. I know how to make pixel art , music and sounds, but coding is just so difficult for me. My objective in life right now is to make a very simple game and I feel so frustrated because I can't achieve anything. I have even tried things like stencyl or construct 2 but even that kind of software I can't understand it enough to make a very simple game. I'm breaking all the rules here, but, can you help me? I read about people that are like 2 months into coding and are already making games. Am I too dumb? Should I just quit altogether?


How to draw the player standing behind a tree in an Entity Component System? I'm making a top down Javascript canvas game using the Entity Component System architecture. For an entity to be drawn on the screen every frame, it needs a PositionComponent and a SpriteComponent. The rendering system looks like this for (let entity of scene.query(CT.Sprite, CT.Position)) this.drawEntity(entity) This works well, but I'm not sure how to modify this to give the player the ability to hide behind objects. For example, in Stardew Valley, you can stand in front of, and behind, objects, as demonstrated in this screenshot https i.imgur.com B90jGS7.png How can this be implemented in an ECS? Because currently my rendering system just iterates through every object and draws them. Also, currently, for drawing the map (scenery and whatnot), it renders the map to a texture and then just redraws that single texture every frame (for performance reasons, instead of redrawing 10,000 tiles every frame). I'd imagine this makes it even more difficult to integrate. My assumption is that I have to take into account the entity's position in some way? That is, an entity with x 0, y 400 will be drawn before an entity with position x 0, y 500 , but I'm also unsure of how to integrate this with an ECS. Thanks for reading.


Why are not the images loaded in Phaser? I am starting to use phaser to create games and I found a problem that I can not find for more tests that I did. I can not show the images I am uploading. You only see a small square in the center, (I show it in this capture when you should see the entire background of the canvas in green, which is the image that first charge. In the example I only charge one, so that more if it does not work. I do not see what error I'm committing, because the navigator inspector does not show errors. The server is created with Node.js. const http require('http') const fs require('fs') const server http.createServer((req, res) gt fs.readFile(". part1.html", (err, data) gt if(err) console.error(err) return res.end(data) ) ) console.log('escuchando en el puerto 3000') server.listen(3000) I show the code for if someone can see the error that I am committing. Thank you. I EDIT the question I add the code that I should add first. The project is in a folder called Game. Here is the file server.js and package.json There is also a folder called public where the html code and images are located. I show you the code. lt !doctype html gt lt html lang "es" gt lt head gt lt meta charset "UTF 8" gt lt title gt Primer juego en Phaser lt title gt lt script src " cdn.jsdelivr.net npm phaser 3.11.0 dist phaser.js" gt lt script gt lt style type "text css" gt body margin 0 lt style gt lt head gt lt body gt lt script type "text javascript" gt var config type Phaser.AUTO, width 800, height 600, scene preload preload, create create, update update var game new Phaser.Game(config) function preload() this.load.image('sky', 'sky.png') this.load.image('sky', 'assets sky.png') this.load.image('ground', 'assets platform.png') this.load.image('star', 'assets star.png') this.load.image('bomb', 'assets bomb.png') this.load.spritesheet('dude', 'assets dude.png', frameWidth 32, frameHeight 48 ) function create() this.add.image(400, 300, 'sky') function update() lt script gt lt body gt lt html gt


Tagging "regions" in rot.js map generator I'm working on a small roguelike and I'd like to be able to tag the various quot regions quot generated via the Map generators so that I can use it as a lookup to environment descriptions. I see that there are quot Rooms quot that are generated in the dungeon generator algorithms, however I didn't really see anything similar in say, the cellular automata generator. Is there a way to leverage the generator in rot.js, or am I stuck with manually determining if I'm in a particular open area (and breaking encapsulation of internal, private variables along the way)? Basically, I'd like to be able to link up my player's location to the text you see at the bottom of , but can't seem to figure out how to do it generically. I'm fairly certain I could use the 'Rooms' object in the first 2 screenshots, and everything else is a hallway, but I'm not clear on how I could get a particular 'region' in a cellular automata generator (or one of the maze generators, for instance).


Click on an isometric plane and obtain normal coordinates I have photos distributed as cells. When I click, I get the corresponding row and column. console.log("Col " X "Row " Y) When applying an isometric view conversion like this ctx.translate(0, 300) ctx.scale(1, 0.5) ctx.rotate( 45 Math.PI 180) I do not know what mathematical formula applies to get the coordinates correctly. Based on feedback so far, I've been able to get this far. The x coordinate seems to work fine, but the y coordinate not. Isometrico() function Isometrico() ctx.translate(0, 300) ctx.scale(1, 0.5) var radianes 45 Math.PI 180 ctx.rotate(radianes) document.addEventListener("mousedown", function(e) CorIsometrico( e.offsetX, e.offsetY) ) function CorIsometrico(xI,yI) RESPUESTA yI yI 300 yI yI 2 xI xI Math.cos(45) yI Math.sin(45) I yI Math.sin(45) yI Math.cos(45) console.log("Coor Isometricas " xI " " yI) Edit Each cell is 50x50. Having 10 columns and 50 rows, the information of each cell would look like this 1 50 50 2 100 50 3 150 50 ... 49 450 250 50 500 250 Maximum Y value 250. xI xI Math.cos(45 180 Math.PI) yI Math.sin(45 180 Math.PI) yI yI Math.sin(45 180 Math.PI) yI Math.cos(45 180 Math.PI) yI yI 2 yI yI 300 Click in X 1 Y 1 138.5929291125633 531.5575746753798 Click in X 1 Y 5 198.69700551341987 90.3229432149742 Y exceeds the maximum value. Edit2 var xI2 xIMath.cos(45 180 Math.PI) yIMath.sin(45 180 Math.PI) var yI2 xIMath.sin(45 180 Math.PI) yIMath.cos(45 180 Math.PI) yI2 yI 2 yI2 yI 300 xI2 xI2 150 console.log("Coor Isometricas " xI2 " " yI2 ) x coor 100 to 400 px if x 150 y coor 0 to 155. Been thinking that the problem is not necessary on isometry. What I'm looking for can be simplified to get the coordinates of a 2d plane by having it rotated X degrees


How can I clear explosions in my function? Hi I have a function to place bombs, and a for loop that places explosions on the tiles where possible. My problem is that I can't remove the explosions after a while. I've tried everything I can come up with so now I turn here as a last resort. The function looks like this function Bomb() var placebomb false if(placeBomb amp amp player.bombs ! 0) map player.Y player.X .object 2 var bombX player.X var bombY player.Y placeBomb false player.bombs setTimeout(explode, 3000) function explode() var explodeNorth true var explodeEast true var explodeSouth true var explodeWest true map bombY bombX .explosion 1 delete map bombY bombX .object for(i 0 i lt player.bombRadius i ) if(explodeNorth amp amp map bombY i bombX ) if(!map bombY i bombX .wall) if(!map bombY i bombX .object) map bombY i bombX .explosion 1 else var explodeNorth false delete map bombY i bombX .object map bombY i bombX .explosion 1 else var explodeNorth false if(explodeEast amp amp map bombY bombX i ) if(!map bombY bombX i .wall) if(!map bombY bombX i .object) map bombY bombX i .explosion 1 else var explodeEast false delete map bombY bombX i .object map bombY bombX i .explosion 1 else var explodeEast false if(explodeSouth amp amp map bombY i bombX ) if(!map bombY i bombX .wall) if(!map bombY i bombX .object) map bombY i bombX .explosion 1 else var explodeSouth false delete map bombY i bombX .object map bombY i bombX .explosion 1 else var explodeSouth false if(explodeWest amp amp map bombY bombX i ) if(!map bombY bombX i .wall) if(!map bombY bombX i .object) map bombY bombX i .explosion 1 else var explodeWest false delete map bombY bombX i .object map bombY bombX i .explosion 1 else var explodeWest false player.bombs If anyone can think of a good way to remove the explosion after a delay please help.


Implementing navigatable achievement menu in javascript I am in the process of learning javascript for game design, and wanted to make a separate achievement page that the user can navigate to that will allow them to check their achievements on various games. (at the moment I am not concerned with implementing localstorage cookies etc, I just want to work on the page for now) So the requirements of my base idea is as follows Able to drag around the viewport page to view all the achievement categories as they will likely not all be in view on smaller screens Able to click on a category to open a small box containing all achievements belonging to that game category Able to mouse over all achievements in the boxes to get text descriptions of what they are OPTIONAL have lines connecting each box on the "overworld" to show users where nearby boxes are if they are off screen At first, I thought I would need canvas to be able to do this. I learned a bit about it and got decently far until I realized that canvas has a lot of restrictions like not being able to do mouseover events unless manually implementing each one. Here is the current progress I was at in doing a test run of learning canvas, but it's not very far var canvas document.getElementById('canvas') var ctx canvas.getContext('2d') canvas.width window.innerWidth canvas.height window.innerHeight function resize() canvas.width window.innerWidth canvas.height window.innerHeight ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.translate(panning.offset.x, panning.offset.y) draw() window.addEventListener("resize", resize) var global scale 1, offset x 0, y 0, , var panning start x null, y null, , offset x 0, y 0, , var canvasCenterWidth (canvas.width 2) var canvasCenterHeight (canvas.height 2) function draw() ctx.beginPath() ctx.rect(canvasCenterWidth, canvasCenterHeight, 100, 100) ctx.fillStyle 'blue' ctx.fill() ctx.beginPath() ctx.arc(350, 250, 50, 0, 2 Math.PI, false) ctx.fillStyle 'red' ctx.fill() draw() canvas.addEventListener("mousedown", startPan) function pan() ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.translate(panning.offset.x, panning.offset.y) draw() function startPan(e) window.addEventListener("mousemove", trackMouse) window.addEventListener("mousemove", pan) window.addEventListener("mouseup", endPan) panning.start.x e.clientX panning.start.y e.clientY function endPan(e) window.removeEventListener("mousemove", trackMouse) window.removeEventListener("mousemove", pan) window.removeEventListener("mouseup", endPan) panning.start.x null panning.start.y null global.offset.x panning.offset.x global.offset.y panning.offset.y function trackMouse(e) var offsetX e.clientX panning.start.x var offsetY e.clientY panning.start.y panning.offset.x global.offset.x offsetX panning.offset.y global.offset.y offsetY body overflow hidden canvas top 0 left 0 position absolute lt canvas id "canvas" gt lt canvas gt So I guess my question is now what is the best way to implement this? Is it feasable to do it with canvas, or should I just scrap that and try to figure out something with div movement? Should I be concerned with performance issues and should that affect how I implement it?


How to include a new file js in a project cocos2d js? I'm trying to include a new js file containing a new scene on a cocos2d js project, but every time try occurs the following error Uncaught ReferenceError GameScene is not defined. I included my file in jsList and in appList "jsList" "src game scene.js" , "appFiles" "src game scene.js" The code of my scene looks normal var GameScene cc.Scene.extend( onEnter function() this. super() var gameLayer new GameLayer() this.addChild(gameLayer) ) The code on app.js to call my scene looks good too var gameScene new GameScene() cc.Director.runScene(gameScene) What should I do?


Is it possible to rotate an image on an HTML5 canvas, without rotating the whole canvas? So I basically want to rotate single sprites on the canvas without rotating the whole canvas, is that someway possible. I also don't want to create a new canvas for each object I have. Also, it would be interesting to know which solution is then the most performant.


How can I imitate interaction and movement in Diablo II? I'm prototyping a simple browser based game. It's played from a top down perspective on a 2d canvas. You left click on a point on the map, and your character will begin walking to it. If you click on a different point on the map, then your character will begin walking to the new point. It's similar to Diablo II. (a demonstration video) How can I best imitate this movement system for a player? Ideas... Track current coords and target coords If target coords are exactly up, left, right, or down, then increment appropriate direction until you get there Implied else target coords are in a quadrant. To make this movement look natural, character will have to move diagonally. For example, pretend the target is to the northeast. For each game frame, alternate incrementing current coordinates in the north and then east directions.


Capitalizing on JavaScript's prototypal inheritance JavaScript has a class free object system in which objects inherit properties directly from other objects. This is really powerful, but it is unfamiliar to classically trained programmers. If you attempt to apply classical design patterns directly to JavaScript, you will be frustrated. But if you learn to work with JavaScript's prototypal nature, your efforts will be rewarded. ... It is Lisp in C's clothing. Douglas Crockford What does this mean for a game developer working with canvas and HTML5? I've been looking over this question on useful design patterns in gaming, but prototypal inheritance is very different than classical inheritance, and there are surely differences in the best way to apply some of these common patterns. For example, classical inheritance allows us to create a moveableEntity class, and extend that with any classes that move in our game world (player, monster, bullet, etc.). Sure, you can strongarm JavaScript to work that way, but in doing so, you are kind of fighting against its nature. Is there a better approach to this sort of problem when we have prototypal inheritance at our fingertips?


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


Y and X Am I doing it wrong? I sometimes run into small issues when doing my JavaScript projects. That is because most build in functions of JavaScript run X,Y if positions are needed. (In that order). But when I build a 2D Array I start out with Y, it seems more logical for me to to run the X axis horizontal. If I am bad at explaining it, let me show you So my loops look like this for(var y 0 y lt 10 y ) for(var x 0 x lt 10 x ) console.log("Doh!") Is this so insane? I would like to convert to the normal practise so that I have an easier time while building my game and don't have to do constant switcherroos. So why is it X before Y ? Edit Here is another example, and probably the main reason for my confusion X is Horizontal, and Y is Vertical in my books.. 0,1,2,3,4 , 0,1,2,3,4 , 0,1,2,3,4 , 0,1,2,3,4 ,


Planck.js (rewritten of Box2D.js) 8 direction box movement I have a box in Planck.js. I want to move this box with some keys. How can I do that? My code planck.testbed("boxworld", function(testbed) var pl planck, Vec2 pl.Vec2 var world new pl.World(Vec2(0, 0)) Box var box world .createDynamicBody(Vec2(0.0, 10.0)) .createFixture(pl.Box(0.5, 0.5), 20.0) box.render fill " FA8072", stroke "black" return world )


Javascript 2D game tile textures I am using a texture atlas for my tiles. Of course I need to get the sub images to draw them on the canvas as separate tiles. Right now I can think of two ways to implement this. Divide the texture atlas into separate Image instances. Then draw them onto the canvas accordingly. Use a single image, and just draw part of it by adding extra parameters to CanvasRenderingContext2D's method drawImage. I'm not sure which is better. My thoughts were that the first option would be more manageable and flexible, since each tile is separated. What would be better? What are the ups and downs of each?


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.


Behaviour of containers in Phaser 3 framework I don't understand the behaviour of containers in this example Phaser example The part I don't unerstand is line 41. Why is lastContainer assigned to newContainer? In line 40, newContainer is added as a child of lastContainer my intuition would be that the effect of line 40 is so that the rotations can be performed on lastContainer (or, rather, on containerTails, which seems to contain four nested container structures, one for each arm), and propagated to its children. It makes no sense to me that the variable containing the parent container should be assigned to its own child how does that not overwrite the nested structure of containers, effectively removing the parent container from the picture?


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.


How to get projectile direction vector in a 2d grid? I am having trouble figuring out how to trace the path of my projectiles in an Asteroids clone. Currently the ship is locked to the center of the screen and can be rotated a full 360 degrees. I know the angle the ship is pointing at any given time, but I am not sure how to calculate the vector that the projectile should use for its trajectory. I know that I can find the correct vector by subtracting the end point from the start point.. but the issue is that I do not know the end point. Theoretically.. the end point is whenever the projectile touches the edge of the screen or some object. This is the current game code https jsfiddle.net m6sxrk8w just using a hardcoded movement vector of x 1, y 1 . Can anyone give some advice on how to dynamically determine the true vector given the current direction of the ship? There must be some simple math I am missing here...


Experience embedding javascript I'm looking into scripting languages to embed in my game. I've always assumed Lua was the best choice, but I've read some recent news about embedding V8 as was considering using it instead. My question is two fold Does anyone with experience embedding v8 (or another javascript engine) recommend it? How does it compare with embedding Lua? I like that v8 has a c embedding API. However Lua API has had lots of time to be refined (newer isn't always better and all that). Note At this point I'm not too concerned with which is better language or which library has better performance. I'm only asking about ease of embedding.


DOM for GUI display animated objects I'm creating an HTML5 game using Canvas, but want to use DOM for the GUI for the reasons mentioned in there articles http blog.sklambert.com html5 game tutorial game ui canvas vs dom http www.html5gamedevs.com topic 29569 how do you guys build your ui http www.html5gamedevs.com topic 802 gui methodologies That being said, we have a component on the GUI that needs to be animated which will be through a sprite. Is it possible to render sprite animations through a DOM element?


TypeError R o5R.F6s is not a function in changing states in phaser box2d i build my game using phaser.2.4.3.min.js and phaser.2.2.2.box2d.min.js When trying to change states this error is being raised TypeError R o5R.F6s is not a function and i can't seem to figure out the problem PS i took The source code of box2d plugin from the example folder in phaser , and i did not purchase the full plugin yet i was just testing it . is there anyway to fix this issue ? here is the game code http jsfiddle.net fbdtq1tg 5 and here where the error is raised SetGameOver function () this.game.state.start("TheGame")


p2.js body position is NaN when spawned inside of each other I'm working on a project for which I need a physics engine. At the moment I'm playing around with p2.js but I'm running into a problem When I try to create multiple bodies (circles and or boxes) which overlap the positions are set to NaN as soon as world.step() is called. The bodies have a mass of 5 and are dynamic. In very rare occasions it does actually work. How can I make sure it works every time? Do I have to wait for the bodies to be initialized? 4 circles before the simulation starts, once world.step is called the positions of these circles is NaN var world new p2.World( gravity 0, 9.82 ) function PhysicsBody(type, x, y, widthOrRadius, height) this.body new p2.Body( mass 5, position x, y , ) this.type type if (this.type 'rectangle') this.shape new p2.Box( width widthOrRadius, height height ) else if (this.type 'circle') this.shape new p2.Circle( radius widthOrRadius ) this.body.addShape(this.shape) world.addBody(this.body) var bod1 new PhysicsBody('circle', 0, 0, 32) var bod2 new PhysicsBody('circle', 10, 0, 32)


How to implement map scrolling inertia formulae I'm looking for a mathematical formulae to calculate map scrolling inertia. Basically I have an HTML5 Canvas displaying part of a map and I capture the mousedown mousemove mouseup to calculate my new offset. And when I scroll the map I want the map to continue scrolling for a few moments after the user stopped dragging the cursor. I do have a sample implementation but I'm not really satisfied with it. I'd be looking for a nice clean math formulae to achieve this. I'd like my map to behave for example like in Civ 5 when you scroll the map around. Here is part of my implementation (working jsfiddle https jsfiddle.net CowWarrior dkxnj5d8 1 ) mouseup stopMapDrag function (e) var movementX (e.pageX this.startX) var movementY (e.pageY this.startY) this.mapOffsetX parseInt(this.mapOffsetX) movementX this.mapOffsetY parseInt(this.mapOffsetY) movementY this.isDragging false this.displayMap() calculate last vector ui.vectorX parseInt(e.pageX ui.absStartX) ui.vectorY parseInt(e.pageY ui.absStartY) show inertia setTimeout(function() ui.dragInertia(2) , 30) console.log("(vectorX " ui.vectorX ", vectorY " ui.vectorY ")") (' canViewport').css('cursor', 'default') , need to find a good formulae for inertia dragInertia function (factor) var movementX parseInt(ui.vectorX factor) var movementY parseInt(ui.vectorY factor) ui.mapOffsetX parseInt(ui.mapOffsetX movementX) ui.mapOffsetY parseInt(ui.mapOffsetY movementY) ui.displayMap() if (factor lt 8) setTimeout(function() ui.dragInertia(factor 1.2) , 30) ,


How do I make an entity move once per second in crafty.js I am trying to implement "Snake" using crafty.js but I can't seem to get the snake entity to move just once in a second. How do I do this?


Unity 5 Animation attaching I have created the walking and idle animation for my fps player. I've added a JavaScript script to access it, but when I run it and press button(w), it stops and says that the animation is not attached to the object. When I drag the walking idle animation and drop to that object, it creates an animation controller. Again I run it, still same error. I can't find where to attach the animation Here's my script function Update () if(Input.GetKeyDown("w")) GetComponent. lt Animation gt ().Play("walk anim2", PlayMode.StopAll) if(Input.GetKeyUp("w")) GetComponent. lt Animation gt ().Play("idle anim2", PlayMode.StopAll) Where do I need to attach the animation?


Canvas slowly degrades in performance after a while I was creating a simple game and was shocked to see how the performance started to degrade. It never happened to me before, most probably because I use images and not the context drawings. So I used this function and the whole game becomes so slow, it just cannot be played after 30 seconds. Office.prototype.draw function() for(var i 0 i lt this.tables.length i ) for(var j 0 j lt this.tables i .length j ) Canvas2D.ctx.rect((373 j) 75, (370 i) 250, 170, 20) Canvas2D.ctx.fillStyle 'green' Canvas2D.ctx.fillRect((373 j) 75, (370 i) 250, this.moneyBar (i 4) j , 20) Draw the experience bar. Canvas2D.ctx.rect((373 j) 75, (370 i) 270, 170, 20) Canvas2D.ctx.fillStyle 'yellow' Canvas2D.ctx.fillRect((373 j) 75, (370 i) 270, this.expBar (i 4) j , 20) Draw the tables. Canvas2D.drawImage(sprites.items 0 , new Vector2( (250 j) 50, (250 i) 200)) So as you can tell from the code, there is the multidimensional array table which has bars on top displaying moneyBar and expBar. If I am to use Canvas2D.ctx.stroke() inside the for loop, the game performance drops right away. Outside of the loop, it keeps up a bit, then it degrades. If I don't use stroke at all, works better, but degrades anyway. So I am really confused as to why this degrades so fast. Also am using requestAnimationFrame and have used the same engine in previous games and performance never degraded. If I was to remove fillStyle, keeps up 3 4 seconds more. There are 8 tables in all, which means the for loops run 8 times per draw. Vector2 function. function Vector2(x, y) this.x typeof x ! 'undefined' ? x 0 this.y typeof y ! 'undefined' ? y 0


Approaches for storing grid like information I am drawing this simple grid on my NodeJS server var grid for(var x 0 x lt 20 x ) grid x for(var y 0 y lt 20 y ) grid x y 0 console.log(grid) The outcome looks like this I know, pretty right?! 0 is supposed to indicate FREE, thus if a player requests to move to a field with 0, he will! The problems come when I want to add more then just Free Occupied, for instance I would like to give each Array Element an ID number for the Client Updates, or certain features on the field to be stored. I tried to assign something N, something2 N But thought it looked rather performance expensive in the long run. (On a big Grid) I read about using a single Object for several elements, but I cannot find this any more.. Should I perhaps use an Array of Objects, or an Additional Array inside each X,Y element? Any performance convenience anything goes tips are welcome D Edit Thank you for the ideas so far, I was now thinking to perhaps using Strings. Storing Variable A "," Variable B and then later using the .split to use the information. Any thoughts on this?


Good practices when optimizing HTML5 Javascript Game Developement I'm just starting out as a game developer and have created a few crappy but playable clones of classic games like pong, and bomberman. Being self taught (bless the internet) I do this by just stuffing in code to make the games work. Now I feel the time has come to create something complete, for this I need to know how a game is structured. I've searched on the web but there isn't that much to be found. The only "high level" language I know is javascript so reading a tutorial or article based on C doesn't help me that much. I'm looking for good resource's pedagogically covering the theory and possibly examples (in Javascript or pseudo code that is understandable for a beginner) of how the game pieces fit together. From the start screen to asset loading and running the game loop. I'm not looking for anything complicated like reading through a 4000 line source code. All I want to learn is where, how and when the main parts of every game should be called. If you know any good resources to share, or maybe even have an answer for me I would deeply appreciate it.


Make a variable go down as another goes up? I am making a JavaScript game called "Spoop The Clicker", and I have a variable shown by text stroke("blue") fill("purple") textSize(30) text("Spoop Cash " spoopCash, 130, 10) This is inside the draw loop, as it is always shown. The thing is, I need textSize to be set shrink as my other variable spoopCash increases. How could I do that? If you can, please include a way to stop it from going too small (such as size 10 being the smallest allowed.)


Mouse position to grid position not working I have a function which converts my mouse position to grid position in the game but it is not working properly... its slightly off. I have two functions one which converts from grid to screen position (this particular one, works fine) and the code is function mapToScreen(gridX,gridY,screen) var grid 64 var x (gridX gridY) (grid 2) x screen.offsetX camera scroll offset X axis x grid 2 centre of the iso tile on X axis var y (gridX gridY) (grid 4) y screen.offsetY camera scroll offset Y axis y grid 4 centre of the iso tile on Y axis return x,y So my function to do the opposite looks like this function screenToMap(pixelX,pixelY,screen) var grid 64 pixelX screen.offsetX pixelX grid 2 pixelY screen.offsetY pixelY grid 4 var gridX Math.floor((pixelX (grid 2) pixelY (grid 4)) 2) var gridY Math.floor((pixelY (grid 4) (pixelX (grid 2))) 2) return gridX, gridY The problem is as shown below in the image, it doesn't return the correct number. The first corner tile should be 0,0 . Also notice the co ordinate doesn't change correctly with the tile border. I don't know how to solve that either.


How to get the Javascript equivalent of GameMaker's hspeed and vspeed given only direction and speed ? I'm using a NodeJS server to control NPC movement in a multiplayer game, and when they get too close to the edge of the room I need to reverse either the horizontal or vertical components of their velocities (how to decide which, is a bridge I'll cross when I get there). The problem is I already have their direction and speed, and am able to convert it to hspeed and vspeed, but not back again. I need the inverse of this function function velocityToSpeeds(direction, speed) return x speed Math.sin(Math.toRad(direction 90)), y speed Math.cos(Math.toRad(direction 90))


how can i make an object in a canvas always look at the mouse cursor this is my code var myGamePiece function startGame() myGamePiece new component(30, 30, "red", 10, 120) myGameArea.start() 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.keys (myGameArea.keys ) myGameArea.keys e.keyCode (e.type "keydown") ) window.addEventListener('keyup', function (e) myGameArea.keys e.keyCode (e.type "keydown") ) , 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.keys amp amp myGameArea.keys 37 ) myGamePiece.speedX 5 if (myGameArea.keys amp amp myGameArea.keys 39 ) myGamePiece.speedX 5 if (myGameArea.keys amp amp myGameArea.keys 38 ) myGamePiece.speedY 5 if (myGameArea.keys amp amp myGameArea.keys 40 ) myGamePiece.speedY 5 if (myGamePiece lt 299) myGamePiece.speedX 5 myGamePiece.newPos() myGamePiece.update() I want myGamePiece to look exactly were the mouse cursor is looking. How can I do this?


Top down four directional movement snap to tiles, not feel like crap I want to make a topdown rpg movement, I need to update these parameters based on user input User input four directions . Update parameters Position x, y, Flip sprite flipx, flipy, Sprite number s, eg 1 for horizontal sprite, 17 for vertical sprite Sprite Animation si, eg 1 to 4 for walking animation This is my crappy implementation function init() p t 0, x 0, y 0, dx 0, dy 0, mtimer 0, s 1, si 0, flipx false, flipy false end function update() local input x 0 local input y 0 if btnp( ) then input y 1 elseif btnp( ) then input y 1 end if btnp( ) then input x 1 elseif btnp( ) then input x 1 end if p.dx 0 and p.dy 0 then if input x ! 0 then p.dx input x p.mtimer 4 elseif input y ! 0 then p.dy input y p.mtimer 4 end end if p.mtimer gt 0 then p.mtimer 1 p.t 2 p.x p.dx 2 p.y p.dy 2 if p.mtimer 0 then p.dx 0 p.dy 0 end end p.t 0.5 if p.dx ! 0 then p.s 1 elseif p.dy ! 0 then p.s 17 end p.flipx p.dx 0 and p.flipx or p.dx lt 0 p.flipy p.dy 0 and p.flipy or p.dy lt 0 p.si flr(p.t 30 30 4) end function draw() spr(p.s p.si, p.x, p.y, 1,1, p.flipx, p.flipy) end This is the end result As you can see it's so bad looking, I want you to implement this movement so it's fun and juicy. Or what can I do to improve the looks and feel of this.


Why can't i change the background color in Phaser? what is wrong with my code? i'm using game.stage.backgroundColor but the screen remains black. main.js var demo demo demo.game new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '') demo.game.state.add('state1', demo.state1) demo.game.state.add('state2', demo.state2) demo.game.state.start('state1') state1.js var demo demo demo.state1 function() demo.state1.prototype preload function() , create function() game.stage.backgroundColor " 4488AA" , update function()


How to make an infinite map I was wondering if someone could explain to me how to implement a seemingly dynamic infinite map like the one at http wordsquared.com My main issue is really generating new tiles in any direction when the user drag the board. I'm also trying to figure out how to handle the coordinate system, and actually what how to store the map in a database.


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?


Creating an Array of 1s and 0s (with all 1s touching) I am a novice programmer trying to add an unnecessary and complicated element to a text adventure! ...and I've run into a question I am not sure how to research further (I suspect due to lack knowledge of the proper terminology). I am working on a small text adventure that uses an 11x11 array. Player is capable of moving into spaces with a 1 and incapable of moving to a 0. I need to a) retain the outer boundary 0s, b) randomize the content inside the border, and c) ensure that there is a linked path of 1s that will eventually connect to a 2 (the exit) 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 1 1 1 1 1 1 1 0 0 1 1 0 1 0 1 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 1 1 1 1 0 1 1 1 2 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I'd appreciate any pointers here not sure what direction I should be looking in. Thinking of scrapping this feature so if it's not viable I don't mind hearing that ) Thanks for reading.


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?


How to make my model's top section rotate without rotating the entire model? I'm trying to learn a bit of Maya modeling so that I can be self sufficient when it comes to creating super basic assets for my game development. I'm trying to understand skeletal rigging and how it modifies the model geometry itself. I've got the most basic model a cube with proportions that make it into a 3D rectangle. I've rigged it with a very simplistic skeleton. My goal is to learn how all of this works, and create a character that has motion similar to maybe the magic carpet from Aladdin it's a rectangle but the edges somewhat move like it has arms and legs. When I rotate some joints, it distorts the entire model. I added a bit more geometry thinking that it'd allow the top section of my model to rotate a bit more without having to deform the entire model, but it still just seems to do the same thing. How can I make the top section of my model be capable of moving forward and backward in such a way that it does not cause the entire model to move forward? Here are some screenshots to help explain and show my situation ... This is my model and skeleton (I told you it was super basic, lol) ... And here is what happens when I rotate around the neck joint ... And here is sort of what I was hoping to achieve ...


How to flip sprite and all collision children of a KinematicBody2D at the same time? I have tried to use the scale property of KinematicBody2D to flip at the same time the sprite and the collision area raycast children. For flipping, one just has to set scale.x 1. If it works in the editor, it does not work properly because the engine seems to reset scale.x to 1 each frame (as stated here) NB Here the original sprite is looking left (that is why it is blinking when going to the right, not very didactic sorry). How to do the same without flipping every collision children one by one?


HTML5 Canvas Tileset Animation How to do in HTML5 canvas Image animating? I am have this code now http jsfiddle.net WnjB6 1 In here I am can add animations something like Animation.add('stand', 0, 1, 2, 3, 4, 5 ) But how to play this animation? My image drawing function is drawTile(canvasX, canvasY, tile, tileWidth, tileHeight) Animation 'stand' return 0, 1, 2, 3, 4, 5 I am need something like when I am run Animation.play('stand') run animation from 'stand' array. I am try to do this something like one day, but no have more idea how. ( Thanks and sorry for my bad English language.


Turn based game in HTML JS CSS new joiner messes with state of game while animations are still running for other players I developed a playing cards web app using HTML JS CSS. Communication with the server is performed using WebSocket. The server is developed in Java Spring. The game proposes to join one of the many available tables where you can immediately perform an action. The players who are already in the table are perfectly in sync with each other, as when they receive a message from the server, I show a screen overlay preventing them from clicking on any element on the table while an animation is running. After the animation is terminated, the game becomes available and runs normally. My problem is that if a new player joins the table after a message has been sent by the server, then he can perform an action while the animation is still running for the other players, thus starting a new animation for them at the same time and the game becomes messy. Is there a way to either prevent the new joiner from performing an action before the animation has ended for the rest of the players ? Do you have any other idea how I can solve this issue ? Thanks for your help


How do I make a 2D sprite flash green when tapped? I have a sprite that is based on an image of a gray circle. When the user touches the sprite, I want the sprite to flash green, as in I want the circle to appear to turn green for 0.2 seconds. I tried setting the color of the sprite via SpriteRenderer's function SetColor, and it blended the color with the initial gray color of the sprite, so I got a very dark green even though I'm really sure I didn't mess up the values when I created the color. Now I'm trying to get my flashing effect by using separate images. I have the images I need, and I have a message getting logged when I tap the circle, I just need to setup a non looping animation and trigger that animation in my code.


texture won't move OpenGL ES 2.0 I want be able to move my texture in GLSL I have set my texture to wrap S and wrap T but not sure why it wont move my fragment shader looks like this at the moment uniform sampler2D n mapTex uniform sampler2D n mapTex2 varying mediump vec2 TexCoord varying mediump vec2 TexCoord2 This gets updated within the main code uniform mediump float vTime void main() gl FragColor texture2D(n mapTex, vec2(TexCoord.x vTime, TexCoord.y vTime)) within my code I have a made a function to calculate FPS and I use the delta time of that function to pass into the fragment shader void OGLESIntroducingPVRTools timer() This method records to the time to start rendering a frame and hold that value in another variable we then start to count again. To get delta time we subtact the current time from the previous time this will give us in milliseconds how long it took for a frame to render. We then divide this by 1000 this converts it from ms per frame to FPS FrameCount p Time c Time c Time PVRShellGetTime() elapsed c Time 1000.0f DT ((float)(c Time p Time)) 1000.0f fCount DT if(fCount gt 1.0f) if time is over 1 second reset counters and recount FPS FrameCount FrameCount 0 fCount 0 and in my renderscene method which updates I have this code to pass the value to the uniform within the fragment shader glUniform1i(glGetUniformLocation(m ShaderProgram.uiId, "vTime"), DT)


Unity How to transition to a different animation during the blend phase? I have a set of animations Idle, start walking, stop walking, and walking full speed. I have the animations all blending nicely...and the controls are fairly responsive during most of the motion...but there are odd transitions where the blends take away control I can't transition to the walking animations when I am blending between the "stop walking" and "Idle" animations, for instance. How do I get the animations to transfer during the blend phase??


Running two simultaneous animations on a model? I am just looking for a broad answer to this question. I am more curious about the general information rather than the specific. Also, I tried to search for this, but I think it's hard to word it so you get the right question. Anyway One common thing I see in a lot of games is multiple animations on the same model. i.e. A character runs, but also raises his arms an shoots. A character has a walking animation, but can also be carrying resources as he walks. I am curious if the first model has a "run" animation and a "run while shooting" animation. Or if they have a "run" animation and a "shoot" animation and run them at the same time. Obviously the first is possible, but I am wondering how the second one is done. Do they use two models for upper and lower body or is there a way to ignore certain parts of a model when animating? I know this depends a lot on the model, the programmer, language and the way the animation is done. But broadly, if you were making a model with the intent of it doing multiple animations at once, what would be the best way to go about it? Again, not after detailed specifics, just an overview ) Thanks!


What constraint (if any) limits crowd animation variety? I have recently noticed something in a large number of sports games relating to the animation of the crowd. Scenario Player holes the golf ball and the crowd all clap their hands. Whilst the faces and attire of the crowd members are different the animation is exactly the same. That is, the arm and hand movement of each member is identical. Similar scenarios exist in other sports games in football games the crowd often stand up and sit down together as well as doing things like "fist pump", wave, etc. in a perfectly synchronised manner. Question Why is there no (or very little) variation in the crowd animation? Is this a memory constraint? If so, what is the general architecure design of this functionality and why is it so constrained? Is it along the lines of "It is more efficient to animate a collection of objects than multiple individuals"? Or do game developers simply not see crowd variation as an important enough requirement? As technology and game "realism" advances so quickly, this is something that still strikes me as "wooden" and unrealistic.


How To Animate Skeletal Interactions (Hugging, Handshakes etc.) I am fairly new to animating and IK systems, but I've got the basics down to some extend. Now I am looking into how to go about skeletal actor animation interactions such as handshakes, fighting, horse riding, hugging or sex animations and such, to be used in unreal engine 4. I would like someone to point me into the right direction on how to go about this. As I am new to this, if the question is too broad or vague please do let me know.


Head bone not found when importing .blend to Unity I have created a model, rigged it(using rigify), and created several actions(animation clips) for it Blender. Everything seems to be fine. However, when I import the .blend to Unity I get a console warning that "Required human bone 'Head' not found". I know that there is a bone called "head" in my .blend. The animations work, except the head rotation does appear to not be deforming. Has anyone experienced this? Is this just a naming convention thing. Should I try to rename my "head" bone to "Head"? I just don't know the inner workings of the the import process well enough to know what to do.


Animation in top down 2d How is this usually done? Especially when the character might need to use different animations, for instance at his hands and legs. I noticed some skeletal animation solutions but they were only applicable to platformer games. Any ideas?


How can I manipulate a static 2D sprite so that it looks alive? I've got a stick figure in the corner of my UI, but I don't like the way he's just standing there, without moving. I'm stuck without additional frames of animation, so my only recourse is the manually move the sprite up and down, left to right, rotation, or whatever else you can think of. Basically I can do everything besides drawing another sprite of animation. I've tried things like have it subtly bounce or rotate a bit to give it a little bit of dynamism, but I don't believe its the best approach. I've got a static sprite of a stick figure, how do I give it a bit of life?


why animated tiles aren't animated? So I got some code and I'm using pytmx to load the maps, but the animated tiles don't seem to animate in my pygame game. Is there a setting to change that or do I need to write the animation code myself?


How to handle animations for a turn based deterministic game? I have a turn based combat system where all monsters act one turn, then all players, etc. The combat mechanics are completely deterministic I can pre calculate the outcome of a turn. I'm interested if I should do all calculations ahead of time (monster A will be at X, monster B will be at Y), and then just play a bunch of animations based on these calculations (Calculate for A) (Calculate for B) (Animate A move to X) (Animate B move to Y) OR do one animation per calculation? (Calculate for A) (Animate A move to X) (Calculate for B) (Animate B move to Y)


Blending effect on textures Hi i am trying to build screen animation like flickering, interlace, color separation similar to old style malfunctioning Amiga screens. The intended effects are shown in this video. I am using libgdx and I already discovered the universal tween engine, which helps a lot to build transitional animations, but how should I approach those blending effects, any suggestions? I will specify my question once I learned more about libgdx, but maybe you could give me some hints already. Thanks!


Skeletal Animation No initial bone rotation I am currently trying to implement animations in my game. I am having an issue where the bones do not rotate properly. In my program, I apply an inverse bind pose to each bone to move them to bone space. Then I recursively calculate the transformations for each bone for the keyframe. The bone transformation looks like this bone.Transform InverseRootGlobal Global bone.InversePose InverseRootGlobal is the inverted root node transformation Global is the recursively calculated transformation bone.InversePose is the inverse pose matrix It appears that all is correct apart from the bones initial rotation. When I move the bones to bone space, they loose their rotation from the bind pose and 'point up'. Here's what it looks like If it helps, I am using Assimp to import the data. Thanks in advance.


Timing in fighting game using animations time? I am developing a 2D fighting game in C . I have made the basic components such as moving, guarding and even a combo system that works perfectly well. My main concern now is that I want the game to be as balanced as possible, and thus I am entering a testing phase. I am even requesting the help of my father to play against as no AI has been implemented (yet). In the game you can chain attacks using a punch kick (PK) button. But you can also charge the attack by pressing the PK button longer, which basically pauses the animation, resuming it when the attack is fully charged or the player releases the button. One thing that I have noticed is that if your opponent is simply pressing the PK button when being hit, it can counter attack pretty easily if you end up charging your attack. This behaviour basically makes charging useless, because it can never go through if your opponent knows that. So my point is that I need to add a delay so that the counter cannot occur (I do not want it to, because the game is based on an actual PS2 game where you cannot counter that way for the record, there is a way to escape, either by pressing the guard button, or by hitting a button at the right timing to teleport behind and counter). To add this delay, I can either modify the actual duration of the "damage" animation so that it does what I want or I can internally add a timer where the character enters a state where he cannot do anything. I would want to go for the first one, since that way you SEE that you cannot counter using a punch since you are still in the damage animation. But the thing is that each character has its own set of animations and thus in theory, the developer or the designer (which is me in both cases) can modify the duration of one character while the others still have an old value. My question is thus more on the design level. Is it a good idea to let the timing be decided via animation duration? Is it what is actually done ? If I have fifty characters when I discover another timing issue, it would mean to modify the animation of each and every one of them... But adding a timer internally seems more like a patch that actual fine tuning...


Unity Implementing Fall with Animation I have a character controller. I am primarily using FSM with the animations and blends. However, I am running into some trouble with the fall. I walk up to a ledge and walk off...sometimes I will make it off the edge and the falling animation will play...but sometimes I get stuck halfway off the edge. Also, the falling animation completely disregards any motion vectors I had prior to transferring to the falling state. Is there a way to transition to fall, retaining the current x y velocities? In an effort to fix this, I tried giving the attached rigidbody a force vector slightly up and in the direction of travel so that the character gets a little hop over the edge...but again, no luck.


How does "Cut the Rope" do such realistic animation? "Cut the Rope" is so smooth and real life like, while some apps are very "bitmap" like. How does "Cut the Rope" do such realistic animation?


Unable to enable IK on someone else's rig I'm using someone else's character rig for reference but I'm not sure how I can enable IK solvers for the arms. The hand controller has a NURBS control with an ikBlend attribute, but when I try to use the "Enable IK Solvers" tool, I get an error saying the attribute is locked or connected. Clicking "Unlock Selected" on the attribute doesn't fix it. Breaking the connections also breaks the ability for it to drive the enabled disabled state of the IK handle. The rigged character can be downloaded here if anyone wants to try to help me out http www.antcgi.com 2014 06 03 free model 15 kila lods rig dynamics


What's the best head bob formula? Given a point in space, a direction of travel, and a time since start, what's a convincing, non sickening formula to simulate head bob? What's been successful in previous games? Has there been any research on what bobs induce sickness the least? An example naive head bob formula, applied to the up axis http www.wolframalpha.com input ?i abs 28sin 28x 29 29


How to set the runtime of an animation based on attack speed? Based on an answer I received on this question How to make an action perform only after an animation has run? I am using notifications in animations to perform certain commands actions. See in the documentation https docs.unrealengine.com en US Engine Animation Sequences Notifies index.html Before resorting to this site, I researched elsewhere for something about modifying the animation speed and the closest question I found was this https answers.unrealengine.com questions 509654 how do you change the ratespeed of animation.html Simply changing the speed of the animation, I know how to do it, but I want to control its runtime. Sort of determining how much time the animation has to play. In the image below I show more or less the scenario I have Note that the notification happens at the end of the animation (where I apply the damage). So based on the speed I set for animation to perform, every time it's finished the notification happens, applying the damage. It turns out that the animation doesn't necessarily have the exact duration of an attack starting when the other one ends (the image below will make it easier to understand) There is one more scenario I imagined. In the latter case, assuming the animation is (usually) 1 second long, and the character has the maximum attack speed (I set the maximum to 2 attacks per second). So the animation would be running 2 times faster But the attack speed will not always be a "simple" number, I would like to know how to calculate set it time so I have no problems when the attack speed is any number. I want to know how to set the animation runtime and a time interval between the animation running.


How to animate a flip of a card in Cocos2d? I am working on a card game and would like to ask if someone could advice me how to implement a flip of a card in Cocos2D?


Trade offs of linking versus skinning geometry What are the trade offs between inherent in linking geometry to a node versus using skinned geometry? Specifically What capabilities do you gain lose from using each method? What are the performance impacts of doing one over the other? What are the specific situations where you would want to do one over the other? In addition, do the answers to these questions tend to be engine specific? If so, how much?


Syncing first person arms and enemy character for struggle in games Some FPS have it where your arms are struggling or doing something melee to a character model. Both the arms and the character you're interacting with are sync'd up in the animation. What's the general idea behind how that syncing is done?


Transition between two Views i want to animation the transition between game screens , in my game loop i have a function called getCurrentScreen() which returns a Screen object this Screen Class has a function called present() this function draw on the framebuffer , when i want to change to another screen i call setCurrentScreen(Screen) , so it will draw the screen i set , What i want is to animation the transition between these screens any suggestion , is the a book or an article that discusses this


Where to find animated matrix transformations in an fbx file? Where can I find matrix transformation animation data in an fbx file? I have an fbx file with animations. I have successfully read the indices, matrix, and weight from it. How can I get the frame by frame changes in the matrix? Unfortunately, I haven't been able to find the answer in the Autodesk documentation.


What animation technique is used in 'Dont Starve'? While playing a few games in my personal time off development I've stumbled across a survival 2D 3D survival game. The game was apparently made in SDL and GLUT (Dont starve) but what really amazed me was the animations in the game. The animations are extremely smooth and fluent. There is no distortion while animating, what usually happens in hand made animations is that pixels get removed, animations are jaggy and they simply aren't as smooth. That got me thinking on how they managed to accomplish such a quality of animations. Were they really handmade (If they were, then it must've taken a very talented artist), is it bone animation or are they using another technique?


What is next to interpolate camera position with smooth speed changes? I am working on a path camera to be used in demo playback. (3d game) The spline math used is catmull rom. I am on my second attempt to get constant position speed ( (someone else is doing rotation). The path cam keyframes are position time. I have a step now when the path is recalculated, it also generates the arc distance time lookup table which I have normalized. I have the duration of each segment(k through k 1)as well as each segments linear velocity calculated from that data. I am not very good at reading anything except basic equations. I could use an explanation or psuedo code of what is needed next in order to get the camera to smoothly accelerate or decelerate depending on the velocity of the next segment. Right now it's instant changes and no good. I tried googling for hours and was going in circles.


MVC How To Handle Animations? I am working on a turn based game that utilizes the model, view, controller design pattern to separate logic from input from rendering. I am still a little new to the pattern, but from my understanding I have laid out the following MVC system. The model(s) comprise a set of pawns with game flow and interaction logic. Pawns models know how to interact with each other and the model world, but only when signaled to do so via function calls. (i.e. pawn.move(startLocation, endLocation) or pawn.attack(enemyPawn)) The view(s) make up everything that is viewable by the player. This includes menus, visual representations of the pawns models, and any user interface components like cursors and buttons. The view(s) query the model for data to draw visual representations of pawns. The view(s) also can dispatch user interface events to any observers interested in these events. The controller(s) handle all transition and input logic. When an interesting user interface or input events occur, the controller decides what the model should do and signals the model to do it. The controller also handles swapping out of views when necessary. I know there are many ways to implement MVC and I am open to suggestions if something seems off with this design, but the real problem I am having is how to handle animations in the view. Say the user commands a pawn to move 5 spaces North and 1 space West. I want an animation to show this over several seconds. How would I handle something like that?


Game thread, render thread, animation inverse kinematics, and synchronization In a multithreaded setup with a game logic thread and a render thread, with some kind of skin mesh animation with inverse kinematics plus etc how does animation work? Does the game logic thread just update a number saying time T in the animation and then the render thread infers Who owns the skin mesh animation, the game logic thread or the render thread? How is it stored in the scene graph if it is stored there at all? When the game logic updates does it do the computation of the skin mesh animation and the computation of the inverse kinematics and then store the result directly in the scene graph or is it stored indirectly and the render thread does the computation?


How to add (not blend) non looped animation clip to looped animation with Mecanim? I have a GameObject with Animator and looped animation clip. This animation changes X coordinate from 0 to 10 and back. I need to add another animation to the first one that increases GameObject's scale and changes its color to red simultaneously. After scale and color change GameObject keeps these parameters and continues to move according to the first animation clip. The only way I managed to work it around is writing a custom script with couroutine IEnumerator Animate() float scaleDelta 0.2f float colorDelta 0.02f for (int i 0 i lt 50 i ) spriteRenderer.color new Color( spriteRenderer.color.r, spriteRenderer.color.g colorDelta, spriteRenderer.color.b colorDelta) transform.localScale new Vector3( transform.localScale.x scaleDelta, transform.localScale.y scaleDelta, transform.localScale.z) yield return new WaitForSeconds(0.02f) This works for linear interpolation, but requires to write additional code and write even more code for non linear transformations. How can I achieve the same result with Mecanim? Sample project link https drive.google.com file d 0B8QGeF3SuAgTU0JWNGd2RnpUU00 view?usp sharing


How do I scale a motion capture animation? I used motion capture in my room using the Kinect. As I don't have much space I make compressed running moves, i.e. I put my legs up and down while not moving far forward. How can I stretch the animation, so me walking 1 meters amounts to the skeleton walking 3 meters or similar while not exaggerating movements to the left right?


Calculating the correct roll from a bone transform matrix Read this forum topic for more info http blenderartists.org forum showthread.php?260602 transform matrix to bone 28head tail roll 29 bug I'm trying to get my Blender3d modeller importer to create correct bones from my file's transform matrices. The Blender Python API doesn't have a way to do this (anymore!), so people had to dig the Blender C source to find out how Blender does it and port that. Here's a Python port of the needed functions, not by me (I don't know C) def vec roll to mat3(vec, roll) target mathutils.Vector((0,1,0)) nor vec.normalized() axis target.cross(nor) if axis.dot(axis) gt 0.0000000001 this seems to be the problem for some bones, no idea how to fix axis.normalize() theta target.angle(nor) bMatrix mathutils.Matrix.Rotation(theta, 3, axis) else updown 1 if target.dot(nor) gt 0 else 1 bMatrix mathutils.Matrix.Scale(updown, 3) rMatrix mathutils.Matrix.Rotation(roll, 3, nor) mat rMatrix bMatrix return mat def mat3 to vec roll(mat) vec mat.col 1 vecmat vec roll to mat3(mat.col 1 , 0) vecmatinv vecmat.inverted() rollmat vecmatinv mat roll math.atan2(rollmat 0 2 , rollmat 2 2 ) return vec, roll How to use them pos mymatrix.to translation() axis, roll mat3 to vec roll(mymatrix.to 3x3()) bone armature.edit bones.new('name') bone.head pos bone.tail pos axis bone.roll roll Sadly, it seems even the Blender C code is buggy and doesn't take into account cases when the bone is parallel to (0,1,0). So such bones can get assigned wrong (by 180 degrees) rolls and mess up animations. Does anyone have better code for generating roll which takes into account such cases? The old Blender 2.4 API generated correct ones. Its C code can be found here http svn.blender.org svnroot bf blender branches blender 2.47 source blender blenkernel intern armature.c I'm no C coder myself, again.


Compensate for animation time in multiplayer network game I'm developing a multiplayer turn based card game. In certain scenarios, the clients are required to perform an animation before moving on with the game. For example, the server informs the clients to animate dealing cards to all players. This animation takes around 5 seconds. Afterwards, the server informs a client to make a move, with a timer showing how long they have to play. How can the server wait for the animation to finish before moving on and starting a timer and informing a client to play? The timer obviously needs to start after the animations are complete. I've thought of the following 1) Hardcode the animation durations on the server side and delay sending out the next message to the clients until after the duration of the animation. 2) Have the clients inform the server when an animation is complete. ..but I feel that there should be a better way. Is there any other way to do this?


How do I spread a LookAt rotation over 3 bones with different percentages? I'm trying to rebuild the RE4 controller. At first, I thought that only the chest bone is used to rotate the pistol towards a target. I have then however found a hack to put the camera in a fixed position so that I could actually see the bone rotations. Juding the logic that I have recorded, I believe that first a LookAt rotation is used, and then this rotation is spread over the abdomen, abdomen2 and chest bones. Looking at the video that I have recorded, I think that the rotation is not quot divided by 3 quot , but procentually and then again changing towards the limits (for example, at the limits, the rotation is mostly done only by the chest). Can anybody tell me if my judgement is correct, and if yes, how to split a rotation this way? Would this be correct? gt The chest bone moves the most, the abdomen2 less, and the abdomen bone moves the least. In percentages chest bone 60 abdomen2 bone 30 abdomen bone 10 Let's assume a rotation of 200 . Am I right to assume that the rotation of each bone is calculated like this? Chest bone Gets 60 of 200 , that is 120 Abdomen2 bone Gets 30 of 200 , that is 60 Abdomen bone Gets 10 of 200 , that is 20 . Thank you! ps Here are a few screenshots, but it's much easier to estimate from the video


Following a path in a smooth fashion I am currently making a 2d tower defense game with a static, predetermined lane that the enemies follow (i.e. towers cannot block the path and path finding is not the problem I am trying to solve). I am trying to figure how exactly to make units follow this lane in a smooth way. I have two rough ideas about how to do this, but I would love some input on which is likely to be easier to implement the more standard technique. Or of course if I there is some totally different way that I haven't considered I would love to learn about that as well. Waypoints My first idea was to define the path as a series of hard coded waypoints. Units would then use a basic "seek" steering algorithm (such as this one) to move to each waypoint along the path in succession. However, I have wondered if it might be hard to keep the units from deviating to much from the lane I want them to follow. I wonder if inability to turn sharply enough might cause them to sort of "glide" out off of the desired lane. I suppose I might be able to prevent that though by allowing for a relatively strong steering force to be applied? Bezier Curves The second solution I have considered is to define the path with a bezier curve and at each time step calculate the point along the curve with is (dt speed) away from the unit's current location. I suspect that this technique would make it much easier to precisely define the path that units will follow, but I don't know know how exactly to go about implementing this. Any suggestions? Also, I don't this will change anyone's answers, but units also must be able to travel at a constant speed along the path. Additionally, I am programming this game in python using the pyglet framework. If anything about the question is unclear please let me know. Edit Also for whatever its worth, I'm sort of trying to replicate the movement behavior of enemies in the Kingdom Rush.


How can I generate isometric sprite sheets from 3D animations? I want to generate sprite sheets for an isometric projection of various 3d assets purchased from the Unity3D asset store. I'd preferably also render the normal maps. I am a programmer, but new to 3D modeling software (Blender, etc.) I found two tools for this SpriteForge and SpriteWorks, but neither supports enough formats to be worth their cost. There must be an efficient way of isometrically rendering various animations of a 3d assets in Blender mdash but I don't know how. How can I do this?


How to flip sprite and all collision children of a KinematicBody2D at the same time? I have tried to use the scale property of KinematicBody2D to flip at the same time the sprite and the collision area raycast children. For flipping, one just has to set scale.x 1. If it works in the editor, it does not work properly because the engine seems to reset scale.x to 1 each frame (as stated here) NB Here the original sprite is looking left (that is why it is blinking when going to the right, not very didactic sorry). How to do the same without flipping every collision children one by one?


Importing skeletal animation from vertex coordinates in maya I have files of different frames of an animation which have the vertex co ordinates of a human skeleton in 3D space. I want to import the animation from these keyframes into maya to perform motion retargeting. Please help me get some direction in this. Also is there any other way to retarget motion from one skeleton to other(different size) other than in maya?


How to implement scene changing in real time? I want to implement real time scene changing effects to make my game could changing from spring to summer, summer to fall, fall to winter. And Chaning effects like this game. Giana Sisters. I think Giana Sisters use animation to transit from two scenes, but I dont know how to make these animations. Is any other suggestions could make this effects?


Automated animation retargeting I am currently developing a video game using my own game engine I develop at the same time. While making a good progress in the past months, I am currently stuck. I assume I only miss a minor thing, but I need another pair of eyes and I really hope you can help me! I wrote a converter which reads FBX files (using the official FBX SDK 2017.0.1) and converts them into my own custom file format. I am able to read meshes, texture and material information, the skeleton and all animation stacks. In my game (engine) I am able to display the textured meshes and animate them with any of the read animation stacks. However, there is one problem for me. I bought meshes for NPC characters from a 3D artist and I also bought a huge animation pack from another artist. The character meshes include the perfectly textured and rigged mesh with all joints and the animation pack contains a rigged dummy mesh with all joints and animations. I want to be able to use any animation from the animation pack on any mesh from the character artist. My first step was to write a joint mapper. When reading the files I know which joint has which type. So, I am able to map the joints from the character mesh to the animation mesh and vice versa. The skeletons of both meshes are pretty similar and the mapping is going to work out. In the FBX samples the animation calculation for a given vertex is Inv(Mesh GlobalPosition Mesh GeometryTransform) Joint GlobalPosition Inv(Joint TransformLinkMatrix) Joint TransformMatrix Mesh GeometryTransform Since Mesh GeometryTransform is the identity matrix for all files I have bought, I can remove it from the term above. The result is Inv(Mesh GlobalPosition) Joint GlobalPosition Inv(Joint TransformLinkMatrix) Joint TransformMatrix Joint GlobalPosition is the transformation in Bone Space and the only matrix that is time dependent in this equation. Inv(Joint TransformLinkMatrix) Joint TransformMatrix is used to transform the World Space to the Bone Space, as I understood. Finally, Inv(Mesh GlobalPosition) is used to transform the result back to World Space. If I understood something wrong, please correct me!!! The joints which are used for the animation mesh are in a different space than the joints from the character mesh, because they come from different artists. I believe the missing part is to map between the joint spaces of both meshes. However, I do not know where to enter the mapping and I also don't know which spaces do I need to map? Object Space? Bone Space? I'd appreciate any kind of help and will reward a useable solution with credits in my game!