Dataset Viewer
Auto-converted to Parquet Duplicate
query
stringlengths
79
1.99k
positive
sequencelengths
1
31
negative
sequencelengths
120
120
cluster
int64
0
32
"Unclutter" units in RTS game For intentional reasons, certain units in the game I'm currently programming don't have any collision detection and response among each other. This enables them to clutter right on top of each other. This is a wanted behavior, since there will be situations in the game when the player does want them to stack like that. However, I want to make the process of uncluttering them easy for the player, so that they just have to press a hotkey or click some button on the screen and have the units disperse just enough so it's easy to select a group of them with the mouse (if they stand on top of each other one mouseclick selects all units). How could I do this without running a brute force N^2 nearest neighbor search on all units?
[ "Out of screen position to inner screen position I don't know how I could solve this.\nI'm trying to accomplish this:\n\n\n So if a object is out of my screen I would like to calculate the position it would be inside of the screen. Searched already but did not found any help for this problem. You can see this in games like cod where it shows you from which direction you got hit by a bullet.\n\nThanks in advance.", "Scrolling and Parallax scrolling in 2D game I'm developing a 2D side-scrolling game.I have a scrollable bitmap for background with size 2400x480.How can i scroll this bitmap?I have searched for algorithms but i can't find any solution.\n\nI know that i can do it with following code:\n\nfor(int i=0;i<100;i++)\ndraw(bitmap,2400*i,480);\n\n\nSo it will scroll bitmap for 240000 pixels.\n\nBut i don't want to draw images which stays out of screen(with size 800x480).\n\nHow can i render scrolling tile?How can i give velocity to it?(For parallax scrolling after normal scrolling)", "How to make a moving camera in 2d with p5.js I am trying to make a hill climb racing clone. My code: https://editor.p5js.org/saathvik/sketches/-XOFPcukt\nWhen I move the car, I want the camera to follow the player, so he can't go off screen.", "2D Physics in a networked game (iOS)? I am researching the possibilities for a new iOS game. It's going to be a run-n-gun type platformer, and I'm looking into the possibility of co-op multiplayer.\n\nThe game itself wouldn't be very physics intensive, there will most likely be 20-30 physics bodies at any given time. For the multiplayer, I think I would have one player \"hosting\" and up to 3 other connecting via the Internet.\n\nHere's my first question, are there any 2D physics engines that work over a network(preferably open source)?\n\nMy second question, Does anyone have any thoughts on using a non-networked engine (like Box2D or Chipmunk) and adding the networking component? Since there would not be very much information sent, do you think it would cause a lot of lag?", "What should I use instead of randomized start positions for good-looking 2D rain? Right now I'm randomizing the position of my 2D rain's spawn positions on both the X and, slightly, on the Y axis. It looks pretty weird right now, it has a bunch of huge clumps and unfilled areas:\n\n\n\nI want a more uniform, but not a completely boring and uniform distribution of my rain. I want something that doesn't look like a perfectly tiled texture, but doesn't look as crazy random as the picture above. What can I do?", "How would you handle different aspect ratios in a 2d platformer? A long time ago, 4:3 was pretty much the only apect ratio you would find on a PC. Today the most common one is 16:10, but most new monitors (especially laptops) are 16:9\n\nI'm writing a 2D platformer, and I can't decide how I should handle all the different ratios.\n\nHere are some ideas:\n\n\n4:3 gets more content, widescreens are cut on top and bottom\n16:9 gets more content, the others are cut left and right\nThe game is in 16:9 with black horizontal bars for other ARs\nThe game is in 4:3 with black vertical bars for other ARs", "How to implement swooping movement? I am trying to code some swooping behavior for a flying enemy in my 2D platformer.\n\nThe ideal behavior has the enemy starting from an arbitrary height above the ground, then accelerating downward and horizontally until flush with the ground, after which he slows and comes to a rest.\n\nI would like to code this in such a way that I can adjust a parameter controlling the steepness of the curve.\n\nIn other words, I want a kind of asymptotic movement, similar to this:\n\n\n\nhttps://www.mathsisfun.com/algebra/asymptote.html\n\nHow can I code this kind of movement in such a way that my enemy can start from any height and smoothly and elegantly accelerates down this kind of curve before gracefully stopping?\n\nI have recourse to all the usual stuff (for example, acceleration, velocity, friction, raycasts, etc.). I would prefer to code the movement using this stuff, rather than hardcoding movement along a curve or path.\n\nI was thinking it might be possible to achieve what I want by raycasting downward and getting the enemy's distance from the ground, and using this distance to adjust accelerations and velocities, but I'm not exactly sure how to go about it.\n\nI work in Godot, but would like an engine-neutral explanation of how to achieve this kind of behavior.", "How can I organize code for views efficiently? I'm making a video game for the Android platform and I need advice on the overall set up of the activities and views in the code. I don't need actual code, psuedocode will do, but actual code always helps. I will basically have the following:\n\n\nA surface view that draws bitmaps in a 2d scene and rearranges them according to what ever is happening on the screen.\nA main UI interface that needs to be shown on top of the surface view at all times that has buttons like the attack, defend, hotkeys and so on.\nA start menu as a seperate activity that the user can choose options like volume, orientation, graphics quality, save & exit and so on.\n\n\nAlso I want dialogs throughout the games that pop up when interacting with NPCs and these dialogs need to display pictures as well.\n\nThat pretty much encompasses the first version of the game. I will add complexity to it maybe later on down the road but for now I would just like a general plan of how to set all of this up in a functional way. Again code would be nice but I really just need an idea of how to efficiently do these things without wasting memory resources and utilizing the Android APIs capabilites with smart programming methods.", "How can a programmer learn to draw 2D assets? Are there any good tutorials for someone who wants to create 2D graphical game assets? Drawing classes for absolute beginners, preferably teaching skills that can be as relevant as possible to games - drawing characters sideways/top-down, isometric, drawing textures and such.", "How to make a text of several letters animate, only with an animation I wonder if it is possible to create an animation in a text with a single \"animation\". The problem is that for me to reach the desired effect I need to create an animation for each letter, as each one will appear a screen location. There is possibility to create this effect with just an animation? Remember that the deed is not the same as an animation into a sprite (one over another).\n\nI did the animation for entering each letter on the screen, Curve > Transform > Position. (in the picture I tried to simulate using arrows to input source for each letter).", "How can I make an attached gameobject behave correctly on character flip? I have a character that on start-up is equipped with another gameobject/prefab as a weapon, attaching it to a hand.\n\nvoid Start() \n{\n handFront = transform.Find (\"root/Hip/BodyBone/OverArmFrontBone/UnderArmFrontBone/HandFrontBone/HandFrontMount\");\n\n instance = (GameObject)Instantiate(Resources.Load<GameObject>(\"VioletClub\"), new Vector3(-0.5f,2f,1f), new Quaternion(0f,0f,45f,-45f));\n instance.transform.parent = handFront;\n}\n\n\nAs long as I move the character in the initial direction (right) the attached object behaves as it should, staying in the hand no matter the animation played. But when I flip the character, the attached object doesn't flip correctly. In the initial position (standing still) it looks correct but when I start to move the character, the item flips and rotates the wrong way. It does not follow the arm movement like it should.\n\n\n\nThis is what I do on flip:\n\nvoid Flip ()\n{ \n facingRight = !facingRight;\n\n Vector3 theScale = transform.localScale;\n theScale.x *= -1;\n transform.localScale = theScale;\n\n}\n\n\n\n\nWhen I flip the character back to the right again it all work as it should. \n\nCan anyone help me?", "Getting a TileMap wrapping as a toroid on player movement [libgdx version 1.9.13 - Desktop Game]\nThis question seems to have been asked many times, but I have yet to find a decent solution. I want to display a map without edges, where the player moves in all directions on a 'world' which is toroidal.\nI load my tiles into cells of an OrthogonalTiledMapRenderer, which I then render. This gives me a map which draws in the game window - works fine - but it has edges. The player can walk up to the edge of map.\nSo my questions:\n\nHow do I get a tiled map to draw without edges (I.E. no background color around edge of tile map, as per attached screen shot, which shows character about to walk off the map)\n\n\n\nHow do I then make the map toroidal - so the player moves off left map edge and is moved to right edge. Same for top/bottom. I can set the players coordinates to do this, but screen 'jumps' to the other edge.\n\nSo if the player continually presses a single up/down/left/right key, eventually they will come back to their starting position.", "How to Create Snakelike Objects I am working on a 2D action platformer in Python, though my question is a general one about creating snakelike objects which move in a variety of patterns.\n\nI have noticed this kind of object in many 2D games. For example, this boss in Contra has snakelike arms.\n\n\n\nAnd this enemy from Super Metroid clearly seems to be composed of multiple segments.\n\n\n\nI want to create snakelike objects in my game, though I don't know where to begin or what I may need to add to my physics engine to support them.\n\nSo far, all my enemies and hazards consist of single sprites and are programmed using simple attributes like velocity, acceleration, parametric curves, etc.\n\nMaybe I need to create a class for the segments, designate one segment instance as the leader, and update the positions of the other segments based on the position of the segment in front of it. But how do I program different patterns of movement? Do I need to learn about so-called joints and implement them between the segments? I currently don't have them in my engine.\n\nI know I could easily create a segmented object where each non-leader segment is moved to the previous position of the segment in front of it (like in classic Snake, described here), but I want more complex patterns than this. Sometimes I may want the object to be flailing from an anchored point, and other times I may want it to be following some pattern across the screen.\n\nI really don't know where to begin in trying to create this kind of object and would greatly appreciate any advice. \n\nHow do you implement snakelike objects with a variety of movement patterns?\n\n(Given the ubiquity of this kind of object in games, I was surprised that I couldn't easily find much about it online. I think a detailed write-up on it would be cool.)", "Procedurally generated 2d terrain for side scroller on Sega Genesis hardware? I'm working on the Sega Genesis that has a 8mhz Motorola 68000 CPU.\n\nAny ideas on how to generate fast and decent 2d tile terrain for a side scroller in real time? The game would generate new columns or rows depending on the direction the player is scrolling in. The generation would have to be deterministic. The same seed value would generate the same terrain.\n\nThe style of game would be a platformer like Sonic The Hedgehog. Maximum size would be around 1024 x 1024 tiles, but smaller could also work. \n\nA column or row doesn't have to be calculated every frame, just when a new one is needed. If the player moves 1 pixels a frame, then a new column is only needed every 8 frames.\n\nI'm looking for algorithms that would satisfy the memory and CPU constraints of the hardware.", "Calculating time until a ball fall How exactly can I calculate time until a ball fall if I know initial and final x and y position of a ball, gravity, delta time, initial dx and dy of a ball and its speed calculated from the formula sqrt(dx ** 2 + dy ** 2)?", "What is the best collision detection method or algorithm for a 2d platformer? I'm working of a 2d platformer.\nIt's a preety simple game, but the ground is flat and it looks boring. I did the collision detection for it and it's all working when the boxes are axis aligned, but I want to add slopes so it's more interesting. I researched a lot and I found the separating axis theorem but I read that it is not good for platformers because it's not side specific. So, my question is: what is the best way to detect collision with curves and slopes? I use javascript if you want to provide some code.\nThanks in advance!", "Switching from Arcade to P2 physics in Phaser so i just started using phaser for test\n\ni've followed the tutorial in the phaser website (making-your-first-phaser-game) everything is clear no problem .\n\nbut since i've making a pool game i need rotation on collision so i've switched to P2 ... suddenly everything moves and collides!\n\nhere is the live code\n\nhttp://199.26.84.223/\n\ni have 2 groups\n\nsides ( sides of table ) and balls\n\n1 - i want sides to be immovable so i 've added\n\nside.body.immovable = true;\n\nto each object like in arcade ... it doesn't work ... how can i make objects immovable in p2 ?\n\n game.physics.startSystem(Phaser.Physics.P2JS);\n\n sides = game.add.physicsGroup(Phaser.Physics.P2JS);\n side = sides.create(0,0 , 'sideA');\n side.body.immovable = true;\n\n\n2 - i dont want my player to collide with red balls only with white ball\n\nso in arcade we had to define each collision otherwise they wouldn't collide\n\ngame.physics.arcade.collide(player , wball ); \n\n\nbut here there is no defining everything collides with everything !\n\nhow can i make exception in ocllision so my player wouldn't collides with anything other then white ball (Wball) ?\n\n3 - what happend to overlap ? or collide call back functions ? i need to add some holes to my table and make the balls dissapir on collide or overlap ... in the arcade i had it like this\n\ngame.physics.arcade.overlap( balls , holes , killBall , null, this); \nfunction killBall ( b , h ){ b.kill() ; }", "Simulation of a two-masses connected by a rod 2D system I'm working on a multitouch-based interface and I want to add some physical behavior to gestures (pan, zoom and rotation). I thought model the system like that:\n\n\nWhen a touch starts, a point mass is created.\nAs the finger moves, I calculate it's velocity vector.\nWhen the touch ends, I suppose the mass is released and starts to move freely.\n\n\nMy problem comes when I have two masses (I don't need more than two masses to model this system):\n\nThe masses should act as if they were connected by a massless rod and, optional, they can slide along the rod with some coefficient of friction.\n\nI attach a picture to explain the thing better.\n\n\n\nI forgot almost all the physics I knew at college and now I'm a developer.\n\nI know that at time t the masses have a position (x, y), a velocity and one or more forces or accelerations acting on it. And I want to know those values at time t+dt.\n\nI would like to have some advice or approach to this problem. It's not about integrators or numerical analysis. My main doubt is about the rod constraint (keep the distance between masses) and the rotation movement.", "Subtracting magnitude from 2D circle contact I'm trying to create an agar.io clone. In agar.io, each player can have multiple cells that \"chase\" the mouse pointer. The cells can also have multiple masses and the velocity is tied to the mass. The bigger the cell, the slower it moves. The first picture in this question is a good representation of how this plays out\n\nThe cells can't overlap (mostly), so I've already implemented\n\n\ncheck to see if they are touching\ncalculate how much they overlap -> distance between circle centers, minus both circle's radius\ncalculate a push vector -> subtract the two centers, normalize the resulting vector, and multiply by overlap value\n\n\nThe above code mostly works, but in the regular game if you have a smaller/faster blob moving behind a larger/slower blob, the faster blob will start to slide around the larger blob. I'm not sure how to implement that.\n\nI think you should be able to calculate the normal to the point where the circles touch, and remove the magnitude of the \"chase the mouse\" velocity in the direction of the normal? I'm not sure how to do that. Math is not my strong suit.\n\nI took the idea for the circle collision from this link and I think my question of how to remove the velocity from the circle normal is in this link which talks about how to calculate the reflection off of a circle, but I haven't been able to translate that to code.\n\nI'm using C++, not that that matters.\n\nThere's also the open source agar.io clones, Ogar and Agar.io-clone, but I haven't found much digging through the code with how they handle that.", "How to smoothly move camera when the player is climbing a diagonal staircase in 2D tile-based side-scroller? I am working on a game, which is tile-based, similar to the way Terraria works. My player is 2 x 3 and can move over one-high obstacles, but this creates a very jittery effect, since my camera currently strictly follows the player. I was thinking of either somehow implementing a smoother camera movement or overhauling the player movement itself. I would love some feedback on how one might go about fixing this.", "2D open world MMORPG; big map memory problem I am developing an 2d open world mmorpg game for learning purposes, and have a issue with big maps. \nA year ago i developed 2d open world single player / co-op game. It saved map in chunks, and AI for NPCs starts 'ticking' when specified map chunk is loaded. \nIn my mmorpg game, NPCs AI is handled by server, and its always 'ticking' in some specified interval. That is where my troubles begin. I want NPC to walk in random directions. For this to work, I have to check map collision for every step, so my NPC wouldn't end up in wall. Problem is when I have big map, for example 10000x10000, and every tile is represented with 6 bytes, that is about 572MB of map data my server must hold in memory all the time, and i cant load just few map chunks, like in my single player RPG because of lot NPCs AI needs to be updated all the time, even if player is not located near by. \nMy goal is to archive map size of 50000x50000 tiles. I know its possible because i seen 2d mmorpgs with huge open worlds, a lot bigger then 50000x50000, and I doubt that their server have 20GB of ram to waste just on maps. \nIf anyone have any ideas how I can lower memory usage, I woud like to hear you. \n\nThanks in advance, and sorry for my bad english", "Given a point on a 2D grid of discrete points, and a normalized direction vector, how to I find the next point in that direction? Say you have a point on a grid, lets call it P and your have a direction vector called V, how do i find the closest point from P in V's direction ?\n\nExample:\n\n1|2|3\n4|P|5\n6|7|8\n\nV = (0.5 , 0.5)\n\nIn this basic example the next point is 3.\nHow do I make a general algoritm for more complex cases, say V = ( 0.44, -0.56) ?\n\nEDIT: Just to clarify something in my question. The next point has to be a neighbor to point P.", "How does one calculate the surface normal, in 2D collisions? I have a ball, which should bounce when it collides with a surface. I know the formula for reflections;\n$$ v_1 - 2n(v_1 \\cdot n) $$\n\nHowever, I cannot obtain the required information. I know:\n\nthe ball position,\nthe ball velocity,\nthe ball radius,\nthe polygon center\nthe polgygon width and height\nthe polgyon corner coordinates\n\n\n\nHow does one calculate the surface normal, in 2D collisions?", "UE4 Drag and Drop: Place PaperCharacter Over Image Widget I'm working on adding drag and drop functionality to my game. I have it working with the exception of I can't get what I'm dropping to be placed where it was dropped. I've tried a number of different things but I can't seem to get it to work.\n\nThe image shows my OnDrop with some leftovers of things I have been trying. And when I adjust the MakeTransform manually, a change of 1.0 seems to move the character much more than 1 pixel. The item I am creating in the OnDrop is a PaperCharacter.\n\n\nHere is an image from part of the level showing the result. The white blocks circled in red are UMG images so I can eventually adjust them to look better and change dynamically as the player is dragging. The player can only drop the item over one of there squares. This functionality works. But no matter which square I drop over the item always gets placed at the point circled in green or nowhere to be seen in the viewport. This is a 2d game so everything has to be in the viewport to be seen. The white squares are attached to a PaperSpriteActor. Not sure if that matters or not.\n\n\nWhat I need to have happen is when the player drops the item above one of the squares, the PaperCharacter must be dropped right in the middle of that square. How do I go about making that happen?\n\nEDIT\n\nAnother observation, if I manually set the MakeTransform location to 0, 0, 0 and drop the item on the same white square multiple times, the item is dropped in a slightly different spot each time.", "HTML5 Canvas 2D lighting and normal maps How using the HTML5 Canvas can I create a 2D game with light sources and also add an extra depth using normal maps. I have never really done lighting in 2D before and I'm not sure where to start.\nSomething like this:\n\nor\n\n(source: wholehog-games.com)", "Grid/cell based light system I am working on a top-down, 2d cell-based RPG game. I would like to implement a cell based lighting system, something like this and this.\n\nI basically have several light sources and light deteriorates on every cell in every direction. Something like the below (numbers represent the level of light in each cell):\n\n1 1 1 1 1 0 0 0 0 0 0\n1 2 2 2 1 0 0 1 1 1 0\n1 2 3 2 1 0 0 1 2 1 0\n1 2 2 2 1 0 0 1 1 1 0\n1 1 1 1 1 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0 0\n0 0 0 0 1 1 1 0 0 0 0\n0 0 0 0 1 2 1 0 0 0 0\n0 0 0 0 1 1 1 0 0 0 0\n0 0 0 0 0 0 0 0 0 0 0\n\n\nSo basically I insert a source of light of \"strength\" x at a given spot. I then set the surrounding cells' light strength to x-1 and so on until I reach zero (or a set global minimum value). I am looking for an efficient algorithm to implement and generate such a lightning grid based on my light sources and any tips regarding such implementation.\n\nI am currently not looking into field of view algorithms, just an efficient way of generating the above. Any help will be much appreciated.\n\nEDIT: Just to clarify, this should handle movement of light sources (e.g. player walking with a torch).\n\nEDIT2: Ok, I've solved my problem myself based on the simple distance suggestion by Jari (thus I'll accept his answer although I'm still looking for a more efficient way of generating such array). If anyone's interested here is a demo of what I came up with (multiple light sources with alpha compositing)", "What should my map creation workflow be for a turn-based tactics game? I am planning to make a tile turn-based game like Final Fantasy Tactics. Now, I am brainstorming of how can I implements the map arena system (the battle arena where there are block by block tile so that character can walk on) such that it is easy to merge an art consisting of whole arena terrain onto the game.\n\nI planned to create a full-map sprite, modelling it after a real place, then put it into the game. The problem is how do I code the program such that it will know the height and location of each tile out of a large single-sprite map? If I am to do that, then I should create some kind of editor that generate such data.\n\nIf I implements a tile by tile map creation, such that I use separate art sprite for each tile, then it would be hard to put the full map onto the game. I will have to build the map from tiny sprite, tile by tile.\n\nI would kindly ask any professional or people who have done these type of game before, which method would you suggest me to do?\n\nAnother question that I want to ask is, if any of you know, how does game like final fantasy tactics layout their background map to make it look 3D? Do they simply make a sprite tile created from an angled (user's ) view instead of flat sprite with top-view? Or do they simply use flat top-view sprite and maps it on a 3D plane/terrain ?", "Strange deviations while implementing alpha compositing I've been trying to create my own 2d renderer for my game (for learning purposes) and I'm trying to implement alpha compositing. The formula I'm using is very trivial, which is color = alpha * src + (1 - alpha) * dest.\n\nEverything seemed to be going and looking well until I started comparing it to existing 2d canvas implementations. I've tested my canvas against OpenGL, the JS canvas, and a BufferedImage in Java, and they have all been getting slightly different results to the formula I use.\n\nFor example, let's say I have a background with a red value of 1 and shape with a red value of 0.49 and an alpha of 0.026. From plugging in the values to the formula, I got a red value of 251.6187 (multiplying the original result by 255), which can be rounded to 252. However, every canvas implementation I've used returns a red value of 251.\n\nI'm keeping all my color values in a float between 0 and 1. However, I've tried experimenting with rounding it to increments of 255 and it still had no effect. For the js canvas implementation, I simply multiply the 0-1 by 255. (BufferedImage and OpenGl both accept a float from 0-1)\n\nHere is a program to illustrate the issue: https://editor.p5js.org/SarahJ/sketches/VTzi0r5c7\n\nI initially thought I needed to apply round, floor, or ceil function to my result, but while that helped this example, it caused problems for others.\n\nIs this not the alpha compositing formula that most 2D canvas implementations use, or am I doing something wrong? Any advice is appreciated. Thanks!", "Simple collision detection for 2D match 3 gems game I'm building simple match 3 game.\nI have the parts where I move the gems with the mouse only in the straight X or straight Y, up and down and both sides, no 45 degrees movements on grid.\nI'm looking for simple collision detection algorithm for the situation when for example:\n\na gem is moved up or down or left or right and there is another gem.\nHow can it detect it touched a gem and which gem it is?", "How to Simulate Height in a Tiled Top-Down Game How can I simulate height in a top-down tiled 2D game? One way I thought was to make tiles which are supposed to be higher brighter, but I was wondering if there was a standard or better implementation.", "2D Shader for affecting lights based on y-distance I've been struggling with this problem for a few weeks (mostly because I'm so new to shaders), but I have an angled camera for my 2D game that uses lights. \n\nI saw this link about the '3D light simulation' and wondered how the shader responsible was written. \n\n\n\nI'm in Godot, which uses its own shader language. I just need a way to compare the y-value's of the light source and the sprite. \nI found \n\nfloat d = (1.0 - (length(LIGHT_VEC)) + 1.0);\n float yoff = abs(VAR1.x * half_size_h / half_size_w);\n LIGHT_VEC.y += (half_size_h - VAR1.y - yoff) + z_offset;\n LIGHT = LIGHT;\n\n\nwhich lowers the vector from the light to the fragment, but I couldn't get what I needed out of that." ]
[ "Having trouble swapping elements I'm trying to visualize a simple Hanoi solver that uses an algorithm, and I'm swapping elements on array to visualize it.\nHere's my code:\n let A = [];\n let B = [];\n let C = [];\n let moveCount = 0;\n let once = true;\n hanoi(3, A, C, B);\n// 3, how many disk\n// A C B are rods\n alert(A + '.\\n' + B + '.\\n' + C + '.')\n \n \n function hanoi(n, start, target, other)\n {\n if (once)\n {\n once = false;\n for (var i = 1; i <= n; i--)\n {\n start.push(i);\n }\n }\n \n \n if (n <= 1)\n {\n let temp = start[n-1];\n start[n-1] = target[target.length];\n start = start.filter(Boolean)\n target[target.length] = temp;\n target = target.filter(Boolean);\n //console.log('Moving disk '+n+' from rod '+start+' to '+target+' rod');\n moveCount++;\n }\n else\n {\n hanoi(n-1, start, other, target);\n \n let temp = start[n-1];\n start[n-1] = target[target.length];\n start = start.filter(Boolean)\n target[target.length] = temp;\n target = target.filter(Boolean);\n //console.log('Moving disk '+n+' from rod '+start+' to rod '+target);\n moveCount++;\n \n hanoi(n-1, other, target, start);\n }\n }\n\nThe C value should be expected [3, 2, 1] but only shows 2. I also checked A and B and 1 is nowhere to be found\nHow do I make this properly so the output would be [3, 2, 1]\nImagine 3 is the largest disk and so on...", "Unpausing a game when a TouchScreenButton node is released I'm making a mobile game in the Godot game engine.\nI made a spike scene where the spikes will respawn at a random time in a particular position moving upwards.\nThen I instanced the scene in the main scene, it worked perfectly, the spikes moving up and appearing in a particular position.\nThen I created a TouchScreenButton node in the main scene and changed it pause property to process and then added a _OnPressed and _OnReleased signal to the main scene script then added this code to the _OnPressed function\nget_tree().paused = true\nAnd added this code to the _OnReleased function\nget_tree().paused = false\nBut when ever I press and release the button it only pauses the scene\nWhat should I do?", "Approximating a fourth point with a weighted average between three points? Given three points \\$p_1,p_2,p_3\\$, how would one approximate the best positive weights \\$(u, v, w)\\$ such that \\$u+v+w = 1\\$ and that the distance between the new \\$up_0 + vp_1 + wp_2\\$ from \\$p_3\\$ is minimal?\nBasically, the enemy's unit is positioned between several "bases" on a 2d plainand it's easy to tell which is closest or even find the "weights" between two bases \\$(t, 1-t)\\$ to compute the relative fractions (eg. 0.3, 0.7). How does one find the optimal weights for three surrounding points?", "How can I stop the player from drifting due to local input prediction when they stop? I'm working on a 2D server-client multiplayer game engine (which you can try here). It uses WebRTC DataChannels. (The connections are peer-to-peer, but the host peer still acts as a server.)\n\nThe biggest problem (apart from connectivity) is the local input prediction. We do the usual: On key press, players move instantly, tell the host what keys are pressed, receive data back from the host and compare it to the historical position. The position is corrected over time if there is a difference. This works well with low packet loss or PDV, even if the ping is high.\n\nIf there is loss or PDV, the deviation can be larger. I think this is because if the first packet indicating a change of input is delayed or dropped, the host finds out later, and starts changing that player later than their local input prediciton shows.\n\nIf the player is moving, we crank up the amount of applied correction, since it's less noticable. This seems to cover up gaps when starting to move and while moving. However, any correction is more noticable if they come to an abrupt stop. Then if the PDV or loss means the host thinks they stopped later, the host overshoots, sends back data saying they're a bit further ahead, and the correction makes the player drift a little. On flaky connections, players often noticably drift after coming to a stop.\n\nI've not noticed this in other games. How can this be mitigated?", "Can I speed up \"potential fields\" pathfinding when it's working on a large grid? I'm looking to implement a pathfinding algorithm that will allow me to throw hundreds of spiders at the players in my grid-based game. I can implement this with A*, but I'm worried that that algorithm has too high of a \"per spider\" performance cost.\n\nThe \"potential fields\" approach looks really good to me, but my map is quite large and rebuilding the entire potential field sounds expensive (even on a background thread).\n\nUnfortunately, there's no logical divisions on my map where I could separate the grid into smaller grids. And the map is quite dynamic (walls/bridges can be destroyed, which could have huge impacts on pathing).\n\nAre there any options other than reducing the size of the map?", "Can I \"unmerge\" merged meshes UE4? I set up my character to be modular, by following the UE4 docs.\nI used the code at the bottom of the page to implement mesh merging functionality.\nIt does work well, I can merge meshes runtime.\nI use this to add clothes to my characters.\nJust wondering, if there is a way to take off clothes, by unmerging stuff:\nSomething like:\n\nstore added clothes in a TArray or something\nthen call a function to remove the desired cloth from the array\n\nOf course, I would like to do it at runtime...", "Whats the most efficient method for controlling entities? I'm creating a tower defense game and I'm having logistical issues trying to figure out how to best have all of the enitites do their apporiate task.\n\nI have considered just constantly looping through a list of all the game entities calling a onAction() method, but I'm not sure if that is effective.\n\nI have also considered having each entity be a thread, but when I am dealing with hundreds of entities, some of which don't need thread time, I'm back to square one.\n\nCan I get any suggestions on a solid approach? Am I on the correct track with my first idea?\n\nThanks for any help ~Aedon", "How can I use collision lines to implement line-of-sight in GameMaker? I am making a GameMaker game that involves the enemies having line of sight so that they don't target the player through a wall. I have this code that uses collision line to detect whether there is a wall between the enemy and the player, then sets CanSee to 1 if true. \n\nif collision_line(x, y, obj_parent.x, obj_parent.y, obj_wall_parent, false, true)\n global.CanSee = 1;\n\n\nHowever, this code does not ever affect the value of CanSee. Am I using this code wrong?\n\nEdit:\nHere is my room setup. The walls all have obj_wall_parentas their parent.\n\n\n\nHere are some of the objects:", "Pygame top down shooter firing bullets I'm working on a top down shooter in pygame and am having trouble getting bullets to fire. I'm using a class for the bullets, I'll show what I think is the relevant code.\n\nThis is what I do after the mouse button is clicked:\n\nif event.type == pygame.MOUSEBUTTONDOWN:\n bullet_vel=[0,0]\n fired_pos=pygame.mouse.get_pos()\n player.fired=True\n bullet_pos_from_player=[0,0]\n\n\n bullet_pos_from_player[0]=fired_pos[0]-player.rect[0]\n bullet_pos_from_player[1]=fired_pos[1]-player.rect[1]\n bulletdistance=math.sqrt(abs((bullet_pos_from_player[0])^2) + abs((bullet_pos_from_player[1])^2))\n bullet_vel[0]=bullet_pos_from_player[0]/bulletdistance\n bullet_vel[1]=bullet_pos_from_player[1]/bulletdistance\n\n print bullet_vel[0], bullet_vel[1]\n\n bulletgroup.add(bullet((bullet_vel)))\n\n\nand here is my class for the bullet:\n\nclass bullet(pygame.sprite.Sprite):\ndef __init__(self, bullet_vel):\n super(bullet,self).__init__()\n self.pos=player.draw_pos\n self.image=pygame.transform.rotate(bullet_image, player.angle)\n self.vel=bullet_vel\n\n\ndef update(self):\n self.pos[0]=self.pos[0]+self.vel[0]\n self.pos[1]=self.pos[1]+self.vel[1]\n screen.blit(self.image, self.pos)\n\n\nHope someone can help out, \n\nthanks guys.", "How to improve my graphics on HTML5 canvas? I am making my own army fighting simulator. Designer have made an 3D model with Blender and textured it, made animations. I have made sprites from that model and did programming. But the result is not as good as I expected. You can look at armyfight.com/simulator.html (refresh until it loads all images properly if it didn't at first time) and when you maximally maximize, you can see there are units moving. But I want to be them clearly visible, with details, high resolution like in flash-games and also that when they are really small units, would be understandable.\n\nIs it possible on canvas? \n\nOr it is my mistake and I must do somehow more HD sprites? I'm stuck now, and I don't know to improve the graphics..", "Movement for Box2D Bodies I'm having trouble wrapping my head around something that should be relatively simple. I'm making a breakout clone using LibGDX and Box2D. I'm also using the Ashley ECS. For movement with bodies, I have two components - a BodyComponent (BC) which contains a reference to the Body that was created for the owning entity, and a PhysicsComponent (PC) which contains a velocity vector.\n\nWhat I'm currently doing is manipulating the PC's velocity vector when providing input, then setting the BC's body's linear velocity to the velocity vector in the PC. This allows my bodies to move how I want them to move but there are two issues:\n\n\nBodies have no maximum velocity\nIf the pad bumps into a static body, it should bounce. However it quickly snaps back to its original position because the PC's velocity is unaffected when bodies collides.\n\n\nHow can I manipulate bodies and make them move and interact with other bodies without the need to use another component for velocity?", "What is involved for a simple UDP game? I once tried to write a simple game with UDP in a week as a throwaway test. It went horribly.\n\nI threw it away early. The main problem i had was restoring the game state of all players/enemies/objects to an old state and fast forward the game to the point of time the player is playing (ie half a second before a jump. A little early or late can make the player miss the jump)\n\nMaybe this method is not the easiest way? i suspect it to be but i designed it wrong from the beginning and realized at the end of 2nd day. (so i didnt learn too much or wasted that much time)\n\nFor myself and others, What is involved for a simple UDP game and how do i write one? Or how do i solve the prediction problem restoring to state properly.\n\nI'll mark this as CW bc i know there will be lots of helpful answers.", "Bullet Manager Class I'm making a game in AS3, and it's a rather simple shooting game because I'm original. Anyway, probably the most subjective question here yet: what is the best way to implement bullets in my game?\n\nWould it be smarter to make a universal bullet manager class on the game that handles all the bullet related data or have every entity that has bullets (players, enemies) have this sort of 'bullet manager'? \n\nMake a level-wide bullet manager --or-- bullet manager for each entity?\n\nOh, and a side question: I actually have an enemy manager class. How would I check for collisions from the aforementioned bullet manager class.", "When the player collides with an entity, the player can no longer move Here is my collision code, any ideas on how I can improve it to fix the problem?\n\n public void collide(Entity entity){\n if(x + width >= entity.x && x <= entity.x + entity.width && y + height >= entity.y && y <= entity.y + entity.height){\n setShouldCollide(true);\n }else{\n setShouldCollide(false);\n }\n}", "How to achieve high Level of Detail on 3D models I'm developing a 3D space-based game which allows free movement in all directions and features planets. Currently I am using the Visual Studio content manager to import models (spheres) with 2D textures applied to them. These planets are supposed to be very large, which allows the player to come very close to their surfaces.\n\nFrom afar, the textures look great. Up close, however, they become very blurred or pixelated (depending on whether I draw them with linear or point clamp).\n\nI understand that I can enable mipmaps for the textures to change the level of detail shown at different draw distances, but obviously this can only be as high resolution as the texture files I provide it. The Visual studio content pipeline only allows Texture2D of size 2048x1024 or less and obviously I don't want to be holding enormous image files in memory for use in game.\n\nShould I produce a set of higher resolution tiles of small sections of the planet's texture, load them on demand and stitch them together? How would this be achieved in XNA?\n\nThe effect I'm looking for would be similar to google maps.\n\nIt may be that in the future, I will decide that the textures being blurred or pixelated is acceptable, but since this is much a learning process for me, I'd still like to know how it would be solved.\n\nBelow is a demonstration of what I mean using a Mercator map of the Earth as an example:", "3d complex collision and trigger detection I'm a Unity developer and I use monobehavior functions to dot things like collision detection. \nI have read about articles about collision detection. Most of them work with geometrical structures like sphere or boxes.\n\nHow are complex collisions with no formal and geometrical structures calculated?", "Should static tiles and dynamic tiles share the same parent class? I want to make an abstract Tile class for all of the tiles in a platformer game - walls, platforms, floor traps, everything. This parent class has basic things every tile will have, such as width and height, position, and boundbox, as well as getters for all of these things. I want to make these attributes constants, because those things typically shouldn't be changing - a wall shouldn't have its width and height changed, for instance. However, in some special cases, those attributes may indeed change - a special platform may change its height when the player jumps on it, or another special platform may disappear after 1 second after the player jumps on it, for instance. \n\nThis presents a problem, because for the static tiles, non-constant attributes in the Tile class is bad practice, but for dynamic tiles, constant attributes will prevent them from being dynamic. Is the best method, then, to create two different parent classes, which are the same, aside from one with constant attributes and one with non-constant? Is there a special name for dynamic tiles (I've heard \"entity\" thrown around, but I really don't know)?", "Preventing diagonal movement I was originally fine with diagonal movement but it's clashing with my sprite animation...\n\n public void keyPressed(KeyEvent e){\n int key = e.getKeyCode();\n\n switch(key){\n case KeyEvent.VK_W:{\n dir = 3;\n velY = -speed;\n break;\n }\n case KeyEvent.VK_S:{\n dir = 2;\n velY = speed;\n break;\n }\n case KeyEvent.VK_A:{\n dir = 1;\n velX = -speed;\n break;\n }\n case KeyEvent.VK_D:{\n dir = 0;\n velX = speed;\n break;\n }\n }\n}\n\npublic void keyReleased(KeyEvent e){\n int key = e.getKeyCode();\n\n switch(key){\n case KeyEvent.VK_W:{\n velY = 0;\n break;\n }\n case KeyEvent.VK_S:{\n velY = 0;\n break;\n }\n case KeyEvent.VK_A:{\n velX = 0;\n break;\n }\n case KeyEvent.VK_D:{\n velX = 0;\n break;\n }\n }\n}\n\n public void update(){\n y += velY;\n x += velX;\n}\n\n\nI thought that perhaps a switch statement or an if else statement would prevent multiple keys from firing at once, but it's not working out. I even tried synchronizing some methods but still to no avail. Any suggestions? And please ignore the dir variable I use it to find the direction the player is facing.", "How to setup animation based events without depending on an animation? How can I have events based off animations without relying on them? Take for example reloading in a FPS game. You'd hit a button to reload your weapon, the animation will play, then animation will hit a certain frame, then the weapon will be reloaded. There's a dependency on the animation eventually hitting that key frame before the weapon can reload and the character can go into another state. Without the animation, the weapon would never reload, and without some arbitrary timeout, the character would be stuck in that state forever.\n\nChecking for the existence of an animation is an option. However, this requires us to still know about some sort of animation, and what it's playing. Am I over engineering this? Would it be okay for the logic of some object to have some information about it's animations?", "Game runs at different speeds in Chrome versus Firefox I am using Box2D for physics on the server side.\nPlayer position is updated on the server, so there is nothing the client can do except give input.\n\nBut running game in Chrome only, the player moves faster as compared to running in Firefox only.\n\nIf running in both browsers (one player in each browser), then the game in both browsers runs at the speed at which it runs in Chrome.\n\nUsing this update loop:\n\nfunction update() {\n\n for(let p of players){\n\n if(p.dead) continue ;\n\n p.keyEvents();\n\n aabb.lowerBound.Set( p.body.GetPosition().x-p.s_w/(2*scale),p.body.GetPosition().y-p.s_h/(2*scale) );//top left\n aabb.upperBound.Set( p.body.GetPosition().x+p.s_w/(2*scale),p.body.GetPosition().y+p.s_h/(2*scale) );//bottom right \n world.QueryAABB( ReportFixture , aabb , p.id );\n p.socket.emit('players',foundPlayers);\n\n foundBodies.players=[];\n\n }\n\n world.Step(\n 1 / 60 //frame-rate\n , 8 //velocity iterations\n , 3 //position iterations\n );\n\n if(deletePlayerIds.length>0){\n deletePlayer();\n }\n\n world.ClearForces();\n}\n\nsetInterval(update, 1000/60);//to call update loop\n\n\nI have read that for Box2D there is no need to apply a delta.\n\nWhat could be the reason for different speeds, and how it can be resolved?", "What physics engine support force fields and bodies represented as points? I need a game engine that supports force fields in 2d or 3d, but suitable for 2d calculations, like bullet.\n\nEach body I want to simulate is represented as a set of points. Each point has positive mass and can accept force. Force field is updated every tick.\nEngine should accept force applied to every point and return point speed values and coordinates.\nEach body made of particles should move as a whole thing in result, relative position of particles must persist, hence this is a rigid body.\nIf engine does not support setting body as a set of points it should allow setting density function, or some other means to let have non-uniform density.\n\nIs there any that can do that, preferably cross-platform.", "How can I get six Xbox controllers to provide input to an HTML5 game? I'm creating a six player HTML 5 game designed to be played locally (Red Ice). \n\nI've previous set up handling 7 Wiimotes using something along the lines of Joy2Key to map each input for each player to a separate keyboard key, but Wiimotes are pretty hard on the hands for these types of games and not very ergonomic so I thought I'd try and get Xbox controller support.\n\nI don't believe that any simple key mapping solution will work due to the nature of the directional stick.\n\nMy inclination is that this will require a browser plugin and if so I'd prefer to write the plugin for Google Chrome. \n\nHow do I create a Chrome browser plugin to handle multiple Xbox controllers or is there some other way?\n\nPlease do not answer this question saying it can't be done, because it absolutely can.\n\nEDIT: I don't believe any keymapping/mouse simulating solution will work unless it can reliably distinguish six axis of inputs, one per player.", "What's the most efficient way to send a users keypresses to the server? So I've been coding a little project in JS recently, using node.js and socket.io to create a server, and HTML5 canvas to draw the client side. The user receives info from the server every 20ms, and the client interprets the data and displays it. If the user presses a key on the keyboard, it stores this information and sends it to the server instatly - so currently, the code is basically 'is keyboard pressed? if yes, send data to server'.\n\nThis has all worked great so far, however recently I increased the servers enemies (AI objects) from only 10 to a whopping 100... this lagged the server. Although I will work out enemy spawning efficiency later, the problem that immediately became apparent is that the user's character moved slower when the server was lagging. This meant that chasing enemies were able to easily catch up to the character and kill him, whereas usually the character could run away with relative ease.\n\nThis leads me to the question, what is the most efficient way that the server can interpret the keypresses of the user, and ensure that even if it is lagging that enemies will move at the same proportional speed to if the server wasn't lagging.\n\nSorry if this question is long-winded, any advice or help would be greatly appreciated. I assume that the same methodologies should apply from different coding languages, so if you have a vague idea how it works in a language you've used... please still share! :)\n\nThanks,\n\nCameron", "A* Pathfinding Gridless With Circles I found that A* is an algorithm for grid (or tiled) maps. I want to use it or some alternative of it to my game. The problem is that I have no grid. I have canvas and GameObjects could be at position { x: 23.91324512, y: 131.12334253461 }. How would you do this?\n\nAnd another question, I have element with stepSize (concretely called movementSpeed), and getPosition().getX(), getPosition().getY() AND getRadius() which returns the radius of a circle.\n\nHow would you do A* algorithm with radius?\n\nBtw I am implementing it in Java, so maybe some Java snippet would be helpful.\n\nEDIT\n\nAs you may suggest me to create a virtual grid, how do I check if I can move to the next node when I have my getRadius() and all the obstacles getRadiuses", "Isometric - precise screen coordinates to isometric I'm trying to translate mouse coords to precise isometric coords (I can already find the tile the mouse is over, but I want it to be more precise). I've tried several different methods but I seem to keep falling short.\n\nFor drawing I use:\n\nbatch.draw(\n texture,\n (y * tileWidth / 2) + (x * tileWidth / 2),\n (x * tileHeight / 2) - (y * tileHeight / 2))\n\n\nThis is what I currently use for figuring out a tile position:\n\n float xt = x + camPosition.x - (ScreenWidth/2) ;\n float yt = (ScreenHeight) - y + camPosition.y - (ScreenHeight/2);\n\n int tileY = Math.round((((xt) / tileWidth) - ((yt) / tileHeight)));\n int tileX = Math.round((((xt) / tileWidth) + ((yt) / tileHeight))- 1);\n\n\nI'm just wondering how I could update these to allow for more precise coordinates, instead of tile only.\nEDIT:\nFollowing what ccxvii said below, and removing the -1 from tileX, the object follows my mouse just like I had wanted. Just going to re-examine the math and figure out if that change will result in other messes =o", "How to handle keyup events in game loop? I'm writing a simple game in JavaScript, which already handles basic keyboard input like so:\n\nvar input = {};\nwhile (!done) {\n handleInput(input);\n update();\n render();\n}\n\ndocument.onkeydown = function(e) {\n input[e.keyCode] = true;\n}\ndocument.onkeyup = function(e) {\n input[e.keyCode] = false;\n}\n\n\nNow I need the game to handle key combos (like CTRL+X for example). I would like it to accept such combos on keyup only.\n\nTwo possible solutions that come into my mind are:\n\n\nexposing an array containing a list of keyup events (object with \"main\" key plus modifiers). The handleInput function would be responsible for draining the queue every time it polls it\nkeeping track of possible key combos inside handleInput (watching for held down modifier keys) and trigger the combo behavior when the \"main\" key goes up (I actually don't like this that much)\n\n\nWould you suggest me an elegant way to extend the current functionality?", "Graphical mesh lags behind collision shape in BulletPhysics debug drawing In Bullet Physics when I debug draw physics world the graphical mesh lags behind the collsion shape.\n\nm_DynamicsWorld->stepSimulation(1 / 60.0f, 10);\n\nbtTransform trans, trans2;\ntrans2 = m_RigidBodies.at(\"CubeMesh\")->m_Body->getWorldTransform();\n\nm_RigidBodies.at(\"CubeMesh\")->m_Body->getMotionState()->getWorldTransform(trans);\n/*\n * using\n * m_RigidBodies.at(\"CubeMesh\")->m_Body->getMotionState()->getWorldTransform(trans);\n *\n * causes the graphical mesh to lag behind the collision shape in DebugDraw call\n * Checking with debugger shows that the lag error keeps on increasing\n * */\n//\n//\nglm::mat4 M;\ntrans.getOpenGLMatrix(glm::value_ptr(M));\nm_RigidBodies.at(\"CubeMesh\")->GetGraphicalObject()->Model = M;\n\nif (m_DebugDraw) {\n m_DynamicsWorld->debugDrawWorld();\n}\n\n\nIf I use the OpenGL matrix from trans2 then debug drawing is perferct.\nBut with trans the graphical mesh lags behind the collision shape in debug draw.\n\nI am using btDefaultMotionState when setting the CubeMesh rigid body.\n\nbtTransform tr;\n tr.setIdentity();\n tr.setOrigin(btVector3(0.0f, 90.0f, 0.0f));\n cubeMesh->m_PhysicsBody->m_MotionState = new btDefaultMotionState(tr);\n\n\nCan anyone explain reason for this lag?", "Unity 4.3 (2D) Rendering only the parts of a sprite that are within specific bounds I'm working in Unity, using the 2D features to recreate the match-3 style of 10000000 (Ten Million).\n\nI have a parent object (green square) with several children objects (blue rectangles) on top of it, as pictured in the first image. I want to only render the parts of the child objects that are over top of the parent object, as shown in the second image.\n\nI can figure out the size and position of everything just fine, what I'm having trouble with is figuring out how to mask off the parts of the child objects that don't overlap with the parent.", "How to iterate through members of lists of members of lists within members of previous lists? I'm sorry for the clumsy title, and for what will be the continuation of further clumsiness in my question - I'm not even sure how to properly ask this, so please allow me to illustrate:\n\nI'm writing a game using XNA and C#.\n\nI have 'nodes' in 2d space, and I'm trying to create a network of nodes representing traverse-able world-space.\n\nThe nodes themselves store a list of their 'neighbors', and an associated dictionary that refer to how an AI might travel from one node to a node's neighbor, either by walking, or jumping.\n\n\n\nI'm trying to find a way that I may iterate from the list of one node's neighbors, to its neighbor's neighbors, to its neighbor's neighbor's neighbors, etc. etc. etc., to test each for contiguous neighboring connections based on whether or not they are all reachable to each other by 'Walk' (so I can find whole walkable platform segments).", "Way to Round Numbers I have it when the player clicks the mouse they can move the peice aoround the board. I am trying to have the chess pieces snap to a grid after the mouse has been released. Is there any way to round numbers so that I can round the X and Y coordinates so that it will snap to the grid?", "Implement resolution scaling HTML5 canvas I'm building an hmtl5 real time game using socket.IO and node.js. If you've heard of the classic game \"pong\", I'm going for that. When you consider the gameplay for this game, it becomes apparent that resolution scaling is something I'll have to implement. I'm running one instance of the game on the server (no graphics rendering, only physics), and of course once for every client. Each client's canvas is the size of the browser window so could be any resolution. \n\nWhat I'm wondering is how I should keep track of positions, velocities, etc. in the core game code. Should I use percentages and then multiply them by the respective screen sizes? Like x = 0.5 to store a position halfway across the screen? What's the best/standard way of doing this? Thanks so much.", "How to make touch events work in a match three type game In \"match three\" types of games like Crazy Kitchen, when the user touches an image, he can drag his finger over multiple images and create a change in each image he touches in a single gesture. You might drag your finger across 5 images and each image highlights as you drag across it.\n\nI want to create a similar affect in my game but I can only get the first image to change in a single drag or touch event. I have a GridLayout with each cell containing a custom LinearLayout with an OnTouchListener attached. I want to have the user drag across multiple cells and have each view the user drags across change its image to a \"highlighted\" image. \n\nHow do I get more than the first LinearLayout to be affected by the touch event?\n\nHere's my onTouch code:\n\n @Override\n public boolean onTouch(View view, MotionEvent motionEvent) {\n int action = motionEvent.getAction();\n FloorTile singleTile = (FloorTile) view;\n singleTile.getParent().requestDisallowInterceptTouchEvent(true);\n switch(action) {\n case MotionEvent.ACTION_DOWN:\n Log.i(TE, \"MotionEvent = DOWN\");\n //assign the new Arrow type to the FloorTile\n swapImage(singleTile);\n break;\n case MotionEvent.ACTION_MOVE:\n Log.i(TE, \"MotionEvent = MOVE\");\n singleTile.swapImage();\n break;\n }\n return true;\n }\n\npublic void swapImage(FloorTile mTile) {\n mTile.setBackground(this.getResources().getDrawable(R.drawable.highlight));\n//the actual game will pull a Drawable ID from an enum that matches up the original image with an //appropriate highlighted version.\n }", "Non-physics character movement in a Box2d Environment I am in the process of creating a physics platformer. However, I want the player movement to feel very old-school(as in: non-physics like), which means that the character:\n\n\nShould always move equally fast horizontally, even on slopes.\nHas a reasonably fast jumping movement. The 'normal'(earthlike) gravity that is the default of Box2d tends to feel floaty.\n\n\nNow, I have been trying lots of things to create a Box2d player that works this way. Multiple questions over the past few weeks are related to problems I've encountered with that:\n\n\nI increased the gravity and the density of the player to ensure they would jump/fall faster. (see this question)\nI worked with the 'unicycle' model(a square connected to a circle) to prevent getting stuck behind small corners. The bad part was that the player was now unable to stay on any slope, because they kept sliding down. \nTo prevent that, I learned that I had to keep the density of both objects low.(see this question) This again created the gravity problem. Also, while the player now was able to keep standing on slopes, moving up on them was still extremely slow (and moving down incredibly fast).\n\n\nI am getting a bit frustrated now over all this crazy behaviour that doesn't work the way I want it to. Now I am wondering: \n\nIs there something wrong with the approach to handle the player's movement outside of Box2d, and after that let Box2d resolve the new collisions with ground and objects? \n\nOr is this going to be extremely unstable and glitchy because I would 'teleport' the player instead of moving them with forces and is there still another, better way to get the movement I'd like?", "Using libGdx and Box2d for game and getting this error- \"incorrect checksum for freed object\" I am new in game development and I am using libGdx with box2d in my game, whenever I try to switch screen (both screens has box2d bodies with Tiled map), I encounter the following error.\n\n\n java(610,0x70000297a000) malloc: * error for object 0x7f8d642fd600: \n incorrect checksum for freed object - object was probably modified after being freed.\n * set a breakpoint in malloc_error_break to debug\n\n\nThe code which I use to switch screen is in render method \n\nif((mapPixelWidth - 200) <= frog.body.getPosition().x * PPM){\n game.gm.setPrefLevel(0);\n Gdx.app.postRunnable(new Runnable() {\n @Override\n public void run () {\n Array<Body> bodies= new Array<Body>();\n world.getBodies(bodies);\n for (Body b: bodies) {\n world.destroyBody(b);\n }\n }\n });\n game.manager.unload(\"maps/World1Level3.tmx\");\n game.setScreen(game.levelLoading);\n }\n\n\nApart from this error, I want to ask that the way I am using Asset Manager and Box2d bodies are correct or not?", "How to avoid 2d enemy using trigonometry? I'm making a game in Javascript & HTML5.\n\nI have a \"bullet\" (let's call it so) that needs to reach the enemy (at fixed position) and that need to avoid the enemy's \"bullet\".\n\nTo make the bullet move to the enemy i'm using this code:\n\nvar direction = Math.atan2(self.enemy.y - self.y, self.enemy.x - self.x);\nvar dir_diff = self.rotation - direction;\n// ... other code\nself.rotation -= dir_diff;\nself.x += Math.cos(self.rotation) * self.speed / dt;\nself.y += Math.sin(self.rotation) * self.speed / dt;\n\n\nHow can I make the bullet avoid another moving bullet?\n\nI tried to search but algorithms like A* etc. doesn't seem right for this.\n\nThank you.", "Detecting a sequence of nodes in a grid Given the image below, I need to detect the most optimal sequence on the board (the green line). The blue/red lines represent possible, but not the best moves.\n\nHere are the rules:\n\n\nYou can move to any tile that is the same, and is your neighbor (diagonal is valid)\nOnce you have visited a tile, you can't visit it again.\n\n\nI have thought about looping through each node, and looking at its neighbors, then recursively going through. Once I find a possible move I can put it into a structure. Once all possible moves are found I just pick the move with the highest count of node. It becomes more difficult when a node has more than one neighbor that matches.\n\nSo, is there some algorithm that I can use? I was thinking some sort of flood fill, but that doesn't meet rules #2.\n\nAs requested, here is a video of similar gameplay. http://youtube.com/watch?v=eumnCTG0AE8", "Should response be tied to request in a multiplayer game? I wonder if server responses on client operation requests should be tied by some operation id?\n\nTied would be when:\n\n1.Client app sends request to server to e.g. buy item X, and sets operation id as ID.\n\n2.Server responds with operation id and true or false.\nThis would mean that operation with that id was successful or not.\n\nUntied example:\n\n1.Client app sends request to server to e.g. buy item X\n\n2.Server responds with just an updated data of item X, where new item owner would be mentioned. \nThis way client can check if owner name is equal to it's own name and if true, assume that item was bought successfully. Same response data could be sent to other clients, to let them know that item X was bought by someone.\n\nWhich approach is better?\n\nIMHO untied is better and simpler in implementation, but it feels like there can be so many edge cases which I don't see right now.", "HTML5 Canvas: Get rect coords after rotation (relative to screen) update: function(delta) {\n for (var i = 0; i < this.bullets.length; i++) {\n this.bullets[i].velocity = this.bullets[i].speed * delta;\n this.bullets[i].contextX += this.bullets[i].velocity;\n }\n},\n\ndraw: function(ctx) {\n for (var i = 0; i < this.bullets.length; i++) {\n ctx.save();\n\n // Move the context to where the player is then make it face the target degree\n ctx.translate(this.bullets[i].startX, this.bullets[i].startY);\n ctx.rotate(this.bullets[i].rotation);\n\n ctx.fillRect(this.bullets[i].contextX, -5, 10, 10);\n ctx.restore();\n }\n}\n\n\nThe code above contains two methods that describe a class that manages the drawing and updating of bullets. The update method moves a bullet along and the draw function then draws it to the screen.\n\nThe canvas does the following:\n\n\nSaves the current canvas context state\nMoves the context to where the bullet originated from\nRotates the canvas to the way the bullet was facing when shot\nDraw the rectangle\nRestore the canvas context to original state\n\n\nHere is an image I have made that better describes what the canvas context is doing:\n\n\n\nSo we know the x position of the bullet but this is relative to the context as it's been rotated. What I need to know is the bullet's X and Y properties in relation to the actual screen. Any ideas as to how I can do this?", "Linux: find force feedback device for joystick device Because SDL 1.3 is still a long way coming I implemented native force feedback (rumble) support for Aquaria:\nhttps://bitbucket.org/panzi/aquaria/\n\nHowever, I could not find a way to find the according event device (force feedback device) for any given joystick (gamepad) device. I looked in the SDL 1.3 source and I thought this might be how it is done:\n\nstd::ostringstream os;\nos << \"/dev/input/js\" << sdl_index;\nstd::string jsdevice(os.str());\nchar evdevice[128];\nevdevice[0] = 0;\n\nint fd = open(jsdevice.c_str(), O_RDONLY, 0);\nif (fd <= 0) {\n std::cerr << \"Could not open joystick [\" << jsdevice << \"]: \" << strerror(errno) << std::endl;\n return;\n}\n\nif (ioctl(fd, EVIOCGNAME(sizeof(evdevice)), evdevice) == -1) {\n std::cerr << \"Could not get event device for joystick [\" << jsdevice << \"]: \" << strerror(errno) << std::endl;\n close(fd);\n return;\n}\n\nclose(fd);\n\n// ...\n\n\nBut it always just prints this:\n\nCould not get event device for joystick [/dev/input/js0]: Invalid argument\n\n\nCurrently I use an environment variable to indicate the force feedback device that should be used. Does anyone know how to automatically find the correct device? What I've got is the input device as an index (e.g. the 0 in /dev/input/js0) and therefore the path.", "How to make sure that when two bodies collide, there is only one collision detection on box2d? I'm using LibGDX with Box2D and, when two bodies collide, the collision is detected multiple times.\n\nHere's the code:\n\npublic void preSolve(Contact contact, Manifold oldManifold)\n{\n Body a = contact.getFixtureA().getBody();\n Body b = contact.getFixtureB().getBody();\n\n if ((Utils.IsPlayer(a) && Utils.IsEnemy(b)) || \n (Utils.IsEnemy(a) && Utils.bodyIsPlayer(b)))\n {\n player.isHit = true;\n player.destroy();\n System.out.println(player.isHit);\n }\n}\n\n\nThe player is destroyed multiple times; I want the player to be destroyed only once.", "UI/Menu that works with and without VR (Unity, WMR) I'm working on an app that I want to be useable without and with VR (with a Windows Mixed Reality HMD like the Samsung Odyssey).\n\nFor non-VR I'm simply using a canvas in \"Screen Space - Camera\" and a second camera, which is a child of the Main Camera and can only see the UI (the Main Camera can see everything but the UI). This way the menus are displayed as transparent overlays that are always visible to the player (with the game scene in the background).\n\nFor VR you have to use World Space. This makes sense because I want to be able to look around without having the menu move too.\n\nHow do you now make an e.g. pause menu work in VR AND non-VR - depending on if the player plugs in his headset before starting the app or not?\n\n\nDo you change the Screen Space to World Space in code at runtime if there's an HMD?\nDo I have to move the whole canvas at runtime to where the player is? You'd want the menu to be in front of the player, no matter where he is but it also has to be in front of the other objects in the scene, so you can interact with it.\n\n\nI'm using Unity 2017.3 with OpenVR/SteamVR.", "How to achieve smooth sprite movement with a scaled up canvas? I'm developing a simple 2d platformer using haxe & openfl (currently targeting flash). To achieve the old school pixelation effect I draw 16x16 sprites over a 4x scaled up canvas. With this approach character movement is very jerky since it seems to consist of a sequence of 4px jumps.\n\nSo my question is: how to be smooth & old school at the same time? Thank you for your time.", "How do I detect a given sprite's bounds automatically using Java? Background\n\n\n\nI have the following png file that contains the player sprite. \n\nAs with any png file, the non-colored pixels are transparent.\n\n\n\n(Width: 16px; Height: 16px)\n\nCurrently, I can erect a rectangle (collision-bounds), using java.awt.Rectangle around the image using the image's width and height, as seen below. \n\n\n\nI would like to crop the image so that the width and height are changed to the edges of the colored portion of the image, much like what is shown below. \n\n\n\nThis will allow for more accurate collision-detection between entities or objects in a game.\n\nI want to construct a method that handles this modification dynamically, as seen below.\n\n//Method calculates how far in from [top, bottom, left and right] \n//the [non-zero] or [transparent] pixel-data of an image are\n//in order to construct a new image that starts at the edges\n//of the colored portion of the image.\npublic BufferedImage adjustImage(BufferedImage image)\n{\n BufferedImage result = null;\n\n\n\n return result;\n}\n\n\nProblem\n\n\n\nHowever, I am uncertain as to the algorithm to use to achieve the result above.\n\nCan anyone give a step-by-step on how to detect these bounds and how to implement such a fuction as described above?", "Draw Ordering with Glowing Objects This is mostly a general design theory question, but for reference the bulk of my game is in JavaScript.\nI can draw images to the screen that layer on top of each other in the order that I please. One of the layers, I call it the light layer, is simply a series of black squares that change opacity based on the light levels in the game. During night, these black squares are almost opaque (unless a light source is affecting them) and during the day they are nearly invisible.\nGlowing things, like bulbs or radar console screens, are drawn above the light layer to make it look as if they're exempt from the light effect. (Glowing)\nHowever, the turret head is a non-glowing object that needs to appear above the glowing objects. For example, it might partially cover the radar console screen or light bulbs. However, it isn't meant to glow.\nThis is where the paradox occurs. The turret head needs to be below the light layer, but also above the glowing elements.\nAny ideas of how I could solve such a paradox?", "Ease action to simulate a clank in a moving or rotating device near end of the trajectory You know those mechanisms that moved or rotated, and then just a few millimeters near the end of the trajectory they oppose a bit of resistance and then clank to the final position.\nI want to simulate that clank with an ease function that can be combined with the standard ease actions. The link is for reference to some examples of ease transition functions, but I just need the pseudocode like this:\nfloat clankActionTime(float t) {\n if (t > 0.9)\n return (0.5*sin(10.0*t*2.0*M_PI)+2.0*10.0*t)/20.0;\n return t;\n}\n\nThat is what I have so far, which gives this graph for t between 0 and 1.\n\nBut I want something more like this:\n\nWhere A and B are parameters passed to the ease function to indicate where to star the clank and how deep is the valley near the end of the curve, respectively.", "Complex Models using bounding boxes in xna 4 I'm new to XNA, and have just started looking into collision detection.\nI've managed to get a bounding sphere around my first person camera object and i want to check the collision between that and the walls of my cube.\ne.g.\n\n\nthis is a cube i have built in Maya and it is 1 combined mesh.\nWhat i want to do i check my bounding sphere against the inside of the walls. and also allow the myself to enter in and out of the holes in the sides and th top.\nMy first thought would be using each vertex to test against collision but i have no idea how to do this, since this is the first time attempting.\nCan anyone point me in the right direction?", "Can Cloud Functions be used for a multiplayer game server? I'm building a turn-based online multiplayer game with Unity for both desktop and mobile.\n\nTraditionally, I would build a Java socket server, host it in Google Compute Engine or similar, and have players connect to it. Since this works with sockets I can easily notify players of relevant events, such as matchmaking, chat, enemy turn, etc.\n\nI've been curious about Serverless Functions for a while, such as Google Cloud or Amazon Lambda.\n\nHowever, at first glance it doesn't seem to me like that would work for my game: because there ins't a constant connection (with sockets), I can't notify players of relevant events in realtime - or can I?\n\nFor mobile I realize I could probably use something akin to push notifications (so the serverless code may push messages to the relevant player's phone). But that doesn't seem as simple for desktop games.\n\nWell, what if the players poll for messages? Like every second, call a Cloud function and ask them if there's anything for them.\n\nI'd image that would work, but that seems rather overkill - with as little as a couple thousand players, calling the same function every second for prolonged times (the game's matches are long) sounds like it would easily increase expenses.\n\nIs there something I am missing? A coding practice that would make serverless code feasible for a cross-platform online multiplayer game? I want to make it work, but it would seem like a socket server is still my only option.", "Why are entities in a component system composed at run time? Why are entity component systems the way they are? For example as far as I have seen it may look like this\n\nclass Entity\n list of components\n add component\n remove component\n update comentent\n ....\n\n\nSo you are building your entities at runtime. I assume it will look like this\n\n Entity ork;\n ork.add(AI).add(movement).add(physics).add(renderer)\n\n\nThe problem I see with this approach is that errors appear at run time instead of compile time. It also seems to add a lot of potential errors for example the AI system only makes sense if the entity also has a movement component.\n\nWhat is the advantage of building your objects that way instead of doing it like this?\n\nclass Ork: IEntity\n movementComp\n AiComp\n physicsComp\n rendererComp\n ....\n //wire everything together\n\n\nOne possible advantage that I can see is that object creation takes less code because you don't really need to wire up your objects, you just add your components and your done.\n\nWould you please enlighten me?", "How do i set gravity towards a point in the centre in AndEngine with Box2D? I have a scene and i can set gravity in the PhysicsWorld like \n\nthis.mPhysicsWorld = new PhysicsWorld(new Vector2(0, -SensorManager.GRAVITY_EARTH),false);\n\n\nbut i would like all bodies to gravitate to a point.\n\nI tried \n\nphysicsWorld.setGravity(new Vector2(centerX, centerY));\n\n\nbut that has not worked- i assume because i need to calculate the vector to the centre. But I'm not sure how to do that and where to calculate it so it changes.\n\nI would like the input (of force) to be from the touch handler of the sprite. The sprite at the moment can be moved via\n\n@Override\n public boolean onAreaTouched(TouchEvent pSceneTouchEvent,\n float pTouchAreaLocalX, float pTouchAreaLocalY) { \n\n //this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);\n\n if (pSceneTouchEvent.isActionMove() || pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionOutside())\n {\n this.setX(pSceneTouchEvent.getX() - this.getWidth() / 4);\n this.setY(pSceneTouchEvent.getY() - this.getHeight() / 4);\n }\n\n return true;\n }\n\n\nI would like to do the calculation in there so as the sprite is dragged, the vector changes, then when it's released it should 'fall' to the centre\n\nEDIT:\n\nMass can be set as 1 unit since it's not relevant\n\nThanks for the help.", "Determine the bullet / particle reflection off of a circle in node js using SAT lib functions I can see how the calculation should occur from other examples such as: How to bounce a 2d point particle off of a circular edge.\n\nBut I could use some help with the specifics for my inputs given during a game loop that is progressing / moving the bullet each game loop tick, and then detecting and handling collisions.\n\nI've tried to mock up an example nodejs script using the SAT lib\nhttp://requirebin.com/?gist=4a5c208dc39d3c3be262abb05fa791a3\n.. with the console logs tracing a few variables, including the output target vector.\n\nMy question essentially lies in understanding how I can use the SAT vector functions like dot() or reflect() to produce the reflection?\n\nhttps://github.com/jriecken/sat-js#classes\n\nEven pseudo code would help me understand what exactly the operation needed to determine the reflection point (not just the angle, but the bullets new target vector) given my inputs of a bullet x,y position colliding with and a circular wall.", "player keeps on firing (Javascript + Canvas) I'm brand new to game development (with Javascript)... I'm pretty sure my question is very simple, but I have a hard time to figure out myself... I'm starting at the very beginning, so this is pretty simplistic. \n\nThis is my whole code in javascript:\n\nvar fire = false;\nfunction keyUp(evt) {\n switch (evt.keyCode) {\n case SPACE:\n fire = false;\n break;\n ...\n }\n}\nfunction keyDown(evt) {\n switch (evt.keyCode) {\n case SPACE:\n fire = true;\n break;\n ...\n }\n}\nfunction update() {\n ...\n if (fire) {\n playerHasShot = true;\n shot.x = player.x + player.w;\n shot.y = player.y + (player.h / 2);\n shot.vx += 2;\n }\n if (!fire) {\n playerHasShot = false;\n }\n ...\n shot.x += shot.vx;\n ...\n //Bullet\n if (playerHasShot) {\n playerHasShot = false;\n }\n if (!playerHasShot) {\n playerHasShot = false;\n }\n ...\n if (shot.vx > 4) {\n shot.vx = 4;\n }\n ...\n if (shot.x > canvas.width) {\n shot.x = player.x + player.w;\n shot.y = player.y + (player.h / 2);\n playerHasShot = false;\n }\n ...\n render();\n renderShot();\n}\n\n\nI hit the spacebar once, and that guy can't stop shooting... Would any of you mind telling me how to stop him, please ? I'm sure I'm close, but there's something I'm missing somewhere.... Thanks! :)", "Approaches for a clickable map of nations (such as a Risk game) with Spritekit I would like to create a political map where each country is clickable by tapping but I'm not sure the best way to determine which nation was selected. Imagine Risk where each country can be individually clicked to bring up additional information. \n\nMy current approach is to make a sprite for each nation where every image is the size of the screen The images are mostly transparent except for the country, that way when all of the images are displayed the countries are in the correct place relative to one another. To determine if a click occurs on an individual country I look to see if the tapped location is a non transparent pixel and check that the sprite's name is one of the countries. Additionally the nation needs to glow or something when tapped as an indicator, however my current solution is yet another sprite that is displayed.\n\nThis seems like a terrible approach and I was wondering what other solutions might achieve the same results. I'm pretty new to SpriteKit so I'm not entirely sure.\n\nThe other idea I had was creating a single texture where each country is a different shade of gray, then when I get the tap location I do a lookup on the color at that location and get the corresponding country. However, I'm not sure how to create a hilight or glowing country effect with that method.", "How to simulate feather fall in box2d? I am working with AndEngine with Box2d extension, but general answer or a concept idea will be appreciated too. \n\nI have feather-like objects in a 2D side view world that I want to be part of the physics simulation. I am using linear damping to make the \"feather\" fall slowly. This might not be a good idea, maybe I should rather apply force in each update, but nevertheless, this works and it makes the object look \"light\" and it feels like there is air with resistance.\n\nNow how can I make the objects actually look like feathers falling through air? \n\nSpecifically I am looking for two types of objects: Long with low density, that should move down in a slow swinging motion and square objects that would just randomly change trajectory. It would be great if this could be one simulation and length would be a parameter - the longer the object is, the more it would swing. Right now I want to simulate feathers, leaves and snowflakes in a cartoon world.", "Collision detection not working in Phaser 3 I am new to phaser. So I started working on a game but I am stuck at implementing collision detection. I want to do it between a static group(dot) and a Sprite(obs).\n\nfunction create(){\n\ndot = this.physics.add.staticGroup(dotx, doty, 'dot'); \n\ndot.create(dotx, doty, 'dot');\n\nobs = this.physics.add.sprite(obsX, obsY, 'obs');\n\nthis.physics.add.collider(obs, ball, alert, null, this);\n\n\n}", "how did coordinate-handling in old flightsimulators work? Im currently working on a combat flight simulator pure for own fun.\nUsing a floating-origin i thought the float inprecision was history, however this was the case untill i tried adding multiplayer to the game. \n\nThe server is authorative and i'm banging my head around positioning the players on the server and handling the gun hits and collisions.\n\nUsing sectors i reset the origin of the clients but the server keeps the original position. This will lead into float inprecisions on the server, thus physic and collision checking are terrible. \n\nNow i'm just wondering how games like Airwarrior, Warbirds and aceshigh overcame these problems. What approach did they use? I'm assuming something else. If only i was able to use double precision, or even fixed point, but i'm tied to a physics model working with floats. I don't feel like changing that around, unless i have no other option. \n\nThanks for any pointers.\n\nstephan", "Is it more performant to index in the vertex shader or fragment shader? I have a shader that draws 2D quads from a texture atlas using instancing. I'd like to add a feature that allows me to map each of the RGBA channels in the texture using a 5x5 matrix. For example, the following would swap the red and green channels:\n\n0 1 0 0 0\n1 0 0 0 0\n0 0 1 0 0\n0 0 0 1 0\n0 0 0 0 1\n\n\nI only need a few of these transformations, so my plan is to provide them to the GPU as a uniform and then index into this by passing an attribute to my shader for each quad. I think there are two approaches I could take:\n\n\nLook up the 5x5 matrix once in the vertex shader and pass it to the fragment shader as a varying\nPass the index to the fragment shader as a varying and look up the matrix in the fragment shader\n\n\nI'm not sure which of these approaches would be more performant. My inclination is 1, because then the lookup only has to happen once per instance, but does that mean there's more overhead in passing 25 floating point numbers via the varying?\n\nBy the way, my graphics pipeline is WebGL if that makes a difference.", "Mobile game: Optimization only working on some devices / Render big texture causes stuttering after level load I'm currently optimizing the rendering of the background of my mobile game. The background consists basically of many colored dots. Since the background is static I'm able ro render the whole background into a 1024x1024 texture (render to texture), so the colored dots don't have to rendered in realtime (especially the blending is gpu intensive).\n\nUnfournately this \"optimazation\" is only an optimazation for certain devices.\n\n\nMy Notebook:\nWithout optimazation: 400 FPS\nWith optimazation: 800 FPS\n\nMy gaming pc:\nWithout optimazation: 1100 FPS\nWith optimazation: > 2000 FPS\n\n\nConsider that mobile devices have a frame cap of 60.\n\n\nSamsung Galaxy Nexus:\nWithout optimazation: 40 FPS\nWith optimazation: 60 FPS\n\nLG G2 mini:\nWithout optimazation: 60 FPS\nWith optimazation: 60 FPS, but with stutters after loading a new level, which\n disappear over time\n\n\nI don't have the slightest idea why the optimazation isn't working for the LG G2 mini.\nSo the LG G2 mini is faster at real time rendering many small colored dots but slower at rendering a single texture? It's also weird that the stutters only occur after loading a new level but vanish after a little time?\n\nGame is written in C++ using cocos2d-x, but I don't think its a cocos2d-x related issue.", "Find shortest path (quickly) on the surface of a 3d model? Imagine this scenario:\nwe have a 3d model, for instance a doughnut, apple or an orange (possibly something more complex). There's an insect (let's say an ant) on the surface of that food item. Now that ant wishes to reach a certain specific coordinate embedded on the surface of the 3d object in the shortest time possible (using the shortest path, ignoring physics).\n\nNow the ant AI could use Dijkstra on the original mesh but that might be low-res so the ant will zig-zag on the surface, outlining the shapes of blocky faces. You could split the faces but the angular nature of the edges, making up the structure of the mesh will continue to drive the ant to more in ziggy-zaggy like manner (imagine a rougelike with very small squares, you can still only move in 8 directions at any given point).\n\nWhat we did is split the edges (of the model) to evenly-sized pieces and embedded \"navigation vertices\" between these pieces, we then connected the vertices of each edge with vertices of other edges sharing a face with it (4 other edges because faces are triangular). This works pretty well cause it means the any can travel freely between faces, ignoring their shape almost completely (unless they are very small and were not split).\n\nWe also have the ant \"pulled\" (dragged even) by an imaginary ant that is a few steps ahead to completely eliminate the more rigid areas in the path (think sharp corners). Sounds great right?\n\nBut this is not terribly fast. Any advice about that is appreciated.", "Drawing thousands of isometric tiles per frame with a high FPS This question seems similar to other questions but no other topics I saw helped.\nI'm making a game in GML (GameMaker Language).\n\nRegardless of the language/software, this should be a universal topic.\n\nOkay, so I currently barely exceed 60FPS on a game with no code in the tick (step? frame? iteration?) so it should most definitely not be a CPU issue. My computer is fantastic and I can run nearly all (if not, all) games at ultra and high settings. Anyway, my game is isometric and tiles are 32x16.\n\nThe terrain data ds_grid (like a 2D array, but can't be jagged) is never changed except when loading other maps. I need the game to be played in a max of 1080p, and higher resolutions won't be implicitly supported.\n\nSo, I have a nested for-loop, to loop through a calculated minx/maxx and miny/maxy, basically defining the rectangular area in the terrain data ds_grid that I need to render. However, at the moment, in 1080p, after applying a variable called count to increment every iteration of the nested loop, I have nearly 8000 draw calls every frame, rendering every tile near the view.\n\nRemember, the tiles are both isometric and small, so there are a lot of things needed to be rendered. There are multiple grass tiles to reduce texture repeating. There is also a water tile, and I may add other terrain tiles. So basically, I need a method of rendering tons of tiles (that don't change) with a much higher (preferably at least 300) FPS.\n\nMORE INFO:\nin GM, a ds_grid is a data structure that is very similar to a 2D array, where the main differences are that it cannot be jagged (it's similar to a table) and any cell can hold any data type, so I could have strings and real numbers etc. all in the same ds_grid.\n\nMy ds_grid contains enumeration values, such as tile.grass or tile.water.\n\nThe terrain does not fit within the screen borders, and resolution directly affects view size.", "How do I check on non-transparent pixels in a bitmapdata? I'm still working on my window cleaning game from one of my previous questions\n\nI marked a contribution as my answer, but after all this time I can't get it to work and I have to many questions about this so I decided to ask some more about it. As a sequel on my mentioned previous question, my question to you is:\n\nHow can I check whether or not a bitmapData contains non transparent pixels? \nSubquestion: Is this possible when the masked image is a movieclip? Shouldn't I use graphics instead? \n\nInformation\nI have: A dirtywindow movieclip on the bottom layer and a clean window movieclip on layer 2(mc1) on the layer above.\n\nTo hide the top layer(the dirty window) I assign a mask to it. \n\nCode\n\n// this creates a mask that hides the movieclip on top\nvar mask_mc:MovieClip = new MovieClip();\naddChild(mask_mc)\n\n//assign the mask to the movieclip it should 'cover'\nmc1.mask = mask_mc;\n\nWith a brush(cursor) the player wipes of the dirt ( actualy setting the fill from the mask to transparent so the clean window appears)\n\n//add event listeners for the 'brush'\nbrush_mc.addEventListener(MouseEvent.MOUSE_DOWN,brushDown);\nbrush_mc.addEventListener(MouseEvent.MOUSE_UP,brushUp);\n\n//function to drag the brush over the mask\nfunction brushDown(dragging:MouseEvent):void{\n dragging.currentTarget.startDrag();\n MovieClip(dragging.currentTarget).addEventListener(Event.ENTER_FRAME,erase) ;\n mask_mc.graphics.moveTo(brush_mc.x,brush_mc.y);\n}\n\n//function to stop dragging the brush over the mask\nfunction brushUp(dragging:MouseEvent):void{\n dragging.currentTarget.stopDrag();\n MovieClip(dragging.currentTarget).removeEventListener(Event.ENTER_FRAME,erase);\n}\n\n//fill the mask with transparant pixels so the movieclip turns visible\nfunction erase(e:Event):void{\n with(mask_mc.graphics){\n beginFill(0x000000);\n drawRect(brush_mc.x,brush_mc.y,brush_mc.width,brush_mc.height);\n endFill(); \n }\n\n}", "How to remove jitter from motion input? I am writing a Minecraft mod that supports input from the Razer Hydra. It is a pair of motion controllers (one for each hand) that provide incredibly accurate position and rotation information.\n\nFor the purpose of this question, rotating the right controller on the Y-axis cause the player's character to look left or right (yaw), and rotating on the X-axis makes the player look up and down (pitch).\n\nThe input from the controller is mapped directly to the character's heading. If the controller is rotated 30 degrees left, the character turns 30 degrees to the left.\n\nThe problem is that the input \"jitters\". If I try to hold the controller perfectly still, the character's heading moves erratically within a very small cone (maybe 1 degree).\n\nThis is probably due to my shaky hands, as the controller's data is seemingly exact.\n\nI tried filtering input by averaging data from the last X frames, but this makes input seem buttery.\n\nMy question is: How can I filter the rotational data to remove jitter without loosing precision?", "Find mouse pos in 3D space? I have a game where there is a set of tiles rotated 45° away from the camera. I want to work out what tile is being hovered over by the mouse, and for that I need to translate the mouse pos on the screen into the position on the plane rotated 45° away. How can I do this? Is there an easy way of doing this without using (expensive) 3D transformation?\n\nThanks in advance.", "Bullet Physics - scaling I have added Bullet to my game engine. So far I am using translation and rotation, and it works fine. But now, I want to scale my geometry (eg. user can drink some potion an became small :-)).\n\nI am using \n\nbtWorldTransform.setOrigin(origin);\nbtWorldTransform.setRotation(rotation);\n\n\nto set position of bullet body directly (it is done only once in initial object placement in scene or in case of teleportation etc. otherwise position is updated by bullet and forces)\n\nNow, if I put object into scene, I set its btCollisionShape and that has some fixed size. Now, I change size of my scene object, graphics has scale, but what to do with bullet collision shape?\n\nI have found setLocalScaling method, but I am not sure if it is, what I want. Can someone verify this?", "Blending animations for more character movements I am making a hack n slash 3rd person game, and I want the character movements to be more dynamic not like fighting games where you have a moves list. \n\nI want to animate tons of different animations and have them \"Tween\" between each other. \n\nI do not want the to use the mouse for controls, I want it to be all keyboard, that way you have up to 10 inputs (All your fingers) to blend and morph animations to create more fluid movements. In the end this will almost be similar to characters typing a phrase or string of keys rather than move forward mouse look click to melee.\n\nMy questions are: \n\n\nHas anyone done this before?\nHow would someone go about trying to tween?\n\n\nlets say one for key on the keyboard excluding Tab, Caps, R+Shift, L+Shift, Enter, R+Ctrl, L+Ctrl, L+Alt, R+Alt, Windows Key, and Menu.\n\nSo thats all the numbers, letters and punctuation keys. Thats 46 keys gives me a combination of 46P1 = 5502622159812088949850305428800254892961651752960000000000L (used Python), and with a minimum entry value of 2 keypresses shortening to half. This is not humanly possible to create so many inique animations in one lifetime. But I'm guessing there is a reason this hasn't been done already. \n\nOr if I just used 10 basic keys. Maybe ASDF SPACE (RIGHT HAND) 456+0 (LEFT HAND KEYPAD)\nit would give me 3,628,800 posible unique animations.", "Adjacency in procedural generation of dungeon I wanted to make a procedural dungeon experimenting a new approach, it works nice for random-meaningless content (in example a procedural background to a level), however when I want it to be not-so-random I incur in some conceptual problem: basically I end up with a grid of numeric sector IDs in 2D.\n\nGrid example:\n\n27 | 56 | 74\n---+------+----\n35 | 31 | 115\n---+------+----\n14 | 52 | 12\n\n\nThe main problem is how to fix adjacency so that content is generated in a deterministic way:\n\n\nContent of sector \"31\" should be generated as a function of adjacent sectors (this works)\nHowever when I generate content for sector \"35\", I end up with a different link between sector \"35\" and \"31\".\n\n\nSo basically according from which direction I cross a sector I see a different passage each time (while the content of the sector is always the same).\n\nAs you see in the following image:\n\n\n\nThe passage between 35-31 is different according to which sector is used to start content generation, which is not what I want. I want the same passage arise.\n\nTo answer comments:\n\nsector[id].content = generateContent( sector[id].neighboursIds());", "How to tune the collision handling to respond differently depending on the collided objects? I'm making a collision handler for a Java game engine. I made an interface called Collidable. I have a method called onCollision which takes the parameter of my Engine Game Object. \n\npublic void onCollision(engine.objects.Object obj) {\n\n}\n\n\nI want to know how I can redo this so that I can give individual instructions for each Collidable object's onCollision method for how to collide with a Wall object or an Enemy object without having to write another method that has the parameters Wall and Enemy so that my engine is flexible. \n\nHow can I do this?", "Designing client-server to mitigate hosting advantage? My game will be client-server, and I'd like to prevent the hosting player from enjoying the usual benefits you'd associate with playing on a server. For example, the advantage of the server running ahead of time compared to clients. \n\nAre there simple ways of mitigating host advantage? Or do I have to make something complicated? My naive solution would be having the host run a \"ghost\" state, and a client state, on the same map. \n\nThe ghost state is an authoritative server simulation, it doesn't render the simulation which remains invisible, but does run ahead of time making calculations and decisions as usual. The host also plays a client on the same map, in which their input is regarded as any other client across the network, and like any other client is required to wait for the server simulation to make and transmit outputs. And so the host doesn't enjoy an advantage because they aren't playing the simulation which is making executive decisions on the game state ahead of client time. \n\nHas this solution been done by any other games, or is there a better way of handling the problem?", "Values or Struct-Like Location Class? I'm currently working on a 2D RPG, where the player character moves on a tilemap but is not constrained to the individual tiles. Every tile in a room is referred to by x and y coordinates to an Array. I'm considering using a Location class to store a float x and float y for the player character, as well as, perhaps, a Room. What are the advantages and disadvantages of this approach versus keeping the float x and float y values of the Player class (thus not creating a Location class)? \n\nCollision detection with walls, objects, and other players will need to be calculated.", "Simulating the effects of wind I am developing a mobile game for Android. It is a 3D jumping game (like ski jump) where wind plays a important role so i need to simulate it. How could I achieve this?\n\nThe game uses libgdx for rendering and a port of Bullet physics engine for physics. To simulate the jump I have 2 spheres which are placed at the start and at the end of the player and gravity is applied to them (they role down the hill and jump at the end). I use them to calculate the angle and the position of the player. If a button is pressed some extra y speed is applied to them (to simulate the jump before the end of the jumping ramp). \n\nBut now I have to add wind to it. How is this usually done? Which collision box/method should I use? The way I understand it I only have to apply some force with direction to the player while in mid air. How can I do this in Bullet?", "Pathfinding with lock and key? I'm working on a game with maps that resemble lock and key puzzles. The AI needs to navigate to a goal that may be behind a locked red door, but the red key may be behind a locked blue door, and so on...\nThis puzzle is similar to a Zelda-style dungeon, like this picture:\n\n\nTo get to the Goal, you must defeat the Boss, which requires going over the pit, which requires collecting the Feather, which requires collecting the Key\n\nZelda dungeons tend to be linear. However, I need to solve the problem in the general case. So:\n\nThe goal could require one of a set of keys. So maybe you need to get either the red key or the blue key. Or there could be an unlocked door the long way around!\nThere could be multiple doors and keys of a kind. E.g. there could be multiple red keys in the map, and collecting one will grant access to all the red doors.\nThe goal may be inaccessible because the right keys are behind locked doors\n\nHow would I perform pathfinding on such a map? What would the search graph look like?\nNote: the last point about detecting inaccessible goals is important; A*, for example, is extremely inefficient if the goal is inaccessible. I would like to deal with this efficiently.\nAssume that the AI knows where everything is on the map.", "Extra sprite spawning when the enemies are redrawn SFML I am making a game in sfml and at the moment when all of the enemies die. They are set to respawn however when this is happening they are respawning with one extra sprite than before. \n\nThe code for loading in the sprites is \n\nunsigned int orcNumber = 5;\nfor (int i = 0; i < orcNumber; i++)\n{\n SpriteVector.push_back(ogreSprite);\n SpriteVector[i].setPosition(spawnPointX[i], spawnPointY[i]);\n}\n\n\nThe code for removing the enemies if they are offscreen or shot is similar to below using erase.\n\nfor (unsigned j = 0; j < SpriteVector.size(); j++)\n{\n if (this->SpriteVector[j].getPosition().x < 0 - 80 )\n {\n //this succesfully removes the object from the vector\n SpriteVector.erase(SpriteVector.begin() + j); \n std::cout << \"Container size...\" << SpriteVector.size() << \"\\n\";\n }\n}\n\n\nThe statement for redrawing them is:\n\nunsigned int orcNumberRespawn = 5;\nif (SpriteVector.size() <= 1)\n{ \n for (int i = 0; i < orcNumberRespawn; i++)\n {\n SpriteVector.push_back(ogreSprite);\n SpriteVector[i].setPosition(spawnPointX[i], spawnPointY[i]);\n }\n}\n\nwindow.draw(SpriteVector[i]);\n\n\nCan anyone identify why when the sprites need to be redrawn it draws with + 1 sprite everytime?", "Getting an object to move in another objects direction I have a player and an enemy, both have x and y values, and I want to move the enemy to the player and have them 'touch' over time in a speed that I can determine, I tried calculating the angle between the enemy, the player, and the 0, 0 point on the canvas using trigonometry but it just doesn't work right, most the times the angle is Not A Number(NaN) or goes in a direction different that the player.\n*The code is not in the same file, I copy pasted the relevant parts of the code and pasted them together.\nHere is my code, any help would be greatly appreciated:\n\n// Creating a visual triangle and storing the length of it's vertices distance(size)\n line(enemy.x, enemy.y, 0, 0);\n lineOne = dist(enemy.x, enemy.y, 0, 0);\n line(player.x, player.y, 0, 0);\n lineTwo = dist(player.x, player.y, 0, 0);\n line(player.x, player.y, enemy.x, enemy.y);\n lineThree = dist(player.x, player.y, enemy.x, enemy.y);\n// Calculating the angle itself using the cosine rule\nangle = acos((lineThree * lineThree + lineOne * lineOne - lineTwo * lineTwo) / (2 * lineThree * lineTwo));\n\n//Function to move the enemy(based on a suggestion made in this website)\nthis.move = function()\n {\n if(angle != NaN && angle >= 0)\n {\n this.x -= 2 * cos(angle) + sin(angle) * 2;\n this.y += 2 * sin(angle) + cos(angle) * 2;\n }\n }\n\n\nThe if statement that checks if the angle is not a NaN value is required because it happens a lot for some reason, it also checks if it is bigger or equal to zero, because if it isn't the enemy just doesn't show at all.\n\nThank you for your time!", "How to make smooth animations Say I want to write a card game. I have a hand of cards and I want to be able to draw a smooth animation of a card moving from the hand to the table. I am looking for suggestions on how to elegantly represent the situation in data structures. Of course, I am not solely interested in cards, it seems to be a problem with more complex user interfaces in general.\n\nThe obvious representation of the hand is an array/list of cards. Given a rectangle in 2d space this hand is trivial to draw. When playing a card I can remove that card from the array and create a new structure that draws that card moving along any curve I like. The problem is then how the hand is drawn. In trivial implementation the hand in one instant shrinks in width by one card (as the array was replaced). Also, the selected card is now either above or bellow the hand (as it is drawn before or after drawing the hand), while a moment ago it was between the two cards next to it. These problems I'm not sure how to solve. They get even worse if trying to move several cards at once.\n\nIt would most likely work to make every card a separate body aware of it's position and movement in the plane (and possibly, the z axis to make overlaps work, as OpenGL allows this). It does seem like poor design to allow a system that almost always stays in a fixed shape too much flexibility. It also looks like a recipe for unexplainable bugs.\n\nI would like to hear from someone who has done this, what is the best approach. To put it briefly, \"specific and restrictive representation in data structures\" versus \"entirely free environment with some external limits\".\n\nThanks a lot", "Smooth out movement of the snake in a 2d Snake game I am working on a 2-D snake game in C++ with the SFML library. I would like to smooth out the movement of my snake as it looks extremely choppy currently.\nHow the Snake moves\nThe snake is made up of a list of parts. If I want to move the snake, I simply remove one part from the back (.pop_back()) and then add a new part in the front accrding to the velocity. This works perfectly. The speed of the snake must be the same as the distance between the parts. So if the distance is 15, the will be 15. But a speed of 15 is extremely high, so I need to only update the snake every few frames or use sf::Sleep(). Since the snake moves such a high distance every frame, the movement doesn't look smooth at all. And since the speed must be equal to the distance between the parts, reducing the speed doesn't work too. How can I come about tackling this?", "Testing Multiplayer Browser Game on Single Computer I am writing a multiplay browser based game and am running into an issue with playtesting simple interactions. When a browser window loses focus is stops running requestAnimationFrame calls. This effectively pauses the state all visuals when focus is lost.\n\nI would like to have two instances of the game running at the same time. I could playtest in one window and observe how a thirdparty would see those actions in another window. \n\nRight now I am only able to toggle between the two windows and see teleportation like behavior as the client state catches up to the new server state.\n\nI am not sure how, without setting up a second computer, I might test this. Anyone have any experience with this or any advice?", "Should I store local forward/right/up vector or calculate when necessary? I'm working on an object picking and translation/rotation/scale gizmos system in my engine where you select objects and perform transformations on them in a 3d editor-like fashion (e.g. Blender)\n\nIn my transform struct, I'm storing the position, rotation angle, rotation axis and a uniform scale value. When transforming my objects, I build the TRS matrix which forms my ModelToWorld matrix. All good.\n\nNow I want to add the notion of local vs world translation. i.e. you select an object, and you can either move it along its local x axis, or the global x axis.\n\nThe global movement is easy I just add directly to my position vector. But for the local one, I have to build a local forward/right/up vector. e.g.\n\nv3 GlobalUp = V3(0, 1, 0);\nv3 LocalUp = m4_Rotate(Rotation->Angle, Rotation->Axis) * GlobalUp;\n\n\nAnd then I translate my position by that amount:\n\nSelection->Transform.Position += LocalUp;\n\n\nI'm kind of torn whether I should store these local up/forward/right vectors in my transform (which means I have to calculate them once every frame in my update function, but every use of them after that point needs no calculation) or only when needed (no need to calculate every frame, but I have to call a function to do the calculation every time I need one, I could still keep the value in a local variable in my usage area if I'm using it more than once)\n\nI'm not sure what approach to go with but I'm leaning towards calculating them as needed.\n\nAre there any other pros/cons to each approach? or is this one of those things where there's no 'absolute right' way to do it?\n\nAny advice is appreciated!", "How do I fairly distribute resources among factories when resources are near exhausted? The main resource in my game is mass, stored as a floating point number that changes over time. Resource nodes increase mass and factories drain it. For example, if I have a resource node yielding 5 mass per second, I'll gain 5 * deltaT mass each game step. Mass is displayed rounded to the nearest integer, and gain/loss indicators are displayed by tenths.\n\nHow should I handle mass hitting zero? This creates a race condition if multiple factories are trying to build at once: Factories first in the queue or which drain less resource get priority once some more resource comes in and so build faster than the others.\n\nHow can I deal with this? Should I skip the step entirely?", "Designing a weather system for biomes in a roguelike I'm making a roguelike game similar to dwarf fortress. So far, I have an average temperature map and average yearly precipitation map generated with simplex noise. Now, I'm trying to implement a weather system that seems realistic, as in it rains more often in biomes with higher precipitation rates, but still seems coherent.\n\nSome of my thoughts on designing this system would be to have a weather object for each individual biome, and every time it rains (and the startup) it picks the next time it will rain based on the biomes precipitation rate. \n\nOne problem with this approach is that it would always rain within the exact edges of a biome, and I don't think it would look very realistic.\n\nAnother option could be to have cloud objects move around the map, and have them pick up water while in biomes with high precipitation rates, and when reaching the max, they rain.\n\nThis seems like a good approach to me that could be very realistic, I would just have no idea how to program the movement for the clouds.\n\nAny thoughts on a better approach or how to implement either of these to make them work?", "How to display a lot of small objects using WebGL? Introduction\n\nThe game scene contains a lot of 10x10 pixel elements: for 1980x1200 px. screen the number of elements on the scene can vary from 0 to 23760 (elements cannot intersect).\n\nThe live example: http://fintank.ru/game/\n\nThe entire game space comprised of tiles: each tile is responsible for some area and keeps elements for that area (similar to google maps).\n\nEach tile exist as 2 entities: S and G. S is a set of elements in the tile, G is rendered image of a tile. When the server put/remove elements to the tile, we change S and then re-render the G.\n\nTo draw a frame (at 20 fps) I just put the G of each visible tile using the putImageData(). That is done without WebGL.\n\nThe question\n\nWhat is the most CPU effective approach to implement such many-elements management using WebGL? Should I render each tile to a texture or each element may be implemented as a separate textured rectangle? The main concern is that each tile may be updated 30-60 times a second (elements adding/removal).\n\nHow to avoid memory leaks (how to reuse buffers?) if we make many new textures every second?\n\nWhat is the most effective way to manipulate pixels during rendering a 100x100 tile?\n\nHow to avoid re-uploading the unchanged textures to graphic card?", "How to make the inside of a cube accessible I have a cube, it is made up of smaller cubes each making the big cube 8x8x8. The cube is the map. The player of the game needs to be able to appraise the entire map and understand it without having to zoom through the inside of the cube since he may need to see opposite ends and interior at the same time. \n\nHow can I make this cube easy for the player to access? \nRequirements:\n\n\nPlayer must be able to see any 2 cubes at the same time, including the interior.\nPlayer must be able to understand depth of cube\nPlayer must be able to click on interior cubes.\nPlayer must be able to differentiate between allied/enemy soldier, and soldier class.\n\n\nif it helps at all, imagine if the rubiks cube had more cube inside it, obviously in the real world, we have no way to control them, but in a game, how would i allow someone to see and manipulate several at one time. Note: not a realtime game.", "Setting the values of a struct array from JS to GLSL I've been trying to make a structure that will contain all the lights of my WebGL app, and I'm having troubles setting up it's values from JS. The structure is as follows:\n\nstruct Light {\n vec4 position;\n vec4 ambient;\n vec4 diffuse;\n vec4 specular;\n vec3 spotDirection;\n float spotCutOff;\n float constantAttenuation;\n float linearAttenuation;\n float quadraticAttenuation;\n float spotExponent;\n float spotLightCosCutOff;\n};\nuniform Light lights[numLights];\n\n\nAfter testing LOTS of things I made it work but I'm not happy with the code I wrote:\n\nprogram.uniform.lights = []; \n program.uniform.lights.push({\n position: \"\",\n diffuse: \"\",\n specular: \"\",\n ambient: \"\",\n spotDirection: \"\",\n spotCutOff: \"\",\n constantAttenuation: \"\",\n linearAttenuation: \"\",\n quadraticAttenuation: \"\",\n spotExponent: \"\",\n spotLightCosCutOff: \"\" \n });\n\n\n program.uniform.lights[0].position = gl.getUniformLocation(program, \"lights[0].position\");\n program.uniform.lights[0].diffuse = gl.getUniformLocation(program, \"lights[0].diffuse\");\n program.uniform.lights[0].specular = gl.getUniformLocation(program, \"lights[0].specular\");\n program.uniform.lights[0].ambient = gl.getUniformLocation(program, \"lights[0].ambient\");\n\n ... and so on\n\n\nI'm sorry for making you look at this code, I know it's horrible but I can't find a better way.\n\nIs there a standard or recommended way of doing this properly? Can anyone enlighten me?", "How to make my multiplayer Air Hockey better? I've made simple multiplayer web game but don't like how it works. Here's a video example (captured at 85 avg ping) showing what I have.\nWhat I used:\n\nSuper naive client prediction - called so because there is no reconciliation - most of the time players' strikers can't be moved by anything except players themselves\n\nInterpolation (it's turned off on the attached video because at the current state of the game in combination with prediction it made things look worse. Without prediction input lag is unacceptably big)\n\n\nI've read some valve wiki articles, Gambetta's articles and some other not so popular sources, which helped to understand general ideas, but I still lack understanding on how to combine various techniques of minimizing delays for players and some implementation details. So here are the questions:\n\nWhat is the best way to sync time on client and server and when to start clocks? I should measure average ping and then what? Server sends notifications to clients 'start clocking in X ms' based on ping? Should they even start clocking at the same time?\n\nHow to improve user experience for my game? I guess I should probably use extrapolation for puck\n\nIs interpolation even needed with 60 tickrate for anything with 60 or lower hz screens? I'm not aiming at e-sports level experience and would rather make it feel nicer for 60 hz phone screens", "LibGDX moving game window with mouse drag TL;DR\n\nHow can I move window with mouse without tide effect.\n\nLong Version\n\nSo when I tried to move my game window via InputListener(just to test if it would work). I got some strange result. The window goes back and forth between last two locations when mouse drags and while button is held. \n\nGame Part\n\nGdx.input.setInputProcessor(new InputAdapter() {\n int b;\n @Override\n public boolean touchDown(int screenX, int screenY, int pointer, int button) {\n b = button;\n // TODO Auto-generated method stub\n Rectangle.tmp.set(0, 0, 100, 100);\n if (Rectangle.tmp.contains(screenX, screenY)) {\n lastx = screenX;\n lasty = screenY;\n System.err.println(\"Touch ( \" + screenX + \" , \" + screenY + \" )\");\n }\n\n return true;\n }\n\n @Override\n public boolean touchDragged(int screenX, int screenY, int pointer) {\n if (lastx != null && tr != null) {\n tr.translate(screenX - lastx, screenY - lasty);\n System.err.println(\"Drag ( \" + lastx + \" - \" + screenX + \" , \" + lasty + \" - \" + screenY + \" )\");\n lastx = screenX;\n lasty = screenY;\n }\n return true;\n }\n\n @Override\n public boolean touchUp(int screenX, int screenY, int pointer, int button) {\n lastx = null;\n lasty = null;\n System.err.println(\"Up ( \" + lastx + \" , \" + lasty + \" )\");\n return true;\n }\n});\n\n\nDesktopLauncher Part\n\nGame.tr = new Translator() {\n\n @Override\n public boolean translate(int x, int y) {\n Display.setLocation(Display.getX() + x, Display.getY() + y);\n return true;\n }\n};\n\n\nPS: What I try&tried to make may look stupid.\n\nEdit: Actually I noticed that window moves less than actual mouse movement.\nEdit2: When I move the movement code to touchUp I get exact result as movement.", "How can I get visually accurate collision normals with sphere collisions? I'm solving simple 3D sphere collisions by checking the sphere for overlap with a mesh, finding the nearest point on that mesh's surface to the center of the sphere, and then resolving the collision by moving the sphere out of the mesh using the normal and the penetration distance.\n\nTo find the normal, I'm using the normalized vector from the nearest point on the mesh to the center of the sphere.\n\nNow I'm trying to resolve a collision where the sphere has overlapped more than one collider. How I'm currently solving it is by iterating through all the meshes and checking to see if the last correction solved the collision.\n\nIn the scenario shown in the bottom image, this can cause a problem when trying to determine a collision normal. The two collisions return two different normals, as they should (Though, Depending on which collision was resolved first, the correction from the right box would solve the collision with the left box, in which case there would only be one normal).\n\nNow, mathematically, that all makes sense, but visually causes a problem. If I'm trying to determine a single normal to, say, bounce the ball off the surface create by those two meshes, any normal that takes both collision normals into effect would be inaccurate. Visually, one would expect the collision normal to be straight op, but since one of the collision normals is at an angle, I would need to somehow determine that that is a sort of \"false\" normal.\n\nThe solution that comes to mind is to order the collision checks by their distance from the sphere, thereby ensuring that, in that scenario, the angled normal never even comes into play. Is this an accurate way to do this, or would that cause other problems I'm not seeing?", "Collider inside collider in MRTK VR: Move the brain via controller while being able to click the spheres I faced a similar issue in 3d unity,\nCollider inside another collider: Move the brain via mouse while being able the click the spheres\nThere is a box collider on the brain and individual sphere colliders on the spheres.\nOne of the suggestions was setting up a layer mask with the mouse, which worked surprisingly well. Now I would like to be able to accomplish the same in MRTK with Windows Mixed Reality Controllers. I need to know how to set up a similar layer mask for the pointers in MRTK so that clicks are only registered on the spheres but the brain can be rotated by click and drag.", "How to render texture into box2d objects from Tile Map? Libgdx I have a problem, when i try to render textures. I read positions of gameObjects, for example coin and create box2d objects circle shape. I have wrote game logic and began make a graphic. But for some reason, textures drawing not in box2d objects, but they shifted to the right and up as mini-map in games. \n\nCode\n\n batcher.begin();\n\n sprite = new Sprite(AssetsLoader.coin);\n\n sprite.setPosition((body.getPosition().x - sprite.getWidth()/2), ((body.getPosition().y - sprite.getHeight()/2)));\n\n sprite.draw(batcher);\n batcher.end();\n\n\nThis is what happened\n\n\n\nAs you can see above, sprite position like body position. And something else: when i move my mainHero all rendered coins moving with him. On the screen they save their position, but in world they are moving. So how i can render coin texture exactly into box2d body.\n\nMay be something wrang with camera?\n\ncam = new OrthographicCamera();\n\ncam.setToOrtho(false, 400, 600);\n\n\n\n\nor with Batcher?\n\nbatcher = new SpriteBatch();\n\nbatcher.setProjectionMatrix(world.getCamera().combined);\n\n\n\n\nI will not give all my code, because it is big and no one will try to understand it.I need an idea or just an advice or a hint. Sorry for my English, hello everyone from Belarus :) Where do I look and what a start? Thank you.", "Moving a sprite in XNA/C#, using vectors I'm currently looking into XNA game development with the C# language.\n\nI have two classes: the main game handler and a \"sprite\" class. Following is some basic pseudo-code which I hope adequately describes the issue.\n\nGame.cs\n\nclass game {\n sprite the_sprite;\n void update(time) {\n var mouse = mouse.state\n if(mouse.clicked) { this.the_sprite.moveTo(mouse.x, mouse.y) }\n this.the_sprite.update(time)\n base.update(time)\n }\n}\n\n\nSprite.cs\n\nclass sprite {\n vector2 location;\n vector2 move_to;\n void moveTo(x, y) { this.move_to = new vector2(x, y) }\n void update(time) {\n if(this.location.x > this.move_to.x /* (or less than) */) {\n // adjust location.x\n }\n if(this.location.y > this.move_to.y /* (or greater than) */) {\n // adjust location.y\n }\n }\n}\n\n\nBasically: when the user clicks somewhere in the game window, the x and y coordinates of the mouse are taken, and the game object will move towards that location over a period of time.\n\nWell... the code works, but it's ugly, and objects don't move directly towards the object (instead, it's diagonal movement, followed by single-axis movement). I'm guessing there are some mathematical functions I can use, but I honestly haven't a clue where to get started. Any suggestions?", "Using Windows 10 Multi-Touch Functionality In Gamemaker: Studio I have a multi-touch monitor that I am using in Windows 10. I am getting visual feedback on the monitor itself that multiple touches are being recognised. However, within my Gamemaker game, I cannot seem to recognise any other touch than the very first one. From the documentation, it seems that I should be able to just use the device_mouse functions, using 0,1,2,3 and 4 to stand for the different 'mice' that each press represents. However, this does not seem to work at all, for example in the following code:\n\nif device_mouse_check_button(0,mb_left) {\nNumber = 1\n}\n\nelse if device_mouse_check_button(0,mb_left) and device_mouse_check_button(1,mb_left) {\nNumber = 2\n}\n\n\nCan anybody shed some light on this problem? I cannot work out why this doesn't seem to be working. It recognises the first 'mouse' press, but as soon as I add the second finger it stops working.", "Rendering terrain only with GPU This is not about generating plane geometry and then applying a shader on it. Instead, I want a big single flat plane, then apply a shader on it.\n\nThe vertex shader has a uniform vec3 realPlanePosition and calls a height calculation function:\n\n// Vertex shader code\n\nuniform vec3 realPlanePosition;\n\nvarying vPosition;\n\nfloat heightCalculation(vec2 verticePosition) {\n // Just for pseudo-code (more black magic append here).\n return magicNoise2D(verticePosition.x, verticePosition.y);\n}\n\nvoid main(void) {\n vec3 vPosition = position;\n vec2 verticePosition = vec2(vPosition.x + realPlanePosition.x,\n vPosition.y - realPlanePosition.z);\n\n vPosition.z = heightCalculation(verticePosition);\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4(vPosition, 1.0);\n}\n\n\nIn my plane update code, I just change realPlanePosition with player position, for example. The plane moves on (x, z) (X rotation: -PI/2.0). The only thing the vertex shader updates is the z (due to plane rotation) value of gl_Position.\n\nIs this good practice? Also, how do I detect collisions with it? And finally, how can I control other terrain objects' generation (rocks, trees, ...)", "Turn based game - how to deal with partial world state updates? I'm implementing a simple \"turn based\" game where the player sets up a bunch of \"actions\" on a board and \"objects\" move on the board and are influences by those actions. The player is no longer involved after setting up the board and just watches the actions play out. Each \"turn\" of the game loop, a \"move right\" action will move any objects on its square one square to the right, for example.\n\nMy problem is now that each time I run the game loop, all actions are executed as follows:\n\nfor(auto& go: gameObjects) {\n go->update();\n}\n\n\nEach of these game objects mutates the world state in its update() method. What I'm seeing now is that when the board is updated by one object, the next one will immediately use that updated board state and perform its action \"too soon\".\n\nFor example: When I place three \"move right\" actions on the board and run the game loop, the object will be moved three spaces in one \"turn\" while it should actually take 3 \"turns\" for the object to move through all 3 of those actions.\n\nHow can I delay the board state update until all actions have had their chance to decide what to do? I'm considering two strategies:\n\n\nCopy the board state for each turn and create a new board state as the result of a turn. This is complicated because all my views are tied to the objects on the board. If I copy the board, I'll have to re-create all views?\nHave each action not update the world state, but only return a function which, when executed, will do the update. Once I have all the functions collected, execute them all to update the board.\n\n\nAny suggestions?", "Tetris: 2D Rotation Matrix? I'm creating a Tetris clone right now. I've got the tiles of tetromino stored as an std::array<tile, 4>. Each tile holds its (x,y) coordinates relative to the piece. For example, the t-block is:\n\n(-1, 0)\n( 0, 0)\n( 1, 0)\n( 0,-1)\n\n\nI want to create a function: rotate(const bool clockwise) that applies a 2D rotation matrix to the tiles to rotate the block either 90 degrees clockwise, or 90 degrees counter-clockwise.\n\nAfter doing some reading on rotation matrixes, I've found that a 2D rotation matrix looks like this:\n\n cos(angle), sin(angle)\n-sin(angle), cos(angle)\n\n\nSince I'm doing 90 degrees only, I figure it should look like this:\n\n//clockwise\n 0, 1\n-1, 0\n\n//counter-clockwise\n 0,-1\n 1, 0\n\n\nAfter doing some more reading on how to multiply matrixes, multiplying the tile position by the matrix gives me this:\n\n//(-1, 0) should end up as (0, 1) if rotated clockwise\n\n-1 0, 1 1,-1\n 0 /*multiplied by*/ -1, 0 /*gives me*/ 0, 0\n\n\nMy question is how do I get an (x,y) position out of that result? Am I missunderstanding how matrixes work? Is there a more trivial way to rotate coordinates around the axis by 90 degrees?", "In-Game Tutorial Decisions I'm working on a game with confusing mechanics such as energy storage and the coolant temperature. What is the best way to get a new player learned quickly? What are the pros and cons of different in-game tutorial methods? I was thinking of a tutorial with annotated screenshots, but that makes it sound like a science textbook (\"Active towers are towers that consume energy and may generate heat.\"). \nOther ways include:\n\n\nin-game tutorials, which is somewhat difficult to program\ntips that will show in-game and after game over\na reduced difficulty without the energy and coolant things", "Detect collision point I'm writing a 3D rigid body physics engine, I am using OpenGl for simulation.\n\nOnly convex objects are considered. \n\nMy question involves how to detect the point of collision, so that when I apply a response force, I can also calculate torque.\n\nI have used SAT algorithm to detect collision according to this reference,\n\nEverything seems to be work fine , But as i get SAT only gives for objects are they colliding? as well as by how much?, it does NOT give you a reference point at which to apply the response force (and thus calculate torque).\n\nI have looked at\n\nResource 1\n\nResource 2\n\nResource 1\n\nNone of them seems to be an answer", "C# Unity3D FPS apply damage to an enemy (Weapon bullet) I am kindly new to Unity3d and c# and I don't understand how I could let a bullet deal damage to an other object. I've seen a lot of JS tutorials but no for C#. I've tried to use them, but it wont work. My code I've tried: For the Bullet (Prefab)\n\n using UnityEngine;\nusing System.Collections;\n\npublic class MoveBullet : MonoBehaviour {\n\n public float speed = 10.0F;\n public float damage = 10.0f;\n\n // Use this for initialization\n void Start () {\n\n }\n\n // Update is called once per frame\n void Update () {\n\n transform.Translate (0, 0, speed);\n\n\n }\n\n void OnCollisionEnter(Collision col){\n\n col.gameObject.BroadcastMessage(\"ApplyDamage\", damage);\n\n\n\n }\n}\n\n\nAnd the one for the Enemy: \n\npublic class enemyhealth : MonoBehaviour {\n\n public int health = 100;\n\n // Use this for initialization\n void Start () {\n }\n // Update is called once per frame\n void Update () {\n }\n\n void OnDamage(){\n health--;\n if (health <= 0) {\n Destroy(gameObject);\n }\n }\n}\n\n\nWhat's not clear to me as well is, what type of Collider I should use (Box Collider, CapsuleCollider...) Or doesn't it makes a difference?\n\nAs I understood, Rigidbody is used for an other \"technique\" to make damage, am I right?", "How can I handle a transition into building interiors? I am trying some stuff on Unreal Engine to make something approching games like Commandos series. \nBut for now, I'm stuck with something I can't figure how it is done : \nHow are building interior handled ?\n\nHere's a screenshot to illustrate what I say : \n\n\n\nWhen you enter a building, everything become black, except the building's interior. The interior is isolated, there is no \"communication\" between the interior and the exterior, and between linked interiors. For exemple if you shoot with a weapon and there is an enemy outside just behind the door, he can't hear you.\n\nSometimes biggest buildings are divided in many parts, and each floor are a different \"section\" that are isolated from each other (you have a transition and can't communicate between). Here is an image that explain it well : Commandos 2 interior\n\nTeleport : I first thinked that you were teleported to a different portion of the map, or a different small map, but it is unlikely. If you look at a window, you are at the same time outside (you can see your character outside at the window) and inside (you character is leaning out the window). Teleport would cause many sync issue.\n\nSection toggle : Then, I thinked that the interior is already handled in the exterior map, but completely hidden, and when you enter it, it \"deactivate\" the exterior by hidding everything outside and displaying interior. Again, this is unlikely since map are full 3D (you can rotate 360°) and exterior are 2D.\n\nHow can I create this kind of transition?\n\nI've specified that I am on Unreal, but I'm more searching the theorical way rather than Unreal specifics.", "Box2D Qt wrong collisions I am working on a simple Box2D game (with Qt), but my objects don't collide correctly: \n\n\n\nAs you can see on the picture, objects try to go through each other and slide over.\n\nMy b2World:\n\nb2Vec2 gravity(0.0f, -9.8f);\nworld = new b2World(gravity);\n\n\nHow I add objects:\n\nb2BodyDef bodyDef;\nif (dynamic) bodyDef.type = b2_dynamicBody;\nbodyDef.position.Set(centerX, centerY);\nbody = world->CreateBody(&bodyDef);\n\nb2PolygonShape box;\nbox.SetAsBox(width/2, height/2);\n\nb2FixtureDef fixtureDef;\nfixtureDef.shape = &box;\nfixtureDef.density = 1;\nfixtureDef.friction = 0.5;\nfixtureDef.restitution = 0.2;\nbody->CreateFixture(&fixtureDef);\n\n\nfor drawing, ppm - pixel per meter, scene - QGraphicsScene, rect - QGraphicsRectItem:\n\nrect = scene->addRect(getRect(centerX*ppm, centerY*ppm, width*ppm, height*ppm));\n\n\nFunction to get QRectF (it takes left and top coordinates, not center):\n\nQRectF GRect::getRect(float32 centerX, float32 centerY, float32 W, float32 H)\n{\n return QRectF(centerX - W/2, centerY - H/2, W, H);\n}\n\n\nAnd how I draw every object:\n\nb2Vec2 position = body->GetPosition();\nrect->setRect(getRect(position.x*_ppm, position.y*_ppm, _width*_ppm, _height*_ppm));\nrect->setRotation(body->GetAngle());\n\n\nI tried to play with density, friction and restitution values, but it has no effect. Help.\nPS. Sory for bad English, I am from Russia", "Finding roots/zeros for collision detection? For the most simple of 2D games, I have implemented a posteriori collision detection (overlapping rectangles) on the x/y Cartesian plane, but am now interested in understanding the basics of a priori collision detection...\n\nIn the link here, I noticed the reference to Newton’s Method. So, I want to better understand the link b/w finding zeros of an equation and detecting a posteriori collision. \n\nLet's start with the most obvious case of finding roots of an equation: If you have a projectile's trajectory modeled as a quadratic function, you can find the roots to predict at what time the height will equal zero (or any other constant height, actually, by just solving f(x)=C to be f(x)-C=0 and then finding roots of that expression). \n\nSo, as I understand, finding the root can tell me the time at which the object will be at any chosen height. More broadly, we basically know the (x,y) location of the object for any given time. But how does root finding, in particular, translate to detecting collisions with another object? (The other object may be stationary, or be moving. If the latter, do you also determine roots/location of this moving object as well? Calculate the (x,y) trajectory of both objects and determine where they will intersect?)\n\nAgain, the basic question is where does root finding come into play? Any links to a basic primer on this topic, with a simple example would also be greatly appreciated.", "Make enemy move diagonally in 2D I'm making the enemy follow the player only straight or diagonally e.g.(1,1)(1,0)(0,1)(-1,1).\nI expected the problem that I have, but I don't really know how to fix it. When my enemy is placed diagonally (relative to the player but not exactly), It will alternate rapidly between going diagonally and straight, causing it to appear like its vibrating.\n\nhere is the simple script returning the Vector2 to follow:\n Vector2 direction = (player.position - goblinTr.position).normalized;\n direction.x = Mathf.Round(direction.x);\n direction.y = Mathf.Round(direction.y);\n\n return direction;", "How to get a smooth path for a vehicle in a 2D top down map? I am making a 2D tile based game which involves having AI that needs to traverse the map avoiding obstacles in a natural and smooth path (NOT NECESSARY THE SHORTEST)\n\nThe orientation of the vehicle is also important in the example above the initial orientation of the vehicle is to NORTH but the orientation of the vehicle at the destination doesn't matter.\n\nAll I could do now is to compute the path using A* or a BFS fill through the center of the tiles.\n\nThis is an example of a desired path:", "Client/Server state synchronization for RTS How can I perform state synchronization using client/server networking in an RTS similar to Starcraft 2 and Planetary Annihilation?\nI'm assuming the server has to do some sort of rewinding time to apply the updates received by each of the clients. But for an RTS game, that sounds like a lot of separate copies of the game world. How do you resolve interactions between units belonging to different players who have different latencies?\nFor the clients, do they need to use their latency (RTT) in order to know how far behind the server they are, to apply future updates that arrive from the server at the right time?\nHow do you keep time in sync when latency could fluctuate and server updates may not arrive at fixed intervals?", "Use libgdx box2d for dynamically generated top down map So, I've already found some information on how to use box2d and tiledmap together.\n\nSince I want to generate my top down map (100 by 100 tiles), I thought about only using box2d.\n\nThe tiles would be fixed and only the player (and maybe some other movable parts like chests, etc) would be dynamic. I'd also like to use box2dlights later, so using box2d seems convenient.\n\nMy only concern on this is the performance. I haven't used box2d much, so I don't know how it handles such a big amount of boxes (though not all 10000 tiles would be visible at the same time).\n\nDoes anyone know how the performance would be influenced or advice on how to achieve this easier?\n\nThanks in advance", "OBB vs Frustrum collision detection Some definitions:\n\n\nAn oriented bounding box (OBB) is a rectangular block which can be represented in many ways, as a collection of eight vertices, a collection of six planes or others, for this particular case let's just consider these 2.\nThe camera frustrum is a convex object formed by 6 planes, resulting from converting the unit cube [(-1,-1,-1),(1,1,1)] to world space.\n\n\nAfter a lot of researching I've seen you can use the SAT theorem to check collision between convex objects so I assume this could be a choice to check whether my objects will intersect with the camera frustrum.\n\nRight now I've got the OBB of my meshes stored as 8 vertices in world space and my camera frustrum stored either as 8 vertices or 6 planes (also in world space). \n\nSo my question, is it SAT suitable to solve this particular problem? If it's so, how would you implement it or where can i find a decently fast implementation of it?", "Accurately simulating the lots of dice rolls without loops? OK so if your game rolls lots of dice you can just call a random number generator in a loop.\nBut for any set of dice being rolled often enough you will get a distribution curve/histogram.\nSo my question is there a nice simple calculation I can run that will give me a number that fits that distribution?\n\nE.g. 2D6 - Score - % Probability\n\n2 - 2.77%\n\n3 - 5.55%\n\n4 - 8.33%\n\n5 - 11.11%\n\n6 - 13.88%\n\n7 - 16.66%\n\n8 - 13.88%\n\n9 - 11.11%\n\n10 - 8.33%\n\n11 - 5.55%\n\n12 - 2.77%\n\nSo knowing the above you could roll a single d100 and work out an accurate 2D6 value.\nBut once we start with 10D6, 50D6, 100D6, 1000D6 this could save a lot of processing time.\nSo there must be a tutorial / method / algorithm that can do this fast?\nIt is probably handy for stock markets, casinos, strategy games, dwarf fortress etc.\nWhat if you could simulate the outcomes of complete strategic battle that would take hours to play with a few calls to this function and some basic maths?", "Circular movement - eliminating speed ups near Y = 0 I have a basic algorithm to rotate an enemy around a 200 unit radius circle with center 0. This is how I'm achieving that:\n\nif (position.Y <= 0 && position.X > -200)\n{\n position.X -= 2;\n position.Y = 0 - (float)Math.Sqrt((200 * 200) - (position.X * position.X));\n}\nelse\n{\n position.X += 2;\n position.Y = (float)Math.Sqrt((200 * 200) - (position.X * position.X));\n}\n\n\nIt does work, and I've ensured that at no point does either X or Y equal NaN. However, when Y approaches 0, it seems to go significantly faster. This surprises me, because the Y values are locked to the X, which is being incremented by a steady amount. What can I do to smooth the speed?", "Is Pushdown Automata better for user input than Hierarchical State Machine? I saw an example of code using HSM for user input, but to me it seems that Pushdown Automata would be a better fit. I'm confused.\n\nIf I'm right, then after Hierarchical State Machine exits a superstate via substate, and comes back, it must start at a default state and cannot return to the substate it left earlier(unless of course, that default state is the substate). And then, if I'm right, Pushdown Automata could replace that need, as it can return to an older state via its stack and discarding of states.\n\nSay I have an actor I control, and it has several states that use user input as transitions. It supports jumping, ducking, standing and walking. When you are standing or walking, you can jump or duck, after which you return to the state you were in, thus standing or walking. If I were to use an HSM to prevent the duplication of code, I could not return to the last state. But if I used a Pushdown Automata, I could put jumping or ducking on top of the stack and discard them after they are done, and that way I could return to the state I was in.\n\nCorrect me if I'm wrong, and suggest me better options for user input than these two, if there is. Also, please don't post options like duplicating the FSM as the amount of states could vary and my question is related exactly to how to prevent that duplication.\n\nThanks,\n\nme.", "Why isnt setting the global_position working? Previously my items were relative to the player by node hierarchy. But for items like bombs this is not ideal so i tried to add the items to the world scene, but when i try to adjust the position of the item to the players position it doesnt work and i see the sword in the top left corner of the screen the worlds origin.\nEntity Script\nfunc use_item(item):\n var newitem = item.instance()\n newitem.own = self\n newitem.global_position = global_position\n\n #not setting the position of the item correctly\n\n newitem.add_to_group(str(newitem.get_name(), self))\n get_node("..").add_child(newitem)\n \n if get_tree().get_nodes_in_group(str(newitem.get_name(),self)).size() > newitem.maxamount:\n newitem.queue_free()\n\nSword Script\nfunc _ready():\n type = own.type\n $anim.connect("animation_finished",self,"destroy")\n $anim.play(str("swing",own.spritedir))\n if own.has_method("state_swing"):\n own.state = "swing"\n \nfunc destroy(animation):\n if own.has_method("state_swing"):\n own.state = "default"\n queue_free()\n\n\nIt seems like it should work but with an engine like godot there could be several reasons why a certain thing is not working.\nhttps://github.com/MonkeyToiletLadder/wendingo\ncould it be that in my animation player i set the sword positions as key frames and thats why its not working?", "Basic Box2D collision detection I don't understand how to listen for collisions in Cocos2D/Box2D. Say I have two dynamic circle bodies. One is very small and the other is relatively large. When the small circle collides w/ the large circle I'd like to do something (play a sound for example). What's the best way to do this?\n\nI'm currently experimenting w/ the TestPoint method. Something like:\n\nif(largeCircleBody->GetFixtureList()->TestPoint(smallCirclePoint)){\n // collision happened...\n // play sound etc\n}", "enemy behavior with boundary to change direction I'm doing space shooter kind of game, the logic is to reflect the enemy if it hits the boundary. With my logic, sometimes enemy behaves like flickering instead of changing the velocity. It's like trapped in the boundary and checking for if loops.\nThis is my code for velocity changing:\n\nif(this->enemyPos.x>14)\n{\n this->enemyVel.x = -this->enemyVel.x;\n}\n\nif(this->enemyPos.x<-14)\n{\n this->enemyVel.x = -this->enemyVel.x;\n}\n\n\nHow can I get around this? Its going out of boundary and don't know where to go and after sometimes its coming into field. I know whats the problem is, I dont know how to get around this problem.", "Hand cards auto arrangement I'm making a card game with libgdx scene2d and what I'm trying to achieve is auto arrange the cards in a way the all fit the screen. This is what it looks now when the hand is full: \n\nI have done that using a horizontalGroup and puting a -1/3 cardWidth space between the cards. I want the cards to spread evenly when some are removed.\nI think I have to change the space between the cards whenever a card is removed or added but I don't know how much.\n\nThis is my code:\n\n CardActor[] cards = new CardActor[14];\n HorizontalGroup hand = new HorizontalGroup();\n int width = Gdx.graphics.getWidth()/10;\n int height = width * 2;\n hand.setBounds(width/2, -height/4, stage.getWidth()-width, height);\n hand.space(width / -3f);\n hand.align(Align.bottom | Align.center);\n for (int i = 0; i < cards.length; i++) {\n cards[i] = new CardActor(new Card(MathUtils.random(3), MathUtils.random(3, 10)));\n hand.addActor(cards[i]);\n }\n stage.addActor(hand);`\n\n\nAnd this is the CardActor:\n\npublic class CardActor extends ImageButton {\n\npublic CardActor(Card card) {\n super(new TextureRegionDrawable(CardTextures\n .getTexture(card.getType(), card.getRank())));\n\n int width = Gdx.graphics.getWidth()/10;\n int height = width*2;\n getImageCell().prefSize(width, height);\n setBounds(getX(), getY(), getWidth(), getHeight());\n addListener(new ChangeListener() {\n @Override\n public void changed(ChangeEvent event, Actor actor) {\n onSelected();\n }\n });\n}", "c++ text rpg loading rooms/mobs So for practice and as a learning exercise i foolishly decided to make a text based rpg on my phone using the c4droid ide. ive done well and have learned a lot.\n\nSo far you can create a new character or load the previous one. and you can walk around in the rooms ive made.\ncurrently the rooms load from a file when you enter it, and then it loads again every time you do anything except leave,which loads the next room instead. ill be tweaking my gameloop so it doesnt reload the room everytime soon.\n\nMy next step is the addition of mobs. and here ive run into a problem i cant find the answer to with google.\nMy plan was/is to make a class for mobs and instantiate it when there was a mob present and load data from a file. But then i was trying to figure out how to code which room to load them in. First answer was to have the room file dictate which mobs, if any to load. great. except that i want the mobs to stay dead, not reapawn everytime the room reloads.\nso now im wondering if i should be loading the rooms from file all at the same time before the game loop. Potentially too memory intensive down the line when the game has more rooms and mobs? and what to load them to? i havent used arrays in c++ yet, though i have used map which seems similar. Im not even sure what a vector is. i expect ill be needing to read up on those very soon.\n\nso the basic question is this: leave loading the rooms the eay it is, load them all at the beginning of the game, or something else?\n\nall help is appreciated", "Isometric tilemap circle around object I am developing an isometric game like Anno 1602.\nI have an isometric tilemap. The default tilesize is 64x31.\nMy goal is to show the area a building has influence to. For that I want to show a circle in isometric style around that building. Look at the picture below:\n\nI need to find an algorithm which turns information about a building (width, height, radius in tiles) into a polygon containing screen coordinates of the outer parts of the dark area (see picture, I want the red points). For example, the data for the picture above would be:\nw = 2;\nh = 2;\nr = 3\nI tried creating circles with midpoint algorithm for each tile of the building. Merging all points together and running concave hull algorithm to get the outer most points. But this did not yield nice results.\nWhat could be an approach to get points to create a polygon which resembles an isometric area around an object.", "Algorithm to modify a color to make it less similar than background I'm creating a demo of 20 balls bouncing each other, with a background filled with a solid color. Color for each ball is chosen randomly with randint(0, 255) for each R, G, B tuple component.\n\nProblem is some balls end up with a color that is very similar to background, making them hard to see. I would like to avoid that, either by rolling another color if the chosen one is too similar (within a given threshold), or by moving it away from the background color.\n\nHow to calculate a similarity index to use as a threshold? Or how to transform a color to make it, say, less blue-ish?\n\nObvious disclaimer: I know nothing about color theory, so I don't know if the above concepts even exists!\n\nI'm coding in python, but I'm looking for concepts and strategies, so pseudo-code is fine (or just the theory).\n\nEDIT:\n\nTo clarify a few points:\n\n\nEach ball have its own random color. I'd like them to remain as random as possible, and to explore as much as possible of the color space (be it RGB or HSV, pygame accepts both formats for defining color)\nI'd just like to avoid each color of being \"too close\" to background. Problem is not just about hue: I'm perfectly OK with a light-blue ball against a dark-blue background (or a \"full-blue\" against a \"white-ish\" blue, etc)\nFor now, I don't care if a ball ends up with a color similar (or even identical) to another ball. Avoiding that is a bonus, but it's a minor issue.\nBackground color is a constant, single RGB color. For now I'm using \"basic\" blue (0, 0, 255), but I'm not settled with that. So consider the background to be of an arbitrary color (with arbitrary hue, brightness, saturation, etc).\n\n\nEDIT2:\n\nTL,DR version: Just give a way to create X random colors so that none \"fades in too much\" against a background of arbitrary (but single and constant) color", "'Destroyed Actors' and 'Save Games' Background\n\nOur team is creating an adventure platformer, and I have been tasked with creating a Save Game system.\n\nOur game features the usual progression systems, and is relatively linear.\n\n\n\nApproach\n\nI have began my approach by using the EMS Easy Multi-Save plugin for Unreal.\n\n\n\nProblem\n\nWe have a 'Switch' system:\n\n\nPlayer takes cube to switch.\ncube gets used by switch\nswitch can now be activated.\n\n\nIn stage 2, where the cube is used by the switch - the actor for the cube is destroyed in Unreal, and the switch's model is changed to one with a switch.\n\nThe EMS plugin does not provide plug-and-play functionality for keeping track of destroyed actors, which means I must do this myself.\n\n\n\nExample problem scenario\n\n\nPlayer approaches area with switch and cube.\nPlayer saves game (cube present and switch deactivated)\nPlayer picks up cube and takes to switch (cube destroyed and switch activated)\nPlayer loads prior save game\nScene reloads with switch in the correct state, however the cube is no longer present (it has been destroyed by Unreal and is no longer tracked by EMS)\n\n\n\n\nProblem solving approach\n\nReading around, I have been given the idea of creating my own class that keeps track of destroyed actors when they are destroyed.\n\nThis class can be saved by EMS, and then can reload these destroyed actors if needed when a game is loaded. \n\n\n\nQuestion\n\nThere is a lack of real advice for the task at hand here, so I wanted to come here and ask for people's advice and opinions on the best approach to making Destroyed Actors within Unreal compatible with Save Games.", "Avoiding memory allocation in Android game development For obvious reasons, allocating memory on the fly in Android game development is not recommended. For example:\n\nhttp://developer.android.com/training/articles/perf-tips.html:\n\n\n There are two basic rules for writing efficient code: \n \n \n Don't do work that you don't need to do. \n Don't allocate memory if you can avoid it.\n \n\n\nI'm following this advice and am avoiding any memory allocation whilst the game is in progress; however, it's limiting my approach to certain tasks. Whilst I could change my code to see what happens, there's a fair amount of it, and it's not going to tell me about the resulting performance on anything other than the limited range of hardware I have available to test it on.\n\nI was wondering if there are any general rules of thumb which can provide an insight into this problem, such as how much allocation/deallocation you can get away with; whether it's the individual size of the allocation or the overall amount that's most important; things you can do to mitigate against the problem (I'm assuming the problem is chiefly having the garbage collector kick in and damage performance, and/or insufficient memory being available if it doesn't fire frequently enough); does it affect some versions of Android more than others, etc.", "What's the recommended way of doing a HUD for an android game? Basically the question is in the title. \n\nI'm creating a RTS game and I will need buttons like attack move / attack ground, etc. I am not using any engine.\n\nWhen people do games in OpenGL for android (my case), do they ever use android components to control the game or do they create their components in the game? What are the general recommended approach, if there's any? \nHow about more complex components like scrolling lists of items , etc?\nI would also appreciate you to pair your answer with a brief comment about how was your experience using the approach(es) you describe.\n\nThanks :)", "Efficient way to store “item” objects in a simple game I am developing a simple text-based game from scratch in Java. In this game, the user is able to collect items and store them in an inventory.\nMy question is: how should I organize the internal structure of my game so that I can load these items in an efficient way?\nI need to be able to create fresh instances of an item whenever the user acquires an item of that type, or when instantiating any feature in the game that contains items. In order to do so, I feel like I need some sort of "master list" of all items that I can just copy out of by indexing into the correct location in the list.\nI've come up with two potential solutions:\n\nHard-code this entire giant list into a data structure within my game\n\nSomehow load these items from an XML file at startup and then populate the "master list" of items on the fly\n\n\nPros of option 1:\n\nRelatively easy\nNo IO time\nAllows me maximum efficiency in designing the actual item objects\n\nCons of option 1:\n\nHard to maintain\nBloats source code\nVery tedious to implement\n\nPros of option 2:\n\nEasy to add/remove/modify items\nAllows the user to customize the game if they want to\n\nCons of option 2:\n\nRequires that I design my objects much more carefully so that they can be built on the fly and stored\n\nRequires that I perform a deep copy from the master list each time I need a new copy of a specific item\n\nI have to write an "item-builder" that is capable of translating the XML input into an actual item object in memory.\n\n\nNeither of these ideas feels very good to me. Is there something obvious I've missed?", "Stop rotating when select the game object by mouse input I am new to Unity and I am confused about how to solve this problem. Initially, I want to make a platform rotate to its center vector up like this. \n\ntransform.Rotate (Vector3.up, speed * Time.deltaTime);\n\n\nThen, I want to stop it from rotating when the mouse select it, like:\n\nRay ray = Camera.main.ScreenPointToRay (Input.mousePosition);\nRaycastHit hit;\nif(Physics.Raycast (ray, out hit)){\n //find a way to stop rotate\n}\n\n\nI cannot figure out how to stop it from rotating. Can anyone help me, please?", "Should all primitives be GL_TRIANGLES in order to create large, unified batches? Optimizing modern OpenGL relies on aggressive batching, which is done by calls like glMultiDrawElementsIndirect. Although glMultiDrawElementsIndirect can render a large number of different meshes, it makes the assumption that all these meshes are made of the same primitives (eg. GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_POINTS).\n\nIn order to most efficiently batch rendering, is it wise to force everything to be GL_TRIANGLES (while ignoring possible optimizations with GL_TRIANGLE_STRIP or GL_TRIANGLE_FAN) in order to make it possible to group more meshes together?\n\nThis though comes from reading the Approaching Zero Driver Overhead slides, which suggests to draw everything (or, presumably, as much as possible) in a single glMultiDrawElementsIndirect call.", "suggestion for a “strategy game” like platform to test AI algorithm I wrote a piece of tricky AI algorithms that simulates animals living in an environment and their food seeking, interacting with each other and especially learning new patterns of lifestyle.\n\nnow I want to add some graphics to it. so instead of a form with colored dots I would see a 3d environment with different objects moving on it, just like an strategy game.\n\nmy code is in VB.net and it uses lots of advanced oop techniques and dynamic nested classes. so changing code to another platform like python, c++ or java is not and option for me. also I am not a trained graphic programmer so which graphic platform I get is what I use as graphic output. If I could only have source of a simple strategy game it would be enough for me.\n\nalso any link to opensource .Net strategy games or any source code that can hemlp me in this concept is appreciated.", "Get points on a line between two points I'm making a simple space game in JavaScript, but now I've hit a wall regarding vectors.\n\nThe game view is top-down on a 2d grid. When the user clicks on the grid, the space ship will fly to that spot.\n\nSo, if I have two sets of points:\n\n{ x : 100.2, y : 100.6 }; // the ship\n{ x : 20.5, y : 55.95 }; // the clicked coordinates\n\n\nIf the game loop ticks at 60 iterations per second, and the desired ship velocity is 0.05 points per tick (3 points per second), how do I calculate the new set of coordinates for the ship for each tick of the game loop?\n\np.s. I do not want to account for inertia, or multiple vectors affecting the ship, I just want the ship to stop whatever it is doing (i.e. flying one way) and move to the clicked coordinates at a static speed." ]
17
"How to render 2D particles as fluid? Suppose you have a nice way to move your 2D particles in order(...TRUNCATED)
["Subdividing a polygon into boxes of varying size I would like to be pointed to information / resou(...TRUNCATED)
["Distort a quad with a World Matrix Is it possible to distort a quad multiplying its vertices by a (...TRUNCATED)
30
"Best visual way to build a \"near isometric\" 2D view I'm working hard in a 2D platform game, as fa(...TRUNCATED)
["How do I calculate the z-coordinate for a perspective-camera in 2D? I'm new to LibGDX and trying t(...TRUNCATED)
["How can I implement caching into my Rectangular Symmetry Reduction pathfinding algorithm? I have a(...TRUNCATED)
17
"Loading maps on HTML5 Games I was wondering if my 2D Pixel Art platformer HTML5 game(a lot of words(...TRUNCATED)
["How do I make a 2D race car turn smoothly? I'm making a competitive 2-player 2D racing game for a (...TRUNCATED)
["Collision Scenario, Detection and Response I have AABB, BSphere, a Polygon Soup, a Triangle, a Pla(...TRUNCATED)
6
"Moving turret aiming at moving target I've found this post Turret Aiming Formula on Reddit and a ni(...TRUNCATED)
["No collision detected with 2D rigidbody No collision detected with 2D rigidbody\n0\nI have a Zombi(...TRUNCATED)
["How should I use Monte Carlo method to simulate some police cars that keep patroling in a tile bas(...TRUNCATED)
1
"In PhaserJS, how do I get a clicked Physics.P2 body's data? I have a sprite with Phaser.Physics.P2 (...TRUNCATED)
["render text inside countries I have a map of the world and I want to place text on top of each cou(...TRUNCATED)
["How do you calculate a sprite's localScale to resize the sprite to a defined height? I'd like to u(...TRUNCATED)
13
"Development platform for 2D web and mobile games Is there a game development platform -- similar to(...TRUNCATED)
["Good Book or Resource for 2D Game Art I have a very clear idea for my first Game . I have immense (...TRUNCATED)
["Getting Bodies to go \"Super Fast\" in Box2D I am making a breakout game in Android using the LibG(...TRUNCATED)
23
"Best approach to 2D racing game AI? I have no experience in AI at all, but I would like to know how(...TRUNCATED)
["How to represent a map in a top-down perspective game with low algorithm complexity? This is the f(...TRUNCATED)
["How can I avoid type checking in the physics side of collision handling? I have a class responsibl(...TRUNCATED)
15
"How to implement a 2D map? I am interested in implementing a map for my 2D action platformer. The m(...TRUNCATED)
["2D SAT How to find collision center or point or area? I've just implemented collision detection us(...TRUNCATED)
["Conveying a claustrophobic atmosphere in cavalier oblique projection I need your collaborative kno(...TRUNCATED)
17
"Pathfinding in Isometric Phaser with Tunnels I want to create a 2D isometric game. Currently I'm lo(...TRUNCATED)
["Simulating water droplets on a window How do I simulate water droplets realistically falling, gath(...TRUNCATED)
["XNA 2D Collision Detection without GetData() I'm currently working on a Worms game which involves (...TRUNCATED)
15
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
2