{"_id": 0, "text": "What's the difference between UnityEvent and OnTriggerEnter() I'm new into game development and programming and I have a question that might sound silly or stupid, but I'm having issue understanding the difference between UnityEvent and OnTriggerEnter(). I would like to understand what I can do with UnityEvent that isn't possible with OnTriggerEnter()."} {"_id": 0, "text": "How to import character from Blender to Unity? I am trying to import a character into Unity from Blender. I exported the model (which has actions animations) from Blender as a FBX file and dropped in into my Unity project s Assets folder. The model with all of its components (mesh, armature, animations) appears in the project window however, Unity doesn t immediate associate the animations with the model when I drag an instance of the model into my scene. I have also imported a Blender default model ( Constructor a man with red overalls and a wrench), and have been comparing the settings of my model to the Blender model in order to find discrepancies. 3 observations I have made Blender s model is automatically assigned an Animation window in the Inspector panel (image 1), while mine is assigned an Animator window (image 2). Since the former window is the one where the animations are listed and you assign the default animation, it seems like this one is crucial. How do I import my model such that the Animation window appears in its Inspector window? (I ve tried adding an Animation window myself, but it doesn t recognize the model s animations as the Blender model s Animation window does. In Unity, my model s animations all begin at 1.0 (even though they begin at keyframe 0 in Blender) (image 3). For each animation, I get the message, The clip range is outside the range of the source take. I get this message even when I move the animation forward several keyframes in Blender and re export the file to Unity as a FBX. I compiled several of my actions into an animation that I then exported as a .mov file, and this is the sequence of actions that begins when I press Play in Unity. When I deleted this animation from Blender (as I thought this was the issue), my model now does nothing when I press Play. I am using Blender 2.67 and Unity 4.1.5f1 My actual question How do I import my character into Unity such that it is automatically assigned an Animation window? I have been struggling with this issue for several hours now, and none of the online tutorials or forums seem to address it."} {"_id": 0, "text": "Help understanding camera scene Unity I'm a brand new unity developer and I watched a few tutorials and then found a game on the Asset Store to provide a nice base for my game. However the setup, especially with multiple scenes is quite different than the tutorials I watched and I can't figure out what is happening. Here is my Scene view from the main menu When I click on Main Camera the tiny little thing with the green outline in the corner is highlighted. Now if I click play, that whole menu fits in the screen, even though the Main Camera is apparently tiny? Then, while playing, I click back to scene view I see this It shows the camera as being empty, even though in Game View I can see interact with the menu. When I swap to my Scene 1, which is the game view, it is the exact opposite. This is what I see in Scene View while the game is playing Note the game running in the preview in the corner. Those tiny circles are the same circles on the main menu, how does the same asset fit in what appears to be two wildly different sizes? So I ask, what is the different between the two scenes. One appears in the preview while one doesn't. One fills in the huge canvas while the other apparently fits in the tiny camera. What am I missing?"} {"_id": 0, "text": "Fitting Gameobjects within camera view I am trying to fit a grid of gameobject into the orthographic view but I have a problem whenever I change the amount of grids to display it would overlap the view. What c n I do to fit a series of gameobjects, having always the same margin as the amount of grid changes? private void Start() for(int i 0 i lt wordSearch.Gridsize i ) for(int j 0 j lt wordSearch.Gridsize j ) cell Instantiate(gridCell, new Vector3(j 1 gridCell.transform.position.x cellSpacing, i 1 gridCell.transform.position.y cellSpacing, 0), Quaternion.identity) cell.name \"cell Y \" i.ToString() \" cell X \" j.ToString() GameObject textObject cell.transform.GetChild(0).gameObject textObject.GetComponent lt TextMeshPro gt ().text wordSearch.matrix i, j .ToString() textObject.name textObject.GetComponent lt TextMeshPro gt ().text CenterPoint() FitToScreen() private void CenterPoint() Vector3 offset new Vector3(0, 1, 10) cellGameobject GameObject.FindGameObjectsWithTag(\"cell\") transformCell new Transform cellGameobject.Length for(int i 0 i lt cellGameobject.Length i ) transformCell i cellGameobject i .transform for(int a 0 a lt transformCell.Length a ) cellVectors transformCell a .position centercell cellVectors transformCell.Length GetComponent lt Camera gt ().transform.position centercell offset private void FitToScreen() Camera.main.orthographicSize Insert Comment"} {"_id": 0, "text": "Getting position of a coordinate on the surface of a sphere So I want to create a object B close to another object A, but I'm trying to avoid that A covers B I have thinking how to achieve that. Take a look of the following drawing I have been thinking in a solution in a math geometry way before searching for some Unity3D function to solve the problem. I have realise A and B would be on the same surface if the camera is within a sphere with radius c A. So I guess the solution can be related to get a point at a B at a distance A B from A on the surface of the sphere with radius c A. Does it has sense? Any other idea? How to do it with maths and Unity?"} {"_id": 0, "text": "Unity redraw only part of the GUI I am making an RTS game which currently has a very heavy GUI and takes up sometimes 50 of the CPU time per frame. Most of the data on the GUI remains constant, (selected units and their avalible actions) but some needs to be updated frequently (health bars, progress bars). Is it possible to draw the GUI once on an event and then keep that on screen and only redraw parts of the GUI?"} {"_id": 0, "text": "GTA style camera Unity I am wanting to make a 3d RPG with unity, and I'm in the planning phase. For the camera I decided to make it GTA style. I want the camera to be rotated around the player without effecting the movement of the player. If anyone can give any pointers on this, I would be very grateful."} {"_id": 0, "text": "How to synchronize the speed of spawned object and spawning time interval? I want a stream of enemies coming from the top of the screen one behind other in a line, with their speed (speed of the whole stream i.e. every enemy) increased over time. When I simply increased their speed, a continuous stream of balls (which will be my enemies) is lost since objects are spawned at a fixed time interval irrespective of the varying speeds of the spawned balls. To maintain the continuous flow of balls what I wanted is to generate balls rapidly as the speed increases. So there should be a direct relationship between spawning interval and speed of the stream. How can I do that?"} {"_id": 0, "text": "Issue implementing wall jump in Unity I'm having troubles implementing a satisfying wall jump in Unity. I managed to detect collision with a wall, but when I press the jump button, the result is alway weird or very weak. I think this have to do with the 2D physic in Unity, but I have no idead how to handle it correctly. Here's my code with the concerned parts public void Move(float move, bool crouch, bool jump) If the input is moving the player right and the player is facing left... if (move gt 0 amp amp !facingRight) ... flip the player. Flip() Otherwise if the input is moving the player left and the player is facing right... else if (move lt 0 amp amp facingRight) ... flip the player. Flip() if (jump) if (!grounded amp amp walled) StartCoroutine(WallJumpRoutine()) void Flip() Switch the way the player is labelled as facing. facingRight !facingRight Multiply the player's x local scale by 1. Vector3 theScale transform.localScale theScale.x 1 transform.localScale theScale IEnumerator WallJumpRoutine() Vector2 wallJumpVector new Vector2(jumpForce 10, 20f) GetComponent lt Rigidbody2D gt ().AddForce(wallJumpVector, ForceMode2D.Impulse) yield return null To be more precise, the result I'm getting is either my player being moved a tiny bit (despite using the same force as my regular jump, which is working fine) or my player being moved a good distance but at very high speed (this is when I'm using ForceMode2D.Impulse). Any help?"} {"_id": 0, "text": "Quest UI Display in Unity 2D I have this quest manager script where I store all my quests for easy duplication. I'm adding a feature that gives the player the option to see his her current to do quest. The first thing I tried was just showing it in my dialogue box(which closes immediately because it's supposed to be for dialogues only). Now I made a quest log UI so he she can see his her current to do list with a claim button for the reward. All I need to do now is to change the text I have in the quest log UI (the Quest Title and the Description) the same way I was doing with the dialogue for each quests, but I can't seem to figure out how. public QuestObject quests public bool questCompleted public DialogueManager theDM public PanelManager thePM public string itemCollected Use this for initialization void Start () questCompleted new bool quests.Length Update is called once per frame void Update () public void ShowQuestText(string questText) theDM.dialogLines new string 1 theDM.dialogLines 0 questText theDM.currentLine 0 theDM.ShowDialogue() public void ShowQuestList() thePM.ShowDialogue() public class QuestObject MonoBehaviour public int questNumber public QuestManager theQM public DialogueManager donMariano public string startText public string endText public string questTitle public string questDescription public int rewardGold public int rewardChilli public int rewardEggplant public int rewardPotato public bool isItemQuest public string targetItem Use this for initialization void Start () Update is called once per frame void Update () if(isItemQuest) if(theQM.itemCollected targetItem) theQM.itemCollected null EndQuest() public void StartQuest() theQM.ShowQuestText(startText) public void EndQuest() theQM.ShowQuestText(endText) theQM.questCompleted questNumber true gameObject.SetActive(false) public class DialogueManager MonoBehaviour public GameObject dBox public Text dText public bool dialogActive public string dialogLines public int currentLine public Image dialogImage private PlayerControl thePlayer Use this for initialization void Start () thePlayer FindObjectOfType lt PlayerControl gt () Update is called once per frame void Update () if(dialogActive amp amp Input.GetKeyDown(KeyCode.Space)) currentLine if(currentLine gt dialogLines.Length) dBox.SetActive(false) dialogActive false currentLine 0 thePlayer.canMove true dText.text dialogLines currentLine public void ShowBox(string dialogue) dialogActive true dBox.SetActive(true) dText.text dialogue public void ShowDialogue() dialogActive true dBox.SetActive(true) thePlayer.canMove false"} {"_id": 0, "text": "Combined Mesh and Lightmap I am using Unity 2017. The left picture is the original state. Light map applied. On the right is the state after all meshes are made into Combined Mesh. Same lightmap settings as left. As you can see, it is filled with dirty black dots. What should I do?"} {"_id": 0, "text": "How can I render from a buffer that exists and was created on on the GPU? I'm looking for a unity API or function call to allow me to do the following ... I wrote some really complex functions that are compute shaders. These compute shaders manage a huge compute buffer containing voxel information. I then take portions of (or the entire) voxel buffer in another compute shader and produce a vertex buffer. All of this is done on the GPU with only compute shader calls from the CPU. Now I want to render that vertex buffer but I must be looking in the wrong place because I can't find any information on how this is done within unity despite there being other examples on how to do this using raw DX or openGL approaches. Can anyone point me in the right direction to determine how I can render using a specified shader a buffer already in graphics RAM (and ideally give it some textures too)?"} {"_id": 0, "text": "Unity assets turned binary from text I'm working with unity and git, and for some reason, from some point the assets started being Binary files, meaning that they're not visible as normal YAML files, and I cannot see textual git diff results on them. Has anyone experiences it and knows how to revert to the textual format from the binary format?"} {"_id": 0, "text": "Check Supported Platforms for Editor How can I find out from script(c ) did I download specific platfrom support for current Unity version?"} {"_id": 0, "text": "is GameObject.Find() a bad idea even for one frame? as I searched GameObject.Find and GameObject.FindwithTag are heavy to work with and for reall projects its better to find repalcements. for a NPC that get instantiated in game it first needs to find player character. for this issue I only can use GameObject.find() . for a scene with lots of objects maybe its heavy for even one frame if there is lots of objects in the scene. is there any way to set the researching object in head of hierarchi and the NPC to only get that?"} {"_id": 0, "text": "How do I pause and unpause gameobjects on is own in the scene without pressing keys in unity3d I can't get my gameobject to pause or unpause in the scene in Unity3d. I need the game to pause for a couple of seconds maybe longer than unpause by itself. Here is my script using UnityEngine using System.Collections public class hu MonoBehaviour GameObject pauseObjects public bool isPaused void Start () pauseObjects GameObject.FindGameObjectsWithTag(\"Player\") Update is called once per frame void Pause () if(Time.timeScale 1) Time.timeScale 7f else if (Time.timeScale 8f) Time.timeScale 1"} {"_id": 0, "text": "Camera Movement Smoothing I am trying to smooth a camera I create in my game, but I can't seem to find a way to actually do this correctly. What I have Calculate the \"current\" Forward vector var cameraForward Vector3.Cross( Self.forward, target.up) .normalized.Cross(target.up).normalized Rotate the camera on the Y axis of the current target, and X Axis based on delta.y and CurrentVerticalLook cameraForward Quaternion.AngleAxis(delta.y, ViewTarget.transform.up) Quaternion.AngleAxis(CurrentVerticalLook, Self.right) cameraForward var offset cameraForward CameraDistance var pos LookAt offset Self.Position pos Self.transform.LookAt(ViewTarget.position) So what I ahve tried I tried Lerping the Vector Position, I tried smoothing the delta.y based on the last N frames. The Camera I need is something like this Rotate on the Around UP Axis of the target and Rotate on Right Axis of the Camera, Camera Up is always to Target UP. So this is sort of Orbital Camera, but I am having trouble finding the correct rotation operations. The way its set right works, but the camera movement is jaggy, but I can't seem to find a way to add Slerp in there without messing everything. Thanks! Edit lt"} {"_id": 0, "text": "Retrieve the original prefab from a game object How would one proceed to retrieve the original prefab used for instantiating an object? In the editor these two functions work Debug.Log(PrefabUtility.GetPrefabParent(gameObject)) Debug.Log(PrefabUtility.GetPrefabObject(gameObject)) But I need something that works in the release version. I have objects that can be transported between scenes ands I need to save their data and original prefab to be able to instantiate them outside of the scene they have been originally instantiated. ie Game designers create new prefabs. Game designers create objects from prefabs and place them in scenes (50 to 150 scenes). Game is played and objects are moved across scenes. Game is saved and infos about objects which have moved are saved in the save streams (files or network). This is where I got stuck. Currently, to palliate to the shortcomings, we're saving the name of the prefab in the prefab. But each time a prefab is moved, renamed or duplicated the string must be changed too, sometimes the objects created from the prefab keep the original name (game designer might have edited the prefabPath field). Maybe there is a better way to achieve proper save games without having to access to the original prefab name. But currently we keep the saves segmented on a per level basis (easier and safer to save load to files and transfer the save games to from servers)"} {"_id": 0, "text": "How do I prevent dynamic GUI elements from overlapping in Unity? I'm working on a birds eye view for our Unity3D game world, where each point of interest has a label hovering above it. The problem is that sometimes they overlap, although there is more than enough space on the screen for them to co exist. Can anybody think of a better way to separate them than checking every texture with every other texture and moving them away from each other?"} {"_id": 0, "text": "Recursively find neighbors I'm making a Bubble Shooter game in Unity. I came to the point where I can hit another bubble and it destroys all of its neighbors. Now I'm trying to use recursion to destroy all of its neighbors neighbors and it causes a stack overflow. private List lt Bubble gt FindAllRecursiveNeighbors(Vector2Int originPosition) List lt Bubble gt allNeighbors FindNeighbors(originPosition) List lt Bubble gt result new List lt Bubble gt () foreach (Bubble bubble in allNeighbors) if (result.Contains(bubble)) continue result.Add(bubble) Recursion starts here. foreach (Bubble bubble in result) List lt Bubble gt neighbors FindAllRecursiveNeighbors(FindPositionOfBubble(bubble)) foreach (Bubble neighbor in neighbors) if (result.Contains(neighbor)) continue result.Add(neighbor) return result"} {"_id": 0, "text": "Adding text to gameobject I'm trying to create a falling word game like z type (code here). I have created 3 game objects and I want the words to be added as text to these game objects something like a health bar is added to enemies etc. This is the word spawner script that spawns the word on screen. public GameObject wordPrefab public Transform wordCanvas public WordDisplay SpawnWord() Vector3 randomPosition new Vector3(Random.Range( 2.0f, 2.0f), 7.0f, 0) GameObject wordObj Instantiate(wordPrefab,randomPosition, Quaternion.identity, wordCanvas) WordDisplay wordDisplay wordObj.GetComponent lt WordDisplay gt () return wordDisplay Right now the words are spawned at a random x position and y position of 7.0. Instead of this how can I assign the words to the gameobjects that I have created. Edit I have created a spawner that spawns 3 enemies at the top of the screen and they start falling down to the bottom. Here is the script attached to the enemy game objects public float fallSpeed 1.0f public GameObject wordPrefab private Transform parent public WordDisplay SpawnWord() Vector3 randomPosition new Vector3(Random.Range( 2.0f, 2.0f), 7.0f, 0) GameObject wordObj Instantiate(wordPrefab, randomPosition, Quaternion.identity, parent) WordDisplay wordDisplay wordObj.GetComponent lt WordDisplay gt () return wordDisplay Update is called once per frame void Update () transform.Translate(0, fallSpeed Time.deltaTime, 0) I have also removed the SpawnWord() method from the wordspawner script. However the words don't spawn along with the enemy gameobjects. There is one more script called the WordTimer. Not sure where to add this code. This is from the original code that's on github. public WordManager wordManager public float delay 1.5f private float nextWord 0f void Update() if (Time.time gt nextWord) wordManager.AddWord() nextWord Time.time delay delay 0.95f"} {"_id": 0, "text": "Load scenes inactive When I call SceneManager.LoadScene() it will set the loaded scene as active. Can I load scenes at the game startup and just call SceneManager.SetActiveScene() during gameplay? If so, is there a way to iterate through all the scenes in the Build Settings and load them? Mine don't have a build index assigned to them until I have called LoadScene()."} {"_id": 0, "text": "Unity Mesh importing as child of armature I'm following along with this tutorial by Sebastian Lague https www.youtube.com watch?v yhPRkihs Yg amp list PLFt AvWsXl0f4c56CbvYi038zmCmoZ4CQ amp index 14 However, when I import my character from Blender into Unity, the sword and shield mesh are children of the armature instead of siblings like the shirt pants shoes etc. I'm fairly certain this is because the sword and shield are parented directly to bones on the hands, I'm just not sure why they import as children of the mesh unlike in the video."} {"_id": 0, "text": "Canvas not scaling to screen size So I have a very simple scene set up with just a camera, a game object called TestGrid with a grid script, and then a canvas. I have a TextMeshPro prefab that I instantiate to fill the 10 x 20 grid with cells. If I build and run the game, I see all the cells on my screen. However, in the editor play view, I can only see as many grid cell as would fit on startup. Making the game view smaller or larger will scale the ones already there, but everything that didn't fit initially is quot clipped quot out. The quot canvas quot is in the bottom left corner of the quot grid quot I'll share my code as well using System using System.Collections using System.Collections.Generic using TMPro using UnityEngine using UnityEngine.Diagnostics public class TestGrid MonoBehaviour private float cellSize 50.0f SerializeField private float width 0.0f SerializeField private float height 0.0f SerializeField private TextMeshProUGUI labelPrefab Start is called before the first frame update private void Start() if (labelPrefab null) Debug.LogError( quot You must set a label prefab. quot ) return GameObject canvas GameObject.Find( quot labelCanvas quot ) if (canvas null) Debug.Log( quot Unable to find canvas quot ) return This is just a 2D array of ints. Grid grid new Grid((int) width, (int) height) var canvasRect canvas.GetComponent lt RectTransform gt ().rect cellSize Math.Min((canvasRect.width width), (canvasRect.height height)) for (int x 0 x lt grid.Data.GetLength(0) x) for (int y 0 y lt grid.Data.GetLength(1) y) SpawnLabel(new Vector3(x, y, 0), canvas, grid.Data x, y .ToString()) TODO Replace this with LineRenderer Debug.DrawLine(GetWorldPosition(new Vector3(x, y)), GetWorldPosition(new Vector3(x, y 1)), Color.white, 100f) Debug.DrawLine(GetWorldPosition(new Vector3(x, y)), GetWorldPosition(new Vector3(x 1, y)), Color.white, 100f) Debug.DrawLine(GetWorldPosition(new Vector3(0f, height)), GetWorldPosition(new Vector3( width, height)), Color.white, 100f) Debug.DrawLine(GetWorldPosition(new Vector3( width, 0f)), GetWorldPosition(new Vector3( width, height)), Color.white, 100f) void Update() NYI private void SpawnLabel(Vector3 localPos, GameObject canvas, string text) float x localPos.x float y localPos.y var world GetWorldPosition(new Vector3(x, y, 0)) new Vector3( cellSize, cellSize) .5f var label Instantiate(labelPrefab, world, Quaternion.identity, canvas.transform) label.text text label.fontSize 100 label.autoSizeTextContainer true private Vector3 GetWorldPosition(Vector3 local) return local cellSize Additional images of environment I'm actually not too sure what is going on here, so here is everything I know I'm parenting my TextMeshPro prefab transform to the canvas transform, so that it scales properly My Canvas Scalar is set to reference resolution of 2560 x 1440, with a RPPU of 108 Canvas Scalar is also set to Scale With Screen Size Canvas Screen Space is set to Overlay I've also read the following links with no luck https stackoverflow.com questions 32347009 unity canvas does not fill screen https answers.unity.com questions 943190 ui panel not covering whole screen.html https answers.unity.com questions 1331722 ui scaling issues.html Expected Results No matter what the screen size is, I should see my full 10 x 20 grid of quot cells quot (in play view they're just 0's). Question If my canvas is supposed to scale with screen size, why is it that when I choose a cell size calculated from the canvas size, that it thinks the canvas is 2560 x 1440 when the screen size is clearly much smaller than that? Do I need to calculate with a different value? Must I dynamically resize everything I draw within the canvas? What's going on here?"} {"_id": 0, "text": "Batch Combine multiple Graphics.DrawProcedural Calls in Unity I have multiple calls to Graphics.DrawProcedural in my Unity project. E.g. I'm drawing 1000 procedural geometries that share the same material and get their positions meshes from a ComputeBuffer. At some place in my code I'm doing something like this foreach(ProceduralGeometry pG in proceduralGeometries) pG.Draw() Where draw sets the Materials buffer accordingly and calls Graphics.DrawProcedural. Is there anything I can do to batch all these geometries together? Currently I perform over 1000 DrawCalls (seen in the frame inspector) which happen to be very expensive performancewise. Thanks in advance!"} {"_id": 0, "text": "How to prevent weapon clipping WITHOUT camera stacking? This is a FAQ, and answers involve camera stacking. I am not using a SRP. I do not want camera stacking as various post processing instructions (e.g. FXAA, MSAA, etc) are all done on the active camera, and redoing all these instructions on multiple camera would be costly Is there any way to prevent weapon clipping through walls without using camera stacking or a SRP?"} {"_id": 0, "text": "Alternative for using game object prefabs for level generator I just finished the Unity Tutorial for creating a simple 2D roguelike Mobile Game. Now I wanted to make my level bigger finding or creating my own algorithm isn't the problem. My problem is that creating a game object or using a prefab for every single floor or wall tile is a bad idea. (Map 200x200 40000 objects). A comment under the tutorial said that and I'm incline to believe it. That much I can understand, but I can't find a alternative. What can I use besides object prefabs? Sidenote I have decent programming skills, but am beginner with Unity. The tutorial I followed https www.youtube.com playlist?list PLX2vGYjWbI0SKsNH5Rkpxvxr1dPE0Lw8F I want to make the maps there bigger, but then everything goes slow motion."} {"_id": 0, "text": "How to make user move in virtual reality with Google Cardboard and Unity? I am working on a virtual walkthrough using Google Cardboard in Unity 5.3.5. I have a building, and I need to move around inside the room using google cardboard. How can I do that? Is it possible to move around when we walk holding the Google Cardboard? I have done movement using arrow key. I am able to turn around the building with Google Cardboard."} {"_id": 0, "text": "How can I simulate a \"Hot Swap\" betwen Audio Clips? I have a Unity project with 3 separate looping Audio Clips and a single Audio Source. Based on certain events, I swap between which of them are playing. This works fine, but whenever I swap between Audio Clips, the AudioSource stops playing, and must be restarted... which means it starts over from the beginning. As the Audio Clips are the same length, how should I handle the logic to pickup where the previous Clip last left off? Neither Unity's AudioClip nor AudioSource classes seem to have either a \"PlayFromTime()\" or \"GetPercentPlayed()\" method that would facilitate using a single Audio Source. What's the expected way to handle such a scenario? Simultaneously \"play\" from 3 AudioSources at once, muting 2 of them and leaving the last the only one that is actually heard?"} {"_id": 0, "text": "Use an object's x position to seek within an animation I have an animation clip I want to play, using the object's x position to control which frame of the animation is displayed. ie. When the object is at x 2, the animation should show its initial frame. As the object moves rightward (increasing x) the animation should play forward. When the object is at x 6, the animation should show its final frame. As the object moves leftward (decreasing x) between these values, the animation should play in reverse. I thinks this is a form of clamping where I want to map x values into key frames of the animation. Below just a simple code to run animation void Update () if (isPositionChanging) if(transform.position.x gt xPos) if(incrementOrDecrement lt 12) incrementOrDecrement AnimationPlayOnPositionValue(1, incrementOrDecrement) else if (incrementOrDecrement gt 0) incrementOrDecrement AnimationPlayOnPositionValue(1, incrementOrDecrement) void AnimationPlayOnPositionValue(float speed,float timeToUpdate) animatedObject \"MachineAnimationComplete\" .speed speed animatedObject \"MachineAnimationComplete\" .time timeToUpdate animatedObject.Play()"} {"_id": 0, "text": "Bold black bar on right side of game in Unity (Android) I am trying to create an endless runner. I have already created a system to generate infinite backgrounds from an array of some. However, on running the game, I get huge black bar on the right side of the screen, both on PC and on Android phone. Here are the screenshots One more thing, on Android, it doesn't even display the left side of the game, i.e, where the character is. It looks like the things are displaced towards left. Also, the game is a scrolling on and everything is scrolling but behind that bar. It just doesn't go. I hope I can get some help. Ask me if you need any piece of code. EDIT \"CameraFollow\" script using UnityEngine using System.Collections public class CameraFollow MonoBehaviour public GameObject targetObject private float distanceToTarget Use this for initialization void Start () distanceToTarget transform.position.x targetObject.transform.position.x Update is called once per frame void Update () float targetObjectX targetObject.transform.position.x Vector3 newCameraPosition transform.position newCameraPosition.x targetObjectX distanceToTarget transform.position newCameraPosition My \"GeneratorScript\" using UnityEngine using System.Collections using System.Collections.Generic public class GeneratorScript MonoBehaviour public GameObject availableRooms public List lt GameObject gt currentRooms private float screenWidthInPoints Use this for initialization void Start () float height 0.0f Camera.main.orthographicSize screenWidthInPoints height (Camera.main.targetDisplay) Update is called once per frame void Update () void FixedUpdate() GenerateRoomIfRequred () void AddRoom(float farhtestRoomEndX) int randomRoomIndex Random.Range (0, availableRooms.Length) GameObject room (GameObject)Instantiate (availableRooms randomRoomIndex ) float roomWidth room.transform.FindChild (\"floor\").localScale.x float roomCenter farhtestRoomEndX roomWidth 3.0f room.transform.position new Vector3 (roomCenter, 0, 0) currentRooms.Add (room) void GenerateRoomIfRequred() 1 List lt GameObject gt roomsToRemove new List lt GameObject gt () 2 bool addRooms true 3 float playerX transform.position.x 4 float removeRoomX playerX screenWidthInPoints 5 float addRoomX playerX screenWidthInPoints 6 float farhtestRoomEndX 0 foreach(var room in currentRooms) 7 float roomWidth room.transform.FindChild(\"floor\").localScale.x float roomStartX room.transform.position.x roomWidth 6.0f float roomEndX roomStartX (roomWidth 13.0f) 8 if (roomStartX gt addRoomX) addRooms false 9 if (roomEndX lt removeRoomX) roomsToRemove.Add(room) 10 farhtestRoomEndX Mathf.Max(farhtestRoomEndX, roomEndX) 11 foreach(var room in roomsToRemove) currentRooms.Remove(room) Destroy(room) 12 if (addRooms) AddRoom(farhtestRoomEndX) (I tried playing with the numbers on GeneratorScript, but nothing seemed to help."} {"_id": 0, "text": "Keep the prefab connection with FBX The steps I have gone through Added an FBX in UnityProject. FBX added to scene hierarchy. Made Prefab by dragging the FBX into my assets. Note that now the model became a prefab in my hierarchy. Then I added a script to the prefab and assigned some objects and methods to such script. My problem is that when I import the new FBX in the project my scene object doesn't update as it's linked to the prefab which doesn't see the updated FBX. Is it possible to update my prefab with the latest FBX so I don't have to rebuild the prefab and reassign all scripts every time?"} {"_id": 0, "text": "Rotate 2D Object Towards Mouse Stop After Full Revolution Essentially what i'm trying to recreate is a dial with a min and max setting. The player clicks and drags the mouse around the dial to move its position but I would like for it to stop at a full rotation even if the mouse keeps revolving around the object. The only way I've come up with this is to keep track of the distance covered by the drag. So I use 360f StartingAngle for the distance it is allowed to travel ( I know this doesn't account for negative direction however you want to think about it ). I then calculate a previous angle and next angle and find the difference and then add that to the total. Then I was checking if the total 360f starting angle for slerping my rotation. Problem I'm running into is when it crosses the threshold between 359.9 degrees and 0 degrees of course the difference comes up with a negative number and I'm not sure if I'm going about this the best way cause I can't seem to come up with a way of determining whether they crossed that threshold or they just went back really far. using System.Collections using System.Collections.Generic using UnityEngine public class Dial MonoBehaviour Vector2 direction float speed 20f float startingAngle float angle float angleRotationTotal float previousAngle Quaternion rotation void Update() if (Input.GetMouseButton(0)) direction Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position angle angle lt 0f ? angle 360f angle if (startingAngle 0f) startingAngle angle SetPreviousAngle(startingAngle) SetAngleRotationTotal(angle) SetPreviousAngle(angle) if (angleRotationTotal gt 360f startingAngle) rotation Quaternion.AngleAxis(0f, Vector3.forward) transform.rotation Quaternion.Slerp(transform.rotation, rotation, speed Time.deltaTime) else rotation Quaternion.AngleAxis(Angle, Vector3.forward) transform.rotation Quaternion.Slerp(transform.rotation, Rotation, Speed Time.deltaTime) else angleRotationTotal 0f previousAngle 0f startingAngle 0f private void SetAngleRotationTotal(float currentAngle) if (currentAngle previousAngle gt 0f) angleRotationTotal currentAngle previousAngle private void SetPreviousAngle(float currentAngle) previousAngle currentAngle lt 0f ? currentAngle 360f currentAngle"} {"_id": 0, "text": "Unity Render only select objects but show previously rendered objects I am making an RTS game which is having performance issues. Is it possible to render the ground and units separately so I can only render the ground when the camera moves but keep the result displaying the units over the top? I'm not sure what details to include but The camera is fixed angle and orthographic The profiler says drawing takes up about 50 of CPU when units are moving. All the logic is done by a c script outside of monoDevelopment but called through a gameobject each frame, (takes 2 of cpu in tests). Units are put in place using the \"transform.position\" command each frame. Units and tiles are instantiated and destroyed when the Camera passes them. The game is using rigged .3ds models for the units. The units have disabled rigidbodies. Each tile in the game is a separate sprite. The performance drops with 100 low poly units without animation or 20 higher poly units with animation."} {"_id": 0, "text": "Add navigation obstacles during runtime lags Please watch this short video. http screencast.com t vw2a5FdOOT It shows the problem. It's using the build in Unity navigation and followed the guide to build the demo in the video. Everytime I add a new obstacle than all agends pauses (hiccups) for a short time. I think this is because they have to recalculate a new path. How to make this recalculation in a background thread? I want to make a mace tower defense. Thank you for reading an watching!"} {"_id": 0, "text": "Modifying an array of quaternions I have written the following function to inter change 2 specific elements of an array of quaternions private void ChangeRotations(Quaternion rotationsArray) Quaternion bone1Rot rotationsArray (int)Bone1ID Quaternion bone2Rot rotationsArray (int)Bone2ID Quaternion temp bone1Rot bone1Rot bone2Rot bone2Rot temp But when I use Debug.Log to see if this has taken effect, I realize that the 2 array elements are unchanged. What am I doing wrong here?"} {"_id": 0, "text": "Google Play Services somehow authenticates without internet connection This question is asked in the context of the Google Play Services plugin for Unity. Following the documentation for the Google Play Services plugin for Unity, I called the Social.localuser.Authenticate() function in my game to check if the player is authenticated (ie logged in to google play services). Here is the authentication code that I am currently calling void Awake () PlayGamesPlatform.Activate() Social.localUser.Authenticate((bool success) gt if (success) GetLeaderboardData(\"FirstLoad\") else loadingText.text \"Failed to connect to Google Play Services.\" StartCoroutine(\"WaitAndStart\") authenticated success success returns true even without an active internet connection ) This works fine with an active internet connection. However, if the player has logged in before, and then launch the game without an internet connection, this function somehow returns true. It doesn't make sense (at least not to me) that the player can authenticate without an active internet connection. Does anyone know if this was intended? (Or if I made a mistake of some sort somewhere?) Should it have been indeed intended (and the method is checking against a cache of some sort), is there no method to check if the player has an active connection to google's servers? Something along the lines of PlayGamesPlatform.CheckConnection()?"} {"_id": 0, "text": "Unity generates changes in GitHub on saving scene So, here is my problem. First I have a look at the changes in the repository which I am working with. Initially there are no changes Then I open up Unity, i don't make any changes and just save the scene I then go to GitHub Desktop and suddenly there are a lot of changes appearing which I did not make How can I avoid that? The files which are getting changed are .prefab files."} {"_id": 0, "text": "Import .fbx animation from Maya 2012 to Unity 2018 I have a grass made by PaintEffects tool (1) and \"animated\" by adding turbulence (2) and then baked with Maya 2012. And in Maya everything looks perfect animation works. Problem is, when I'm importing that .fbx animation to Unity 2018, nothing happens. I can't either see this animation in Preview, I can see only the \"model\" itself. I read on the internet that's maybe because I set wrong animation, or rig option in Unity, but I tried every one of them. Is there something I missed, either in Maya, or Unity? Maybe I have too old version of Maya? Also, I was trying to save that animation into separate files, or with extensions like .ma, .mb... Nothing works either."} {"_id": 0, "text": "Unity How to make an array of video clips and play them? I have 26 video files which I have to put in an array and play for different objects. So far I have written this from what I know using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Video public class videomanager MonoBehaviour public VideoClip vids private VideoPlayer vp Use this for initialization void Start () vids new VideoClip 25 vp gameObject.GetComponent lt VideoPlayer gt () Update is called once per frame void Update () I have attached this script on a plane on which I am playing the video. Before that, I had 26 different planes, one for each different video, but I think it would be better if I could play them on a single plane and change the video according to logic. I am not sure how I should load them into my player and play them."} {"_id": 0, "text": "Recommend a way to draw thousands of particles (liquid) per frame in Unity3d I'm writing a plugin for this library for Unity3d. I have it working and now I am looking for an efficient way to draw the particles. My 1st test just uses sprites and runs fine on my laptop but I doubt it will be so good on a mobile device. Is there a cheap way of simply drawing lots of particles to the screen each frame? The library generates an array of all the particle positions which updates in FixedUpdate() so I can just draw everything in that array each frame. I'm thinking maybe somehting in the Graphics namespace would handy here, like maybe Graphics.DrawTexture Also I might consider doing some kind of metaballs like pass over the particles to make them look more liquid like."} {"_id": 0, "text": "Why is Camera turning with different speed than Player with same code in different scripts? (with unity) I want to integrate a running character in my game, so I downloaded an animation via Mixamo. The player is running and if I attach the camera directly to the Player, it's shaking the camera and the game is not playable. Therefor I made a different script for the camera. In there, the camera is always following the player but turns (like the player) via float h PlayerMovement.horizontalSpeed Input.GetAxis( quot Mouse X quot ) transform.Rotate(0, h Time.deltaTime 60, 0) (for the camera) and float h horizontalSpeed Input.GetAxis( quot Mouse X quot ) transform.Rotate(0, h Time.deltaTime 60, 0) for the player. (horizontalSpeed is a constant) But after a few seconds I'm running in a completely different way then I look. Why is that and how can I solve this? I tried different animations nothing worked. Update If there is no rigidbody and no collider attached to it it works fine. But I need them."} {"_id": 0, "text": "Abstraction for player, NPC's, and monsters I am trying to come up with a good abstract term for my players, NPC's and monsters. They can all have stats and inventory. so they all can function in the same way. But some could be humanoids, some are monsters and whatnot. Are there any standard abstract terms that game devs tend to use."} {"_id": 0, "text": "Is it bad practice to store inventory and scores in PlayerPrefs? I'm building a mobile game for a client in Unity. To save time, we started with a template game from the Asset Store that had some of the features that the client wants. The game includes a progression system and shop, so we save the user's scores, progress, in game currency, inventory, etc. We currently have no plans to export the save data. The template game uses PlayerPrefs to store all save data. Is this bad practice? Assuming we don't include a button that calls PlayerPrefs.DeleteAll(), is there any extra risk associated with using PlayerPrefs instead of external files to store the player's data?"} {"_id": 0, "text": "BoxCollider2D fails verification, where CircleCollider2D does not I have a 2D game object with no parent and a 2D box collider set with trigger enables. The dimensions are quite large. When I place the game object in the scene, manually, it works just fine. However, when I instantiate the prefab, it doesn't work in the inspector view, under the collider component a notification appears The collider did not create any collision shapes as they all failed verification. This could be because they were deemed too small or the vertices were too close. Vertices can also become close under rotations or very small scaling. When I switch to scene view, while the game is in play mode, I can not see the collider boundaries. Surprisingly, everything works fine, if I use the circle collider. Does anyone know what the problem could be?"} {"_id": 0, "text": "Difference between putting shaders in \"Always Included Shaders\" vs \"Preloaded Assets\" I am developing an mobile AR application with Unity AR Foundation. After a successful android build, I was told one of the shaders was not found. ShaderNotFoundException GLTF PbrMetallicRoughness not found. Did you forget to add it to the build? I realized I forgot to include one of the shaders that is only loaded at runtime. I searched the internet and was taught to include the shader under Project Settings gt Graphics gt Always Included Shaders. That totally made sense but I was faced with the same problem everybody faced, the building takes ages as it compiles all my shader variants. I stopped the build and opted for a method that was not mentioned by the internet, I went to Project Settings gt Player gt Optimization and included the shader under Preloaded Assets. The build was much faster and the shader was loaded correctly in my application. At this point, my build error is solved but I can't help wondering if it is correct to do so. I am not seeing anyone mentioning about this method and there is not official documentation recommending including shaders under Preloaded Assets. Could anybody help me out by explaining (hopefully) what these 2 methods actually do to my build, and what is considered the best practice to include the shaders? I am using Unity 2020.3"} {"_id": 0, "text": "How do I get the InputManager to recognize a certain axis Vector2D with a Vive motion controller? Right. So basically I want to map the Vive motion controller touchpads (certain locations) to the certain inputs in Unity's InputManager. How do I do this? Like I want a certain area on the touchpad to equate to forwards backwards in the InputManager. How would I do this? I am not seeing a way to do it natively. Long story short I'm wondering if I can use the Vive with the InputManager or not."} {"_id": 0, "text": "Unity Scaling down a GameObject containing a child Final IK (VRIK) rig I'm currently building a VR AR hybrid in Unity, where I'm controlling an IK rig using VR, then sending the VR controllers positions to an iOS device using network transforms to mirror the IK rig's movement in ARKit. I'm having trouble implementing pinch to scale the scene locally on the iOS device. I'm attempting to uniformly scale down a parent GameObject containing the IK rig which has its Head target connected to SteamVR Vive headset and its Hand targets set hand controllers positions. The vectors that describe the positions of the controllers are being sent over the network, so I'm applying the same scale factor to those, so that the targets match up to the scaled down character. However, the IK rig appears to break when scaling the character down, and in particular the legs appear to be too far apart, and the hand movements no longer look correct Could the problem be to do with the internal relative transforms within the IK rig needing to be modified? And is there a better approach?"} {"_id": 0, "text": "Character Movement and Collision with Ragdoll Rigidbodies Colliders? I have a player character that I'm moving with a character controller script and it is moved by applying velocity to a Ridigbody. This works when I have a rigidbody component on the player but my character also has ragdoll colliders and rigidbodies on each body parts (set up with Untiy's ragdoll wizard). What I'd like to do is remove the ridigbody and collider that are on the player and use the ragdoll colliders and rigidbodies instead for physics movement and collision. But it's not working! When I use the rigidbody from the skeleton Root and try to apply velocity the character won't move (animation plays but she keeps running on the same spot). What do I need to do to get this working? Another issue is that if I leave the player rigidbody on but remove the large capsule collider I can move the character but collision doesn't work and she runs through static objects. I already tried with convex set to true on static meshes but it doesn't make a difference. Does somebody know what causes movement and collision not to work with the ragdoll rigidbodies and colliders?"} {"_id": 0, "text": "Unity Editor stops updating ScriptableObjects if I click away from them in editor I'm trying to be better about structuring my code, and I think I'm doing it right. The issue I've got right now is I need to get joystick inputs, scale those values appropriately, and then use that scaled data on any number of MonoBehaviour scripts. I'm trying to split the input conditioning from the end user, and I'd like to do that by using a ScriptableObject to hold the conditioned data. I was thinking that a MonoBehaviour script would run, get the joystick data, scale it, and then push that data to variables in the ScaledJoystickData ScriptableObject. Later, a second MonoBehaviour script would access the variables in the ScaledJoystickData and use those to move the things in the game. I'm understanding the benefits of structuring the code this way, especially in that I can access the ScriptableObject from the editor and manipulate those values I don't actually need to have a joystick connected, and I'm free to test either end of the input handling independently. The problem is that, if I am looking at the ScriptableObject instance in the editor, it stops updating as soon as I click away from it (to the consuming GameObject). If I click back to the ScriptableObejct instance, none of the values update. Nothing on the GameObject's script updates unless I start the game with that GO selected in editor, and again THAT fails to update if I click off and click back. The GameObject script is currently using the values from the ScriptableObject instance and piping them to public variables, and the public variables aren't updating. Is there some bug with ScriptableObjects, or am I doing this wrong? EDIT Here's an example. Make a script called \"ExampleSO\" and replace the contents with using System.Collections using System.Collections.Generic using UnityEngine CreateAssetMenu public class ExampleSO ScriptableObject public float stashedVar 0f Make a script called \"ExampleWriter\" and replace the contents with using System.Collections using System.Collections.Generic using UnityEngine public class ExampleWriter MonoBehaviour public float scaling 2f public float scaledInput 0f public ExampleSO exampleSO null Update is called once per frame void Update() if(exampleSO! null) scaledInput scaling (Input.GetKey(KeyCode.LeftArrow) ? 1f 0f) exampleSO.stashedVar scaledInput Make a script called \"ExampleReader\" and replace the contents with using System.Collections using System.Collections.Generic using UnityEngine public class ExampleReader MonoBehaviour public float display 0f public ExampleSO exampleSO null void Update() if(exampleSO! null) display exampleSO.stashedVar Create an instance of the ExampleSO, add the ExampleWriter to a game object, and put the ExampleSO instance into the ExampleWriter slot. Highlight the game object holding ExampleWriter and run it. Push the left arrow key and see the value toggle 0 2. Click the ExampleSO instance. Nothing is happening there now. Click back on the game object, and now it doesn't update either. If you have the ExampleReader on the same game object then it won't work at all. ExampleReader will read fine, if you have it on a separate GameObject, but again if you click off and click back then it stops responding."} {"_id": 1, "text": "Error drawing two VAO, each one using different shader programs (vertex fragment shader) in OpenGL Core 4.3 GLSL 430 I am trying to draw over a GL TRIANGLE FAN one texture to render video frames, using shaderProgram1, and render above it some points (GL POINTS) using shaderProgram2. By this way (OpenGL Core 4.3) void GLViewer paintGL() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glUseProgram(handleShaderProg1) glUniform...() Set Uniforms for shaderProg1... lt FIXED glBindTexture(GL TEXTURE 2D, textureHandle) Bind texture glBindVertexArray(vaoHandle1) Bind VAO glDrawArrays(GL TRIANGLE FAN, 0, 4) glBindVertexArray(0) Unbind VAO glBindTexture(GL TEXTURE 2D, 0) Unbind texture (used in shaderProg1) glUseProgram(handleShaderProg2) glUniform...() Set Uniforms for shaderProg2... lt FIXED glBindVertexArray(vaoHandle2) Bind VAO glDrawArrays(GL POINTS, 0, 25) glBindVertexArray(0) Unbind VAO But only the points defined in vbo2 are rendered over the black glClearColor. Without using the shaderProgram2, all are rendered, texture and the points above it. Is mandatory to use a FBO and two pass deferred rendering? If not, what could be the problem? SOLVED After an OpenGL debugging, I discovered a newbie bug... In my case, I needed to pass the uniforms to the shader every time the current shader program will be changed to another shader program. I was thinking that the uniform variables will keep alive after another call to glUseProgram. I was wrong..."} {"_id": 1, "text": "Is index drawing faster than non index drawing I need to draw a lot of polygons consisting of 6 vertices's (two triangles). Without any texture coordinates, normals etc., both approaches result in 72 bytes. In the future I would definitely also need texture coordinates and normals, which would make index drawing consume less memory. Not a lot though. So my question is For VAOs with few vertex overlaps, which approach is faster? I don't care about the extra memory consumed by non index drawing, only speed. Edit To make it clear. Non index approach float 18 vertices Triangle 1 1,1,0, 1,0,0, 0,0,0, Triangle 2 1,0,0, 0,1,0, 0,0,0, Index approach float 12 vertices 1,1,0, 1,0,0, 0,0,0, 0,1,0, int 6 indices Triangle 1 0,1,2, Triangle 2 0,3,2"} {"_id": 1, "text": "Is there a gl TexStorage equivalent to glCompressedTexImage I have been using glTexImage functions to create textures and then heard of glTexStorage that is supposed to be better and is introduced in the latest standards. But the problem is that I can't seem to find an equivalent to glCompressedTexImage2D(...) in terms of gl TexStorage. I've only found 2 references on an IRC chat to these supposedly equivalent functions while searching. (here and here) Do these equivalent functions even exist ? And if they don't, why don't they exist ? Thanks for any help"} {"_id": 1, "text": "Optimising the modelview transformation in GLSL for 2D So, the standard way to transform vertices and then pass to the fragment shader in GLSL is something like this uniform mat4 u modelview attribute vec4 a position void main() gl Position u modelview a position However, I am working in 2D so there is redundancy in the 4x4 matrix. Would it be more efficient for me to do this? uniform mat3 u modelview attribute vec3 a position void main() gl Position vec4(u modelview a position, 1.0) gl Position requires a 4 component vector so an extra operation is required at output. However the matrix multiplication is for 9 elements instead of 16. Can I do any better?"} {"_id": 1, "text": "How does one get adjacency information in a geometry shader? If you use triangle adjacency as the input type of a geometry shader, do you need to do something on the client side besides make the primitive mode triangle adjacency? Basically what I'm asking do you need to do anything in your application to make the adjacency information available to the geometry shader besides setting the primitive mode in your draw commands?"} {"_id": 1, "text": "Camera follow 3D Object OpenGL I'm trying to make my camera follow a 3D object, the X and Y values from the camera position are the same as the 3D object, but the Z axis is not the same, it has an offset of 13.0f so the camera looks to the object from a distance. The problem is that, the more I go up with the object, more the object disappears on the screen, its like the camera is following it slowly, or like, since the camera is far away then the object goes up faster than the camera, so how do I center the object in the middle of the camera? my current code for the view matrix of the camera view glm lookAt(position, position forward, up)"} {"_id": 1, "text": "glm rotating quaternion in Y axis deforms object I'm implementing my own game engine in C and I need help here, I have a game object, its orientation property is a quaternion and I want to rotate it A degrees in the Y axis. So, I have currentAngle 0.01 currentAngle is a member variable, so yes i initialized it quat q(currentAngle, vec3(0, 1, 0)) myGameObject gt SetOrientation(q) GameObject SetOrientation(quat q) myOrientation q but as the game object rotates, it also gets scaled (deformed). So I checked how I am applying the transformation matrices myModelMatrix Math CreateTransformationMatrix( transformation gt GetPosition(), transformation gt GetOrientation(), transformation gt GetScale()) mat4 amp Math CreateTransformationMatrix(vec3 amp translation, quat amp orientation, vec3 amp scaleSize) mat4 translate glm translate(glm mat4(), translation) mat4 rotate glm toMat4(orientation) mat4 scale glm scale(glm mat4(), scaleSize) return translate rotate scale but it looks ok (at least to me), I removed the scale matrix form the multiplication to check if somehow I was doing something with it. However, it didnt fix anything. I also tried quat q(currentAngle, vec3(0, 1, 0)) quat orientation myGameObject gt GetOrientation() orientation orientation q myGameObject gt SetOrientation(orientation) But it didnt work either. I also checked the code in my shaders and I am positive is not the problem. This is how I send the matrices to the shader glUseProgram(progarmId) 1 glUniformMatrix4fv(uniforms name , 1, GL FALSE, glm value ptr(matrix)) I tried modifying the 3rd parameter to True and swapping the order of the projection view matrix multiplication and it didnt work either So, guys ... any ideas what could I be doing wrong ? I'm out of ideas"} {"_id": 1, "text": "How do I render a PNG image with OpenGL? I have an image (100 200 px) painted with Paint.NET and saved as a .png with 32 bit color depth. How can I render it using OpenGL 1.1 (with the LWJGL binding) or higher inside the display? I tried creating a ByteBuffer, then loading the pixel color values inside that buffer, but I'm missing the OpenGL settings that need to be enabled. Some help?"} {"_id": 1, "text": "OpenGL Colour Issues I am using a single VBO to store vertices in the follow format v1X, v1Y, v1Z, v1R, v1G, v1B, v2A, v2X, ... Vertex positioning is fine, shapes show up where expected, however instead of using the colour provided, all shapes show up red. The code given below simply draws two triangles to form one square ground shape. Buffer data preparation method public void prepare(float data) glBindBuffer(GL ARRAY BUFFER, vboID) FloatBuffer dataBuffer RenderUtils.fArrayToBuffer(data) if(dataLength ! data.length) glBufferData(GL ARRAY BUFFER, dataBuffer, GL STATIC DRAW) dataLength data.length else glBufferSubData(GL ARRAY BUFFER, 0, dataBuffer) glVertexAttribPointer(0, 3, GL FLOAT, false, 7 4, 0) glVertexAttribPointer(3, 4, GL FLOAT, false, 7 4, 3 4) Render code floorObj.prepare(new float 5, 0, 5, 1, 0, 0, 1, 5, 0, 5, 0, 1, 0, 1, 5, 0, 5, 0, 0, 1, 1, 5, 0, 5, 1, 0, 0, 1, 5, 0, 5, 0, 1, 0, 1, 5, 0, 5, 0, 0, 1, 1, ) glDrawArrays(GL TRIANGLES, 0, 6) Vertex shader version 330 core in vec3 position in vec4 i color out vec4 color uniform mat4 transform void main() gl Position transform vec4(position, 1) color i color Fragment shader version 330 core in vec4 color out vec4 f color void main() f color color As previously stated, vertex positions work fine, however colour does not. Just ask if any other code would be useful to determine the problem. Thanks, Jasper"} {"_id": 1, "text": "How to correctly implement 'layered lighting' with Box2D Lights How does one only allow Box2D Lights to affect one and only one OrthographicCamera. After researching, I found the following answer. This answer goes into detail about how to prevent one camera from being lit by the RayHandler by blending layers of the FBO object. I'm unsure if this answer will produce the results I require. If it indeed does create the results I require, how can I do so more simply elegantly. For example 1) In this image you can see ambient light is set to this.rayHandler.setAmbientLight(new Color(0.1f, 0.1f, 0.1f, 0.25f)) 2) There is a point light on the far right with purple colour. 4) There is a star background on a different OrthographicCamera to the other objects. When looking at this image, you notice that the stars are brighter near the planet due to the point light casting light on the background. However, I require the inverse. The stars should be brighter when light is not drowning them out. Knowing that the star background is on a different OrthographicCamera how can I allow the texture to be completely unaffected by light so the ambient light of the RayHandler does not dim them further away from the planet. The texture used for the stars contains transparency. The black is created using Gdx.gl.glClearColor(0f, 0f, 0f, 1) Preferably, I would like to be able to simply place cameras into two lists, affected by light and not affected by light. How does I produce the results I require? I can manage to get the lighting to ignore the star background by rendering it after the RayHandler has been updated and rendered, however this obviously causes the star background to be drawn over the top of everything like so After achieving this, I was reminded of the OpenGL depth buffer. I enabled it using Gdx.gl.glEnable(GL20.GL DEPTH TEST), I then attempted to change the z coordinate of the spritebatch used in the camera for the star background by using SpriteBatch.getTransformMatrix().idt().translate(0f, 0f, 1f) however after playing with the values of the other sprite batches I can still not get the effect I require. It is possible that the above method did indeed work, although I am aware that using the depth buffer incorrectly can cause issues with alpha blending? Making it seem like my problem was not fixed because the planet became translucent."} {"_id": 1, "text": "Java OpenGL Perspective matrix not working I'm trying to render a simple triangle with OpenGL in Java using LWJGL3. Everything is working great, but the projection matrix (perspective) is not working. In C I just used to apply the glm perspective() method which works just great. But in Java, I implemented it myself since there are no libraries like GLM handling it. So here the code for the perspective in Java public mat4 perspective(float fov, float aspectRatio, float zNear, float zFar) mat4 perspective new mat4() float halfTanFov (float) Math.tan(Math.toRadians(fov 2)) float range zNear zFar perspective.m00 1f halfTanFov aspectRatio perspective.m11 1f halfTanFov perspective.m22 (zFar zNear) range perspective.m23 1 perspective.m32 (2f zFar zNear) range return perspective Of course I tested this multiplication and a compared a result with my TI output, and it worked great. Other information, the default constructor for the mat4 class is putting all the values to 0. here is the code public void setZero() m00 0 m01 0 m02 0 m03 0 m10 0 m11 0 m12 0 m13 0 m20 0 m21 0 m22 0 m23 0 m30 0 m31 0 m32 0 m33 0 the viewMatrix() in the other hand is working great. It's a simple implementation of the lookAt() method. So when it's lookAtMatrix modelMatrix position where the position is a vec4 the result is good. But when I try to add the projection matrix for the MVP perspective lookatMatrix model position the result is nothing. Here where I do it in the code public mat4 getViewProjection() mViewProjection MatrixTransform.getInstance().lookAt(mPosition, mPosition.add(mDirection), mUp) return mViewProjection public mat4 getMVP(mat4 model) return mPerspective.mult(getViewProjection()).mult(model) And here is my simple GLSL shader (for the vertex shader ) version 430 layout(location 0) in vec3 position uniform mat4 MVP void main(void) gl Position MVP vec4(position, 1) I tried other implementation of the perspective without success, so I guess my mistake is somewhere else, but sadly enough, I can't figure out where. If someone could help, it'd be great ! thank you. If you other informations, please ask me and I'll post it. EDIT Here is how I put a mat4 into a uniform public void uniform(String variableName, mat4 matrix) int loc glGetUniformLocation(mId, variableName) FloatBuffer buffer BufferUtils.createFloatBuffer(16) matrix.putIntoBuffer(buffer) buffer.flip() glUniformMatrix4(loc, false, buffer) and the method putIntoBuffer() public void putIntoBuffer(FloatBuffer buffer) buffer.put(m00) buffer.put(m01) buffer.put(m02) buffer.put(m03) buffer.put(m10) buffer.put(m11) buffer.put(m12) buffer.put(m13) buffer.put(m20) buffer.put(m21) buffer.put(m22) buffer.put(m23) buffer.put(m30) buffer.put(m31) buffer.put(m32) buffer.put(m33)"} {"_id": 1, "text": "Rotating a circle on its axis I have a circular shape object, which I want to rotate like a fan along it's own axis. I can change the rotation in any direction i.e. dx, dy, dz using my transformation matrix. The following it's the code Matrix4f matrix new Matrix4f() matrix.setIdentity() Matrix4f.translate(translation, matrix, matrix) Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), matrix, matrix) Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), matrix, matrix) Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), matrix, matrix) Matrix4f.scale(new Vector3f(scale,scale,scale), matrix, matrix) My vertex code vec4 worldPosition transformationMatrix vec4(position,1.0) vec4 positionRelativeToCam viewMatrix worldPosition gl Position projectionMatrix positionRelativeToCam But, it's not rotating along its own axis, it is flipping like a coin instead. What am I missing here?"} {"_id": 1, "text": "Loading screen OpenGL with glut API I'm trying to make a loading screen. My idea is to have two threads working one in the background loading the 'game' scene, one displaying 'load' scene. When building 'game' scene is finished, it's displayed instead of 'load' scene. Before threading I want to make it work the usual way first display 'load' scene, then 'game' scene. Both GameScene and LoadScene inherit from a virtual function Scene. Here's how my main looks like LoadScene load scene GameScene game scene Scene scene int main(int argc, char argv) Init GLUT and create window glutInit( amp argc, argv) glutInitDisplayMode(GLUT DEPTH GLUT DOUBLE GLUT RGBA GLUT STENCIL) glutInitWindowPosition(initWindowX, initWindowY) glutInitWindowSize(windowWidth, windowHeight) glutCreateWindow(\"OpenGL\") Register callback functions for change in size and rendering. glutDisplayFunc(renderScene) glutReshapeFunc(changeSize) glutIdleFunc(renderScene) Register Input callback functions. 'Normal' keys processing glutKeyboardFunc(processNormalKeys) glutKeyboardUpFunc(processNormalKeysUp) Special keys processing glutSpecialFunc(processSpecialKeys) glutSpecialUpFunc(processSpecialKeysUp) Mouse callbacks glutMotionFunc(processActiveMouseMove) glutPassiveMotionFunc(processPassiveMouseMove) void glutMouseFunc(void( func)(int button, int state, int x, int y)) glutMouseFunc(processMouseButtons) glutMouseWheelFunc(processMouseWheel) Position mouse in centre of windows before main loop (window not resized yet) glutWarpPointer(windowWidth 2, windowHeight 2) Hide mouse cursor glutSetCursor(GLUT CURSOR NONE) warp Initialise input and scene objects. input new Input() scene new LoadingScene(input) load scene new LoadScene() game scene new GameScene(input) load scene Create GameScene() Create LoadingScene(GameScene ) delete LoadingScene() LoadingScene thread tells game to start loafing assetss Enter GLUT event processing cycle glutMainLoop() return 1 The game scene reassignment must be called in changeSize function. I thought it should be in the renderScene function but it's the only way it works. Here's how it looks like void changeSize(int w, int h) scene load scene scene gt resize(w, h) Any ideas how I could go on about it? So far if I assign to 'scene' pointer 'load scene' object it's displaying 'load' scene. Same goes for 'game' scene. Is it even possible to achieve a transition between scenes without threading?"} {"_id": 1, "text": "Efficient way of loading wavefront models in openGL game In my game, a RTS game, the units are all wavefront obj. all their animation frames are each seperate wavefront obj file. ie. without any skeletal animation fully rigid models. So when many units are loaded before a game starts, it takes too much time. for example, if 20 types of units are loaded, they take approximately 700 800MB in memory, take atleast 3 minutes to load. Can it be done in an efficient way somehow? Solutions I have already used As obj parsing take too much time. I have stored each obj as memory dump and load that dump. This helped a lot atleast reduced to 3min from 10min, for above example. Further Possible solution I tried I tried loading the anination frames on runtime, when they are accesessed. But this is making the game slow at some crucial time. Like when fighting, all units' fighting frames are loaded together. thus making the game slow. loading the units in different threads. Makes no improvement"} {"_id": 1, "text": "Loading multi texture 3ds c I have a question about loading 3ds using this tutorial. I want to use more than one texture on the model (because here all the models have more than one) but it seems that this library can't do that. Do you know any other alternatives or a way to edit this existing library to reach my aim?"} {"_id": 1, "text": "Perspective projection matrix with a non orthogonal near plane I'm trying to figure out a way to provide such a perspective projection matrix to a shader that the \"near\" plane wouldn't necessarily be orthogonal to the camera vector. More specifically, I'm basically trying to clip all vertices above a certain y coordinate, but I don't have access to the shader programs themselves. Is there such a matrix that would throw those vertices with a y coordinate over some specific value outside of the clip space?"} {"_id": 1, "text": "Is glDrawArraysInstanced in OpenGL parallel when drawing those instances? Is glDrawArraysInstanced in OpenGL parallel when drawing those instances? I cannot figure out by referring to its reference and numerous online tutorials. Update To be more clear, I mean, for example, we have 100 instances. Are the drawing of those 100 instances parallel? For example, we have the 100 commands \"glDrawArrays(mode, first, count) \"? Is execution of those 100 commands sequential or parallel? I think it should be sequential. GPU begins to draw the second instance, only AFTER the first instance drawing finished. Or glDrawArraysInstanced just save the time for \"giving your GPU the commands\"? Update 2 The reason I wanted to know the answer, is that If it is sequential, personally I think drawing thousands of tree leaves in this way is time consuming. I may draw them in one shader program with some algorithm tweak."} {"_id": 1, "text": "Sorting a vector using array version of quick sort I'm coding a simple rendering engine using OpengGL and I wrote a class that manages a particle system. The class creates the particles and pushes them into a vector to be used by a renderer to draw them on screen. I need to order the particles from the farthest to the nearest to the camera (in order to solve problems with alpha blending and depth, having disabled depth testing for transparency), so I tried with the following code void ParticleRenderer render() prepare renderer ..... update particle state (position,ecc..) and remove it if necessary update returns a bool indicating if particle is still alive while (it ! mParticles.end()) if (!( it) gt update()) delete it it mParticles.erase(it) if (it mParticles.end()) break else continue it if (mParticles.size() gt 0) sortParticles( amp mParticles 0 , 0, mParticles.size() 1) for (Particle particle mParticles) ..... render particle ..... std cout lt lt getCameraDistance(particle) lt lt std endl std cout lt lt \" \" lt lt std endl mShader.unuse() glDisable(GL BLEND) void ParticleRenderer sortParticles(Particle particles, int low, int high) if (low gt high) return Particle temp particles low while (true) while (compareParticles(temp, particles high ) gt 0 amp amp low lt high) high if (low high) break else particles low particles high while (compareParticles(temp, particles low ) lt 0 amp amp low lt high) low if (low high) break else particles high particles low particles high temp int middle high sortParticles(particles, low, middle 1) sortParticles(particles, middle 1, high) double ParticleRenderer compareParticles(Particle particle1, Particle particle2) return getCameraDistance(particle1) getCameraDistance(particle2) double ParticleRenderer getCameraDistance(Particle particle) glm vec3 distance mCamera.getPosition() particle gt getPosition() return glm length(distance) but what I get on the console are all unsorted particles (the cout statement) and of course I have problems when the particles are rendered on screen. Am I missing something? I know I could use std sort and the STL algorithms, but since I'm learning I would like to know what I am doing wrong."} {"_id": 1, "text": "OpenGL Debug version runs faster than Release version My Visual Studio 2019, 64 bit version of Tetris using OpenGL runs significantly faster, 3X, in Debug mode than in Release mode. The image above shows the board. Each cycle of the rendering or game loop redraws everything, viz., the light blue background, the grid, the individual game pieces (one shown) with the latest one added moving every 300 ms, and the text score display. I have moved all the repetitive code out of the loop, e.g., that which sets the location in shaders for uniform constants. The Release mode loop cycle time ranges from 0.05 to 1390.0 ms while that of the Debug mode ranges from 0.05 to 350.0 ms. Any thoughts on what I might investigate? Thanks."} {"_id": 1, "text": "Aggregation of value in GLSL loop results in 0 I'm banging my head against a wall trying to understand why this code is giving me some reasonable results with some visible colors on parts of the screen... version 130 in vec2 vTex must match name in vertex shader flat in int iLayer must match name in fragment shader out vec4 fragColor first out variable is automatically written to the screen uniform sampler2DArray tex uniform sampler2DArray norm define MAX LIGHTS 4 struct Light vec3 position vec4 color vec3 falloff vec3 aim float aperture float aperturehardness uniform Light lights MAX LIGHTS void main() vec4 DiffuseColor texture(tex, vec3(vTex.x, vTex.y, iLayer)) if (DiffuseColor.a 0) discard vec3 NormalMap texture(norm, vec3(vTex.x, vTex.y, iLayer)).rgb NormalMap.g 1.0 NormalMap.g vec3 FinalColor vec3(0,0,0) for (int i 0 i lt MAX LIGHTS i ) vec3 LightDir vec3((lights i .position.xy gl FragCoord.xy) vec2(320.0, 200.0).xy, lights i .position.z) float D length(LightDir) vec3 N normalize(NormalMap 2.0 1.0) vec3 L normalize(LightDir) vec3 Diffuse (lights i .color.rgb lights i .color.a) max(dot(N, L), 0.0) vec3 sd normalize(vec3(gl FragCoord.xy, 1.0) lights i .position) float Attenuation smoothstep(lights i .aperture lights i .aperturehardness, lights i .aperture, dot(sd,lights i .aim)) (lights i .falloff.x (lights i .falloff.y D) (lights i .falloff.z D D) ) vec3 Intensity Diffuse Attenuation FinalColor max(FinalColor, DiffuseColor.rgb Intensity) fragColor vec4(FinalColor, DiffuseColor.a) ... but when I change FinalColor max(FinalColor, DiffuseColor.rgb Intensity) to FinalColor clamp(FinalColor DiffuseColor.rgb Intensity, vec3(0,0,0), vec3(1,1,1)) everything goes black. Is there something I don't understand about aggregation of variables in loops in GLSL, or about the operator operating on vectors? By my logic, the changed code should return more brightness than the original code because the changed code would be adding all the values whereas the old code would just be taking the highest one."} {"_id": 1, "text": "Render scene twice in OpenGL, overlay second render with tranparency Is it possible to render two scenes (same scene with different setups) without any alpha, and after that is done just overlay the result from the second render on top of the first layer with a static transparency? And how do I do it? I want it fast so the transparency should not be implemented during rendering, only on the final overlay process. Basically I am asking for an efficient OpenGL post processing method to combine the two different renders when drawing to screen."} {"_id": 1, "text": "What is the convention for column major order matrix transformations? According to this cheat sheet for CG, if I want to use column major order for my matrix vector math I have to multiply from the left applying transformations from right to left, i.e. v' P V v I built my view and projection matrices like this Matrix44 view(right.x, right.y, right.z, position.x, up.x, up.y, up.z, position.y, forward.x, forward.y, forward.z, position.z, 0.0f, 0.0f, 0.0f, 1.0f) Matrix44 projection(Sx, 0.0f, 0.0f, 0.0f, 0.0f, Sy, 0.0f, 0.0f, 0.0f, 0.0f, Sz, Pz, 0.0f, 0.0f, 1.0f, 0.0f) However, when using them in the vertex shader gl Position projection view vec4(position, 1.0) I cannot see my geometry unless I swap the transformation to gl Position vec4(position, 1.0) view projection which means that I am using row major order instead of column order. So my question is if the pdf I'm following is correct in the notation for the column major order for view and projection matrices or what am I missing?"} {"_id": 1, "text": "OpenGL Bump Map Texture artifacts ? I am learning OpenGL (and learning the math behind it) and I'm making a simple OBJ viewer, nothing fancy. I have diffuse, specular and ambient light texture working fine and now I am implementing the bump mapping. I based my code on what I learned with the OpenGL 4.3 Redbook and \"Mathematics for 3D game programming and computer graphics\" book. There is probably something I didn't understand correctly, I just hope you will be able to help me ) Anyway this is the result I get (from a free asset used just for testing the results are fine in blender) This is the diffuse texture and the bump map Fragment shader code void main() vec3 normalDirection normalize(tangenteSpace (texture2D( bump tex, f texcoord ).rgb 2.0 1.0)) vec3 normalDirection normalize(mat3(invTransp) vertNormal) vec3 viewDirection tangenteSpace normalize(vec3(invView vec4(0.0, 0.0, 0.0, 1.0) position)) float attenuation 1.0 none vec3 vertToLightSource vec3(light.position position light.position.w) float distance length(vertToLightSource) attenuation mix(1.0,1.0 (light.constantAttenuation light.linearAttenuation distance light.quadraticAttenuation distance distance),light.position.w) vec3 lightDirection tangenteSpace (vertToLightSource distance) spotlight if spotCutoff lt 90 float clampedCosine max(0.0, dot( lightDirection, normalize(light.spotDirection))) float tempMix mix(attenuation pow(clampedCosine, light.spotExponent),0.0,clampedCosine lt cos(light.spotCutoff 3.14159 180.0)) if outside of spotlight nothing attenuation mix(attenuation,tempMix,light.spotCutoff lt 90.0) should there be any attenuation ? attenuation mix(attenuation,1.0,light.position.w) ambiant light vec3 ambientLight vec3(ambientScene) vec3(mat.Ka) specular light get the reflection vec4 specularMapPixel texture2D(spec tex, f texcoord).rgba vec3 specularColor specularMapPixel.rgb float shininess specularMapPixel.a vec3 specularReflection mix( attenuation vec3(light.specular) vec3(mat.Ks) pow(max(0.0, dot(reflect( lightDirection, normalDirection), viewDirection)),mat.Ns shininess) specularColor.rgb, vec3(0.0, 0.0, 0.0), dot(normalDirection, lightDirection) lt 0.0 ) vec3 diffuseReflection attenuation vec3(light.diffuse) vec3(mat.Kd) max(0.0,dot(normalDirection,lightDirection)) vec4 Color vec4(vec4(specularReflection,1.0) vec4(ambientLight,1) texture2D(amb tex, f texcoord) vec4(diffuseReflection,1.0) texture2D(dif tex, f texcoord)) FragColor Color Vertex Shader Code void main() comnpute tangent space tangenteSpace 0 mat3(mv) normalize(tangent.xyz) tangenteSpace 2 mat3(mv) normalize(vertNormal) tangenteSpace 1 mat3(mv) normalize(cross(tangenteSpace 0 ,tangenteSpace 2 ) tangent.w) tangenteSpace transpose(tangenteSpace) position in world space position m vertCoord f texcoord vec2(texCoord) gl Position mvp vertCoord"} {"_id": 1, "text": "Triple buffering causes input lag? Consider some time in between two vsyncs. Suppose the first display buffer is being used to display the current image, and suppose the game was really fast and computed and rendered the next image to the second display buffer and the next one after that to the third display buffer. That is the rendering to the second and third display buffer happens so fast that it occurs before the next vsync. Suppose input from the user comes in now. What you would like is for the results of the input to show up on the next vsync or (probably more typical) the vsync after that. However, with the third display buffer already rendered the input can only effect the image after that. Meaning the input will only take effect at best 3 vsyncs later. I wish i had an image to show the exact timings of what I mean."} {"_id": 1, "text": "What's wrong with this camera implementation? I'm using WebGL and glMatrix and I implemented a camera. When a move backward, no problem. But when I move to the side and particularly forward, the camera becomes all glitchy. I implemented almost exactly the same camera before in C and it worked perfectly. I put the whole code on jsFiddle (with glMatrix because it's not in the list and I didn't find a url, sry). https jsfiddle.net ydx0Lr1v 14 Click and move the mouse to move around. Also, the more I decrease the speed of the camera movement, the more it works well. I put a high speed to dramatize the effect. I know I should make the speed of the camera depend on the time between each frame, but I haven't implemented an fps counter yet. Thanks! Edit Hum, that's strange. In jsFiddle the camera seems to work better when moving forward."} {"_id": 1, "text": "Depth Peeling implementation problem How to render the next layer? (OpenGL) I try to implement order independet transparency sticking to the pseudo code in the linked paper (page 4). I can't figure out how they are able to do this in OpenGL. I am rendering the scene two times in two different framebuffers and then want to blend the two. The first rendering uses the normal depth test GL LESS. So I receive the nearest fragments in the first framebuffer. I want to render the second nearest fragments in the second framebuffer. In the pseudo code they use the depth test GL GREATER for this. But this would result in having the \"farest\" fragments in the second framebuffer, right? So how can I render the \"second nearest\" pixels to a framebuffer? Which depth test would be right and how to apply it in OpenGL?"} {"_id": 1, "text": "OpenGL slower than Canvas Up to 3 days ago I used a Canvas in a SurfaceView to do all the graphics operations but now I switched to OpenGL because my game went from 60FPS to 30 45 with the increase of the sprites in some levels. However, I find myself disappointed because OpenGL now reaches around 40 50 FPS at all levels. Surely (I hope) I'm doing something wrong. How can I increase the performance at stable 60FPS? My game is pretty simple and I can not believe that it is impossible to reach them. I use 2D sprite texture applied to a square for all the objects. I use a transparent GLSurfaceView, the real background is applied in a ImageView behind the GLSurfaceView. Some code public MyGLSurfaceView(Context context, AttributeSet attrs) super(context) setZOrderOnTop(true) setEGLConfigChooser(8, 8, 8, 8, 0, 0) getHolder().setFormat(PixelFormat.RGBA 8888) mRenderer new ClearRenderer(getContext()) setRenderer(mRenderer) setLongClickable(true) setFocusable(true) public void onSurfaceCreated(final GL10 gl, EGLConfig config) gl.glEnable(GL10.GL TEXTURE 2D) gl.glShadeModel(GL10.GL SMOOTH) gl.glDisable(GL10.GL DEPTH TEST) gl.glDepthMask(false) gl.glEnable(GL10.GL ALPHA TEST) gl.glAlphaFunc(GL10.GL GREATER, 0) gl.glEnable(GL10.GL BLEND) gl.glBlendFunc(GL10.GL ONE, GL10.GL ONE MINUS SRC ALPHA) gl.glHint(GL10.GL PERSPECTIVE CORRECTION HINT, GL10.GL NICEST) public void onSurfaceChanged(GL10 gl, int width, int height) gl.glViewport(0, 0, width, height) gl.glMatrixMode(GL10.GL PROJECTION) gl.glLoadIdentity() gl.glOrthof(0, width, height, 0, 1f, 1f) gl.glMatrixMode(GL10.GL MODELVIEW) gl.glLoadIdentity() public void onDrawFrame(GL10 gl) gl.glClear(GL10.GL COLOR BUFFER BIT) gl.glMatrixMode(GL10.GL MODELVIEW) gl.glLoadIdentity() gl.glEnableClientState(GL10.GL VERTEX ARRAY) gl.glEnableClientState(GL10.GL TEXTURE COORD ARRAY) Draw all the graphic object. for (byte i 0 i lt mGame.numberOfObjects() i ) mGame.getObject(i).draw(gl) Disable the client state before leaving gl.glDisableClientState(GL10.GL VERTEX ARRAY) gl.glDisableClientState(GL10.GL TEXTURE COORD ARRAY) mGame.getObject(i).draw(gl) is for all the objects like this HERE there is always a translatef and scalef transformation and sometimes rotatef gl.glBindTexture(GL10.GL TEXTURE 2D, mTexPointer 0 ) Point to our vertex buffer gl.glVertexPointer(3, GL10.GL FLOAT, 0, mVertexBuffer) gl.glTexCoordPointer(2, GL10.GL FLOAT, 0, mTextureBuffer) Draw the vertices as triangle strip gl.glDrawArrays(GL10.GL TRIANGLE STRIP, 0, mVertices.length 3) EDIT After some test it seems to be due to the transparent GLSurfaceView. If I delete this line of code setEGLConfigChooser(8, 8, 8, 8, 0, 0) the background becomes all black but I reach 60 fps. What can I do?"} {"_id": 1, "text": "JOGL Hardware Shadow Mapping Transparent Shadow Texture I'm using hardware shadow mapping on JOGL based on the demo(HardwareShadowMapping) supplied by the distribution. After generating the shadow texture from lights point of view, I apply it to my scene with no problems. What I'm looking for is soft shadows instead of pitch black shadows. Is there any way that I can change the alpha values while applying the shadow depth texture? Btw I'm not an expert on OpenGL especially about custom shaders and I don't want to spend more time on understanding and developing custom shaders instead of the game. Here's a screenshot of the application in case you come up with another solution to what I'm trying to achieve. The game is actually a hack amp slash RTS hybrid.Here's the pseudo code of the gl event listener attached to shadow pbuffer. gl.glClear(GL.GL COLOR BUFFER BIT GL.GL DEPTH BUFFER BIT) gl.glPolygonOffset(polygonOffsetFactor, polygonOffsetUnits) gl.glEnable(GL.GL POLYGON OFFSET FILL) render shadow casting geometry gl.glDisable(GL.GL POLYGON OFFSET FILL) gl.glBindTexture(GL.GL TEXTURE 2D, lightViewTextureID) gl.glCopyTexSubImage2D(GL.GL TEXTURE 2D, 0, 0, 0, 0, 0, textureSize, textureSize) I sense here a way of updating alpha values of this texture"} {"_id": 1, "text": "Raypicking raytracing in OpenGL Alright, so before you down vote saying that OpenGL doesn't support rays for rendering, please read So I want to detect a quad in opengl 1.1( I don't want to use opengl 3.0). I wanted to detect it using OpenGL, but that doesn't seem possible. But basically I have one choice, which is kind of \"hacky\". I create custom matrices and store the transformed vertices somewhere, then do a simple collision test. What is the common way of doing ray tracing in legacy OpenGL?"} {"_id": 1, "text": "Multiple semi dynamic objects in one VBO I am working on a game that uses opengl 3. The huge geometry is spread over a grid of about 270,000 cells. The geometry in each cell, though not very frequently, can change independently from other cells. Usually most of these cells don't contain any geometry at all. Until now my approach was to have one vertex buffer object per cell. Today i discovered that alone generating all these VBOs (without any data in them) results in almost 1GB of main memory usage. That would be equivalent to an overhead of around 3KB per VBO. As it seems this overhead can not be avoided, i first thought of generating a VBO only when the cell creates its first geometry and deleting it once the cell becomes empty again. This might work quite well, but it would still be inefficient if the geometry happens to have very few geometry in every cell. So i searched for a different solution and read, that one approach is to put multiple meshes in a single VBO. The problem with that is, that the mesh of a cell may change its size and require more memory in the VBO than initially. This would require subsequent meshes in the VBO to be shifted. Now my question is How do i do that? Do i have to save the mesh for every cell, so i can rewrite it into the VBO when it needs to be shifted? Would glMapBuffer help me? Also Is there a better, completely different solution? Thanks in advance!"} {"_id": 1, "text": "convert gl Position into screen coordinates Pretty simple question I think. I need to convert model space coordinates into screen space coordinates for a special shader effect. I am of course able to just convert them into gl Position coordinates by just multplyng them with the wold view and projection matrices. Unfortunately though, thats where I am at my wits end. Since opengl somehow converts normal vertices them into screen coordinates itself, and I need a few extra vertices for a special effect, I have no idea how to achieve this. So does anybody have any idea how I convert model space coordinates into gl Fragcoord screen coordinates? I basicly want to be able to give the vertex shader a bunch of model space coordinates and have it spit out where exactly they are on the screen if they were rendered."} {"_id": 1, "text": "OpenGL light calculation I want to add somebasic point lights to my OpenGL application. I read here that I have to caluclate the light in a pre projection space Lighting can be done in any pre projection space (e.g., world coordinates or eye coordinates), as long as all the objects and lights are all in that same space. And here is my problem. My Renderer currently looks something like this public void onDrawFrame(GL10 unused) GLES20.glClear(GLES20.GL COLOR BUFFER BIT GLES20.GL DEPTH BUFFER BIT) Matrix.multiplyMM(camProjection, 0, projection, 0, camera, 0) for(int i 0 i lt sceneObjects.size() i ) SceneObject object sceneObjects.get(i) object.draw(camProjection) ... As you can see I multiply my projectionMatrix with the viewMatrix and I think that is a good solution because I only have to do this once. To draw I give the PVMatrix to all objects and multiply it with their modelMatrix and then I push the finall MVPMatrix to the shader. This is a problem because I can not calculate the light direction in eye space in the shader because I do not have any pre projection matrix here. Do I really have to push a MVMatrix to the shader and calculate the normals and so on with it? I think this is really inefficient because I have to do much more matrix multiplications, isn't it? What would you suggest to calculate this efficiently?"} {"_id": 1, "text": "Game assets are images or 3D models I am new to game development and I have created simple games with javascript and SFML. Those games are 2D and there I used images as my gaming assets. I was trying to be familiar with OpenGL like 3D modeling APIs. In 3D gaming is all the assets are 3D models or there can be some images like in 2D?"} {"_id": 1, "text": "Accessing 3D texture data without normalized coordinates directly, but with filtering texelFetch() exists to access texture data with texture coordinates in \"image dimensions\", but texelFetch skips filtering. In case of 2D textures, it's possible to use a rectangle texture sampler to access textures without normalized coordinates with filtering, but the same equivalent doesn't seem to exist for 3D textures. Is this somehow possible with 3D textures?"} {"_id": 1, "text": "3D camera window resolution relation I'm having a bit of an issue when it comes to 3D and 2D camera(s), in relation to a game's window resolution. I want to let the player choose from different window resolutions, either from a menu or by just resizing the window by dragging the window border, and can't get the scaling of the graphics to work properly. In games I've played, I can go into the options menu, choose a screen resolution and then the window resize itself and the graphic's, menu buttons etc just scales up to the correct sizes. At the moment, I've tried two different window resolutions 800x600 and 1280x720 (don't mind the different aspect ratios). 800x600 1280x720 As you can see, more of the game world can be seen (more stone tiles can be seen, if that makes sense) in the window with a resolution of 1280x720 and I want my 3D 2D game(s) to be resolution independent and that the same amount of the game world to be seen, independent of what window resolution the player chooses to use. My camera class consist of Camera matrix used to translate and rotate my camera View matrix the inverse of the camera matrix Perspective matrix see code below View projection matrix view matrix perspective matrix Fov 45.0f Aspect ratio camera width camera height Note row major matrices Perspective matrix const float Tangent 1.0f tanf(DEGREES TO RADIANS(Fov 0.5f)) const float NearToFar FarClip NearClip PerspectiveMatrix(Identity) PerspectiveMatrix 0 Tangent AspectRatio PerspectiveMatrix 5 Tangent PerspectiveMatrix 10 FarClip NearToFar PerspectiveMatrix 11 1.0f PerspectiveMatrix 14 ( NearClip FarClip) NearToFar PerspectiveMatrix 15 0.0f At each update, I'm also setting the viewport by calling glViewport(0, 0, CameraWidth, CameraHeight). This might change in the future if I decide to make two cameras in a game, for a splitscreen game for example. How can I solve the window resolution independence issue? I have though about creating a framebuffer the size I want, attach it to a quad and then render the quad the size of the window, which will scale up down the framebuffer if the window is bigger smaller than the framebuffer's original size, but if it's an easier way of doing it, I would gladly use that instead."} {"_id": 1, "text": "What are \"free vertex indices\" in WebGL 2 and how do they relate to geometry shaders? In January Notch tweeted about WebGL 2 WebGL 2 is happening. Bye, compatibility! Hello, 3d textures and pixel buffers! oh god it's got free vertex indices in the shader. That is basically a geometry shader. .. which is great considering I'm rendering like five triangles.. What are these quot free vertex indices quot and how do they relate to geometry shaders? I'm new to all this and my google fu is failing me on this occasion."} {"_id": 1, "text": "What happens to OpenGL buffer data that isn't used? I have a vertex struct that has 5 glm vec3 but some of my objects only use 2 or 3 of those members. So I have two questions 1.) What happens to the large buffer I create, even though I don't use all the data. Struct Vertex glm vec3 pos, color, UV, normal, tangent std vector lt Vertex gt vertices will store the vertex data glBufferData(GL ARRAY BUFFER, vertices.size() sizeof(Vertex), vertices.data(), GL STATIC DRAW) That creates a buffer that is larger than needs to be. Is the additional buffer data not send? 2.) If I send empty data to the buffers, is it causing any performance issues? glVertexPointer(2, 3 , GL FLOAT, GL FALSE, size of(Vertex), reinterpret cast lt GLvoid gt (Offsetof(Vertex, unusedData)) Thanks for the information!"} {"_id": 1, "text": "An API independent way of managing video memory? I'm developing a game. The game architecture is very modular. I have a \"Graphics Engine\", which uses either a Direct3D or OpenGL renderer. However the user does not have access to the renderers directly. Instead the \"Graphics Engine\" class is used, which uses a renderer interface. I also have a resource management system. As for now, the renderers are respoinsible for allocating and releasing video memory. That couples my design in a bad way, since the \"Graphics Engine\" has undesirable logic for transferring resources between the RAM and the VideoRam through sending signals to the \"Renderer\". I want the resource management system to be responsible for allocating video memory. I want to decouple the \"Renderer\" and \"Graphics Engine\" classes as much as possible, and make the renderer only responsible for rendering. Is there a way to obtain a universal pointer to a Video RAM buffer, and use it to render with both renderers? My problem is basically that I can only obtain OpenGL or Direct3D handles, which can be used only from the relevant API. And the \"Graphics Engine\" should not know which renderer it uses."} {"_id": 1, "text": "How do I ensure my skybox is always in the background, with OpenGL? I created a skybox in OpenGL (through LWJGL), but the only way I found to render it behind all objects was to make it very big. This leads to ugly edges between the 6 skybox planes. Optimally, I would draw a small skybox and disable DepthTesting on all other objects, but since I want those to display in the right depth order, that isn't possible. How can I do this?"} {"_id": 1, "text": "What causes the difference between these boxes? I have recently started using Blender and I notice that the light (from my game) on default box is different from the one I downloaded. The below picture shows that. They have the same normal direction in Blender. Thanks in advance."} {"_id": 1, "text": "OpenGl indices array I have a class terrain which create a grid of Quads. I do it like this for(int z 0 z lt length z ) for(int x 0 x lt width x ) vertices.push back(vec3((float)x 250, 0.f, (float)z 250)) for(int z 0 z lt ( length 1) z) for(int x 0 x lt ( width 1) x) int index z width x Vertex vertices Vertex(vertices.at(index),vec3(0, 0, 0)), Vertex(vertices.at(index 1),vec3(0, 0, 0)), Vertex(vertices.at(index width),vec3(0, 0, 0)), Vertex(vertices.at(index 1 width),vec3(0,0,0)) unsigned short indices index,index 1,index width,index 1,index width,index width 1 Quad quad( vertices, 4, indices, 6) squares.push back(quad) i The vertices and the logic are correct, but the indices aren't, for some reason. here is the output for this code But when I change this indices to this unsigned short indices 0,1,2,1,2,3 It works great The problem is I don't understand why this line unsigned short indices index,index 1,index width,index 1,index width,index width 1 doesn't work. And if it worked, my grid would consume a lot less ressources. If someone could explain me why it doesn't work, It would be great, thanks you. In case you need to know how I draw a Quad, here is the code class Quad public Quad(Vertex vertices, int n, unsigned short indices, unsigned short numIndices) for(int i 0 i lt numIndices i ) indices.push back( indices i ) for(int i 0 i lt n i ) vec3 v vec3( vertices i .position, lengthPower) position.push back(v) glGenVertexArrays(1, amp mVertexArray) glBindVertexArray(mVertexArray) glGenBuffers(1, amp mPositionBuffer) glBindBuffer(GL ARRAY BUFFER, mPositionBuffer) glBufferData(GL ARRAY BUFFER, sizeof(vec3) position.size(), position.data(), GL STATIC DRAW) glGenBuffers(1, amp mIndicesBuffer) glBindBuffer(GL ELEMENT ARRAY BUFFER, mIndicesBuffer) glBufferData(GL ELEMENT ARRAY BUFFER, sizeof(unsigned short) indices.size(), indices.data(), GL STATIC DRAW) void draw() glEnableVertexAttribArray(0) glBindBuffer(GL ARRAY BUFFER, mPositionBuffer) glVertexAttribPointer(0, 4, GL FLOAT, GL FALSE, 0, 0) glBindBuffer(GL ELEMENT ARRAY BUFFER, mIndicesBuffer) glDrawElements(GL TRIANGLES, indices.size(), GL UNSIGNED SHORT, 0) glDisableVertexAttribArray(0) Quad() private std vector lt unsigned short gt indices std vector lt vec3 gt position GLuint mVertexArray GLuint mPositionBuffer GLuint mIndicesBuffer I'm using, OpenGL, glm, glfw etc."} {"_id": 1, "text": "Are there any advantages of Vulkan using traditional methods? I keep hearing that Vulkan meant for direct low level operations with the GPU and hence it's targeted toward expert and experienced graphics programmers. What would be some other advantages of Vulkan that are usable for a more traditional graphics programmer, rather than a full blown AAA expert? One advantage I keep hearing about is multi threading support. It's buzzing in media to annoying levels, yet still never explained what and how it's different from OpenGL's level of multi threading."} {"_id": 1, "text": "OpenGL ES 2.0 Converting GL TRIANGLES into GL TRIANGLE STRIP I export my 3D geometry from a 3D authoring application. It is possible to export the vertex coordinates as full triangle arrays. On ther other hand, triangle strips are more efficient for the OpengGL to render. This is especially true for OpenGL ES, which is very sensitive for performance. Is it therefore possible to convert GL TRIANGLES arrays into GL TRIANGLE STRIP, please? Could anybody provide me with working algorithm? Thank you."} {"_id": 1, "text": "Taking a 2D slice of a 3D volume I have a regular 3D polygon and I'd like to display 2D slices of it. What is the best way to achieve this? (Preferrably in OpenGL, but a general algorithm tecnique would be good as well). I've already tried by using a camera with narrow z near z far values, but that doesn't seem like a good solution. I don't know if this could be implemented with a custom shader. Edit An example of what I'd like to do Kind of the opposite of what is commonly known as 'Volume Rendering'. Here's an older example http answers.unity3d.com questions 941826 2d slice from a 3d cross section slice.html"} {"_id": 1, "text": "Normal Mapping space confusion I've been reading today about normal mapping. Up to now, the only normal mapping I encountered was with maps already in world space so I just extracted the info from the texture and transformed them with the normal matrix. Now I wanted to try to use a normal map that is in tangent space, but I immediately became really confused. What I've in my code up to now is Vertex Shader ... passedPosition modelViewMatrix vec4(vertexPosition,1.0) ... Fragment Shader vec3 V normalize( passedPosition .xyz) Eye vector ... vec3 L dir passedPosition .xyz lights i .lightPosition.xyz vec3 L normalize(L dir) ... And then proceed with my lighting calculations. All the tutorial I came across change all the light directions and the view vector into tangent space (in the vertex shader) and then extract the normal from the texture and keep going (in fragment). My issue here is that I'd like to avoid to access all my lights informations in the vertex shader, so my questions are Does make sense to pass to the fragment shader the t,b,n vectors so that I transform the light directions there? Should I consider access all my lighting informations in vertex shader (I have an array of Light struct which has more than just the position) and then passed them on to the fragment shader? Is something I'd like to avoid, but if is much better I can think of it. There is a way to perform normal mapping that is more compatible with what I've now (snippets above posted). Should I consider change my calculations from view space to world space? In that case, how can I perform normal mapping? Thanks"} {"_id": 1, "text": "How to render a curved horizon when rendering terrain far away For games with long view distance, it might look at bit weird when you fly high above the ground and the horizon is all flat. So, how can I make a crumb bend effect, when I fly high above the surface? Can this be done in the shaders? If you're not sure what I mean, heres a picture A more clear example, though it might be captured with fish eye. What would this best way to do this? I believe you could rotate and move (using transformationMatrix) all vertices a tiny little bit according to how far they are from the camera. But would this even create the desired effect, and would it be too resource extensive? Or maybe you know a whole another way to do it."} {"_id": 1, "text": "Image speeds up while moving and or rotating instead of constant speed I'm having a problem with rotating moving an image. I've set one of my images to rotate on it's z axis buy updating the angle, but when I run my game, the image starts slowly starts to rotate from a stationary position as if to build up momentum. Once it reaches a certain speed, it begins to slow down to almost a stop, then repeats the process over. Furthermore, when it starts to rotate, it's rotating clockwise. But halfway before it stops, it's now rotating counter clockwise. If I were to only update it's x or y position or both, the image will move slow, then speed up to the desired speed, instead of moving at the desired speed at start. Lastly, if I were to rotate AND move the image, the image shakes erratically while rotating. My suspicion is that I'm calculating something wrong. Within Shader uniform mat4 projection uniform mat4 view uniform mat4 model .... gl Position projection view model vec4(position, 1.0) init() projection glm ortho(LEFT, RIGHT, BOTTOM, TOP, ORTHO NEAR, ORTHO FAR) mSprite.init(\"res texture foo.png\", 1.0f) mSprite.setPosition(mPosition) mSprite.setRotation(rot, glm vec3(0, 0, 1)) glm vec3 pos(1.5, 0.5, 0.0) mSprite2.init(\"res texture bar.png\", 1.0f) mSprite2.setPosition(pos) mSprite2.setRotation(0.0f, glm vec3(0, 1, 0)) update() mPosition.x 0.000005f mPosition.y 0.000005f mSprite.setPosition(mPosition) rot 0.0005f mSprite.setRotation(rot, glm vec3(0, 0, 1)) render() mShader gt start() mShader gt LoadProjectionMatrix(projection) mSprite.draw(mShader, view) mSprite2.draw(mShader, view) mShader gt stop() draw(Shader shader, glm mat4 amp view) (mSprite) shader gt LoadViewMatrix(view) shader gt LoadTransformMatrix(mModel) shader gt connectTexture(mTexture.id) Draw image... void setPosition(glm vec3 position) mModel glm translate(mModel, position) void setRotation(GLfloat angle, glm vec3 axis) mModel glm rotate(mModel, angle, axis)"} {"_id": 1, "text": "Opengl create tunnel TRIANGLES and texture coords on a 3d path I have a path, lets say a bezier, or a circle. I d like to make a continously 3d cylinder (tunnel) on it (R 0.5f) How can I calculate tha TRIangles (TRIANGLE STRIP) coordinate, and the texture coords right?"} {"_id": 1, "text": "Techniques for managing vertex buffer memory I'm learning OpenGL and I haven't seen any advice on managing vertex buffers in all of the tutorials I've read. The basic problem is that I have some memory allocated as a buffer B in which I'm going to store vertex data to send to the graphics card. Then I have the data that represents my domain D. This is the data that the game's simulation is run against. Let's say in a simple case it's just a list of 100,000 circles that will be moving around. Let's also assume that all of the data can, but might not, change every frame. Nothing is necessarily static. I'm looking for the techniques people use to efficiently fill B with D. I could create a new B each frame, but I imagine that would be very expensive. I could give every object in D a pointer to a location in B and have it update that pointer directly, but that strikes me as error prone as then I have to manage all of these pointers. I could also traverse D and fill a reused B every frame. This is what I'm currently leaning towards. The only problem here is that I'm forced to update every vertex in B every frame (because the location of the vertex data for a particular D could change within B) unless I come up with a more sophisticated scheme that guarantees that that an object in D always gets the same spot in B. So I can think of several options, but I'm wondering what people typically do. I imagine almost everyone has to solve this problem at some point."} {"_id": 1, "text": "Slick2D shader crashes, but only after a while I'm using Slick2D's ShaderProgram for shader based drawing in my game. Some players report that after 3 10 minutes, the game inevitably crashes hard during what appears to be a setUniform4f operation that's happened thousands of times before error occurred during error reporting (printing native stack), id 0xc0000005 Java frames (J compiled Java code, j interpreted, Vv VM code) J org.lwjgl.opengl.ARBShaderObjects.nglUniform4fARB(IFFFFJ)V J com.zarkonnen.airships.Appearance.draw(Lcom zarkonnen catengine Draw DDDDILcom zarkonnen catengine util Clr Z)V Full Log Why might this happen? Is it a transient problem, or maybe a driver issue? I'm confused that this happens not when the shader is bound, or when textures are set, but at the point of this utterly mundane operation of setting a 4f value. I'm in fact pretty lost here, as I can't even repro this on any of my own machines. This is the culprit function in its entirety public void draw(Draw d, double x, double y, double w, double h, int ms, Clr tint, boolean flipped) if (shaderLoadFailed) drawFallback(d, x, y, w, h, ms, tint, flipped) return if (tex null) tex loadTex(SPRITESHEET) if (tex null) shaderLoadFailed true if (sp null) try sp ShaderProgram.loadProgram( AGame.getGameDirectoryPath(\"data passthrough.vert\"), AGame.getGameDirectoryPath(\"data frag.frag\")) catch (Exception e) e.printStackTrace() shaderLoadFailed true if (shaderLoadFailed) return sp.bind() glActiveTexture(GL TEXTURE0) glBindTexture(GL11.GL TEXTURE 2D, tex.getTextureID()) sp.setUniform1i(\"tex\", 0) if (tint null) sp.setUniform4f(\"tint\", 1.0f, 1.0f, 1.0f, 1.0f) else sp.setUniform4f(\"tint\", tint.r 255.0f, tint.g 255.0f, tint.b 255.0f, 1.0f) Img img frames.get((ms interval) frames.size()) glBegin(GL QUADS) if (flipped isFlipped) glTexCoord2d(img.srcX, img.srcY) glVertex2d(x w, y) glTexCoord2d(img.srcX, img.srcY img.srcHeight) glVertex2d(x w, y h) glTexCoord2d(img.srcX img.srcWidth, img.srcY img.srcHeight) glVertex2d(x, y h) glTexCoord2d(img.srcX img.srcWidth, img.srcY) glVertex2d(x, y) else glTexCoord2d(img.srcX, img.srcY) glVertex2d(x, y) glTexCoord2d(img.srcX, img.srcY img.srcHeight) glVertex2d(x, y h) glTexCoord2d(img.srcX img.srcWidth, img.srcY img.srcHeight) glVertex2d(x w, y h) glTexCoord2d(img.srcX img.srcWidth, img.srcY) glVertex2d(x w, y) glEnd() sp.unbind() TextureImpl.bindNone() And the shaders FWIW passthrough.vert void main() gl TexCoord 0 gl MultiTexCoord0 gl Position gl ModelViewProjectionMatrix gl Vertex frag.frag uniform sampler2D tex uniform vec4 tint void main(void) gl FragColor texture2D(tex, floor(gl TexCoord 0 .st) 1024.0) tint As you can see, there's very little to them."} {"_id": 2, "text": "Calling function every n second javascript game I making a game and I want to call a function that runs every random second to spawn something every time. I've seen some posts that said to use the setInterval() function to keep track of the time but I don't know where to implement it because I'm using the requestAnimationFrame() to loop the game. I also tried to implement it in the update function of the classes but it doesn't seem to work. This is my main with the loop import Game from ' src game.js' let canvas document.getElementById('main') let ctx canvas.getContext('2d') const WIDTH SCREEN 800 const HEIGTH SCREEN 600 let game new Game(WIDTH SCREEN, HEIGTH SCREEN) game.start() function loop() ctx.clearRect(0, 0, WIDTH SCREEN, HEIGTH SCREEN) game.update(ctx) requestAnimationFrame(loop) window.addEventListener( quot keydown quot , (event) gt game.controller.keyListener(event)) window.addEventListener( quot keyup quot , (event) gt game.controller.keyListener(event)) requestAnimationFrame(loop)"} {"_id": 2, "text": "How to post player s score on Facebook (with js) I have my game made with Phaser (and compiled with cocoon.io) and on the leadersboard state I want to let the user to post his score on Facebook. Well, I created an App on Facebook and I m not finding a good solution to create this simple post, something like \"I scored 10 points on this riduculous game...\" Pretty easy on Twitter and not so easy on Facebook, I can find information about posting links and that stuff but I m not finding a proper way to create a simple post just with text. How do you guys do this? I guess I m missing something, it shouldn t be so complicated. (I already tested this link and it s not working for me Simple way to post score from my game to Facebook and Twitter? API Error Code 191 API Error Description The specified URL is not owned by the application Error Message redirect uri is not owned by the application.)"} {"_id": 2, "text": "Map scrolling around the world I am developing an TBS (turn based strategy) game. I have created a simple canvas renderer to render hexagonial map. I already implemented scrolling on the map. My current problem is that I want to make it like in the civilizations games that you can scroll around the world. But I am kind of stuck on how to implement that. I had the idea of checking if a tile was rendered and if there is still space to the left render next sibling and so on, but this would turn out into long loops. My map array (2d) holds all the tiles and every tile has a member which holds all the siblings. How would you solve this? This is a screenshot from the example. You can check it out on http civ.minerjs.com. The code is also available to browse on the site using developer tools. Thanks for reading!"} {"_id": 2, "text": "I keep coming across an error \"Cannot read property 'innerHTML' of undefined\" I'm new to game designing and have to create a game for my project but I keep coming across an error to do with index.html 93 Uncaught TypeError Cannot read property 'innerHTML' of undefined at drawMissiles (index.html 93) at gameLoop (index.html 140) Any idea how to fix this problem? drawMissiles() function drawMissiles() document.getElementsByTagName('missile') 0 .innerHTML lt (index.html 93) for(var i 0 i lt missiles.length i ) document.getElementById('missile').innerHTML lt div class 'missile1' style 'left missiles i .left px top missiles i .top px' gt lt div gt"} {"_id": 2, "text": "2d grappling hook for platformer? What are the options and mechanics for creating a grappling hook in a 2D game? In the prototype for this feature, the person runs around in a platformer world and can throw the hook at any wall, where it sticks and shows a line to the player sprite. So that part (the easy part) is solved. But what options are available now for getting a rather good looking (not necessarily \"correct\") Tarzan style grappling hook going, e.g. one allowing some kind of neat looking swings? (I understand several different approaches of how the mechanics could work are available I'm looking for a simple one that may make some compromises and not be entirely physical, e.g. perhaps something which attracts the player to the hook center for a while or so while keeping to a certain rope min distance or such.) I'm using JavaScript ImpactJS, by the way. Thanks!"} {"_id": 2, "text": "PHP and Javascript HTML5 Collaboration I've recently been working on a fairly complicated game. I've stored information with local storage, but that allows the player to edit it, and does not transfer from computer to computer. The two scripts run on a single server, and I use the following to ping the php server function initiateLoginSequence() var isnewplayer prompt(\"Hello! Are you new?(Y N)\") if(isnewplayer.equalsIgnoreCase(\"N\")) var username prompt(\"Enter username.\") var password prompt(\"Enter Password.\") parsing code goes here later. else var username prompt(\"Enter a username. This will be used for future logins.\") var password prompt(\"Enter a password. This will be used for future logins.\",\" \") var req new XMLHttpRequest() req.open('POST', 'http 69.144.34.106 Scores.php', true) req.send(\"returning false\" \" amp name \" username \" amp pw \" password \" amp level \" lvl \" amp save true\") req.send() I then process the results with this lt ?php returning POST \"returning\" save POST \"save\" password POST \"pw\" username POST \"name\" score POST \"lvl\" connection mysql connect(\"localhost 3306\",\" \",\" \") if( returning \"false\" amp amp save \"true\") mysql select db(\"userdata\", connection) sqlcmd \"CREATE TABLE \". username.\"( Username varchar(\". username.\") Password varchar(\". password.\") Score varchar(\". score.\") )\" mysql query( sqlcmd) else if( save false) sqlcmd \"SELECT FROM userdata\" result mysql query( sqlcmd) while( row mysql fetch array( result)) if( row 'Username' username amp amp row 'Password' ) echo row 'Score' else if( save true) sqlcmd \"SELECT FROM userdata\" result mysql query( sqlcmd) while( row mysql fetch array( result)) row 'Username' username row 'Password' Password row 'Score' Score ? gt But after creating the mysql database, nothing is populated. So my basic question is, Am I doing this right? If not, what am I missing?"} {"_id": 2, "text": "Javascript game to Phonegap for android game? me and a friend of mine are in the process of building a javascrip HTML5 game and I'm running into a few questions about the process of using converting it to an android game. I plan on using Phone gap as it appears to be fairly simple and does what I'm looking for it to do. I've done a little research, but there is still a few questions I have about the whole process. Can I run the app offline? I want to be able to post the app to app store and allow people to download and play offline. Given the fact there will be no server requests can I make the game function offline? As I make the game for the computer I'm relying on the keyboard as input to move around. Obviously, once I port it to mobile this won't be practical. What is the easiest way to go about doing this? I'm considering simply changing the game to have a click on screen which moves the character to that location or even a simple movement pad in the corner of the screen. Would these on screen clicks change correctly over to mobile. Lastly, what is the easiest way to handle save data. On the computer side I plan to use HTML5 local storage to store game data. Does this convert to mobile or is there a better way? I appreciate any help in this matter."} {"_id": 2, "text": "Javascript create a new bullet instance every time a user event is triggered Basically I have a function that I need to create an object of every time the user presses space(event listeners not shown here). function arrow() this.x playerXPos 40 this.y playerYPos 40 this.init function() var arrowImg new Image() arrowImg.src \"arrow.png\" c.drawImage(arrowImg,this.x,this.y) this.x 10 if(this.x gt 500) keySpace false if(keySpace) arrowObj.init() This works great, but I can only have 1 arrow on the screen at once, which is rather limiting. Is there some way to create a new object every time the if statement is true, and store it in an array or something?"} {"_id": 2, "text": "User input in game loop I am building a simple multi player fly around a 3D world game in Javascript webGL websocket (Chrome, Firefox mostly). How should I handle and process user input? My preliminary design (untested) is to first just track which keys are down in the event handler var keys document.onkeydown document.onkeyup function(evt) keys evt.charCode evt.type \"keydown\" keys CTRL evt.ctrlKey keys SHIFT evt.shiftKey websock.send(JSON( time (new Date()).gettime(), down evt.type \"keydown\", key evt.charCode, shift evt.shiftKey, ctrl evt.ctrlKey )) and then, in my requestAnimationFrame callback, compute how many time slices (say 20 per second?) have elapsed since the last render callback, and then compute that many time steps using the booleans in the keys array to determine if to apply a left bank, right bank, up down and accelerate and so that time step for each player. How effective responsive is this? Is there a better way? And is there a neater way to deal with latency than just backdating changes for other user's ships?"} {"_id": 2, "text": "How to make Pong ai paddle? I'm trying to make an ai so the paddles will move to position before the ball reaches it. I'm not sure how to go about it in this case. Here's the game http cssdeck.com labs ping pong game tutorial with html5 canvas and sounds Function to increase speed after every 5 points function increaseSpd() if(points 4 0) if(Math.abs(ball.vx) lt 15) ball.vx (ball.vx lt 0) ? 1 1 ball.vy (ball.vy lt 0) ? 2 2 Track the position of mouse cursor function trackPosition(e) mouse.x e.pageX mouse.y e.pageY Function to update positions, score and everything. Basically, the main game logic is defined here function update() Update scores updateScore() Move the paddles on mouse move if(mouse.x amp amp mouse.y) for(var i 1 i lt paddles.length i ) p paddles i p.x mouse.x p.w 2 Move the ball ball.x ball.vx ball.y ball.vy Collision with paddles p1 paddles 1 p2 paddles 2 If the ball strikes with paddles, invert the y velocity vector of ball, increment the points, play the collision sound, save collision's position so that sparks can be emitted from that position, set the flag variable, and change the multiplier if(collides(ball, p1)) collideAction(ball, p1) else if(collides(ball, p2)) collideAction(ball, p2) else Collide with walls, If the ball hits the top bottom, walls, run gameOver() function if(ball.y ball.r gt H) ball.y H ball.r gameOver() else if(ball.y lt 0) ball.y ball.r gameOver() If ball strikes the vertical walls, invert the x velocity vector of ball if(ball.x ball.r gt W) ball.vx ball.vx ball.x W ball.r else if(ball.x ball.r lt 0) ball.vx ball.vx ball.x ball.r If flag is set, push the particles if(flag 1) for(var k 0 k lt particlesCount k ) particles.push(new createParticles(particlePos.x, particlePos.y, multiplier)) Emit particles sparks emitParticles() reset flag flag 0 Function to check collision between ball and one of the paddles function collides(b, p) if(b.x ball.r gt p.x amp amp b.x ball.r lt p.x p.w) if(b.y gt (p.y p.h) amp amp p.y gt 0) paddleHit 1 return true else if(b.y lt p.h amp amp p.y 0) paddleHit 2 return true else return false Do this when collides true function collideAction(ball, p) ball.vy ball.vy if(paddleHit 1) ball.y p.y p.h particlePos.y ball.y ball.r multiplier 1 else if(paddleHit 2) ball.y p.h ball.r particlePos.y ball.y ball.r multiplier 1 points increaseSpd() if(collision) if(points gt 0) collision.pause() collision.currentTime 0 collision.play() particlePos.x ball.x flag 1 Function for emitting particles function emitParticles() for(var j 0 j lt particles.length j ) par particles j ctx.beginPath() ctx.fillStyle \"white\" if (par.radius gt 0) ctx.arc(par.x, par.y, par.radius, 0, Math.PI 2, false) ctx.fill() par.x par.vx par.y par.vy Reduce radius so that the particles die after a few seconds par.radius Math.max(par.radius 0.05, 0.0)"} {"_id": 2, "text": "Javascript Isometric draw optimization I'm having trouble with isometric tiles drawing. At the moment I got an array with the tiles i want to draw. And it all works fine until i increase the size of the array. Since I draw ALL tiles on the map it really affects the game performance (obviously) D. My problem is I'm no genius when it comes to javascript and I haven't managed to just draw what is in viewport. Should be fairly simple for an expert though because its fixed sizes etc. Canvas is 960x480 pixels, each tile 64x32. This gives 16 tiles on first row, 15 on the next etc. for a total of 16 rows. Tile 0,0 is in the top right corner. And draws X up to down and Y right to left. Going through the tiles on the first row from left to right as X Y. Here is the relevant part of my drawMap() function drawMap() var tileW 64 Tile Width var tileH 32 Tile Height var mapX 960 32 var mapY 16 for(i 0 i lt map.length i ) for(j 0 j lt map i .length j ) var drawTile map i j var drawObj objectMap i j var xpos (i j) tileH mapX var ypos (i j) tileH 2 mapY Place the tiles isometric. ctx.drawImage(tileImg drawTile ,xpos,ypos) if(drawObj) ctx.drawImage(objectImg drawObj 1 ,xpos,ypos (objectImg drawObj 1 )) Could anyone please help me how to translate this to just draw the relevant tiles? It would be deeply appreciated."} {"_id": 2, "text": "I'm having very negative thoughts, can you help me? I'm 27 years old and I recently started vocational studies for app development. The first year is mostly about introduction to c programming and also a light introduction to html and javascript. I have never studied anything related to coding before. I know how to make pixel art , music and sounds, but coding is just so difficult for me. My objective in life right now is to make a very simple game and I feel so frustrated because I can't achieve anything. I have even tried things like stencyl or construct 2 but even that kind of software I can't understand it enough to make a very simple game. I'm breaking all the rules here, but, can you help me? I read about people that are like 2 months into coding and are already making games. Am I too dumb? Should I just quit altogether?"} {"_id": 2, "text": "How to draw the player standing behind a tree in an Entity Component System? I'm making a top down Javascript canvas game using the Entity Component System architecture. For an entity to be drawn on the screen every frame, it needs a PositionComponent and a SpriteComponent. The rendering system looks like this for (let entity of scene.query(CT.Sprite, CT.Position)) this.drawEntity(entity) This works well, but I'm not sure how to modify this to give the player the ability to hide behind objects. For example, in Stardew Valley, you can stand in front of, and behind, objects, as demonstrated in this screenshot https i.imgur.com B90jGS7.png How can this be implemented in an ECS? Because currently my rendering system just iterates through every object and draws them. Also, currently, for drawing the map (scenery and whatnot), it renders the map to a texture and then just redraws that single texture every frame (for performance reasons, instead of redrawing 10,000 tiles every frame). I'd imagine this makes it even more difficult to integrate. My assumption is that I have to take into account the entity's position in some way? That is, an entity with x 0, y 400 will be drawn before an entity with position x 0, y 500 , but I'm also unsure of how to integrate this with an ECS. Thanks for reading."} {"_id": 2, "text": "Why are not the images loaded in Phaser? I am starting to use phaser to create games and I found a problem that I can not find for more tests that I did. I can not show the images I am uploading. You only see a small square in the center, (I show it in this capture when you should see the entire background of the canvas in green, which is the image that first charge. In the example I only charge one, so that more if it does not work. I do not see what error I'm committing, because the navigator inspector does not show errors. The server is created with Node.js. const http require('http') const fs require('fs') const server http.createServer((req, res) gt fs.readFile(\". part1.html\", (err, data) gt if(err) console.error(err) return res.end(data) ) ) console.log('escuchando en el puerto 3000') server.listen(3000) I show the code for if someone can see the error that I am committing. Thank you. I EDIT the question I add the code that I should add first. The project is in a folder called Game. Here is the file server.js and package.json There is also a folder called public where the html code and images are located. I show you the code. lt !doctype html gt lt html lang \"es\" gt lt head gt lt meta charset \"UTF 8\" gt lt title gt Primer juego en Phaser lt title gt lt script src \" cdn.jsdelivr.net npm phaser 3.11.0 dist phaser.js\" gt lt script gt lt style type \"text css\" gt body margin 0 lt style gt lt head gt lt body gt lt script type \"text javascript\" gt var config type Phaser.AUTO, width 800, height 600, scene preload preload, create create, update update var game new Phaser.Game(config) function preload() this.load.image('sky', 'sky.png') this.load.image('sky', 'assets sky.png') this.load.image('ground', 'assets platform.png') this.load.image('star', 'assets star.png') this.load.image('bomb', 'assets bomb.png') this.load.spritesheet('dude', 'assets dude.png', frameWidth 32, frameHeight 48 ) function create() this.add.image(400, 300, 'sky') function update() lt script gt lt body gt lt html gt"} {"_id": 2, "text": "Tagging \"regions\" in rot.js map generator I'm working on a small roguelike and I'd like to be able to tag the various quot regions quot generated via the Map generators so that I can use it as a lookup to environment descriptions. I see that there are quot Rooms quot that are generated in the dungeon generator algorithms, however I didn't really see anything similar in say, the cellular automata generator. Is there a way to leverage the generator in rot.js, or am I stuck with manually determining if I'm in a particular open area (and breaking encapsulation of internal, private variables along the way)? Basically, I'd like to be able to link up my player's location to the text you see at the bottom of , but can't seem to figure out how to do it generically. I'm fairly certain I could use the 'Rooms' object in the first 2 screenshots, and everything else is a hallway, but I'm not clear on how I could get a particular 'region' in a cellular automata generator (or one of the maze generators, for instance)."} {"_id": 2, "text": "Click on an isometric plane and obtain normal coordinates I have photos distributed as cells. When I click, I get the corresponding row and column. console.log(\"Col \" X \"Row \" Y) When applying an isometric view conversion like this ctx.translate(0, 300) ctx.scale(1, 0.5) ctx.rotate( 45 Math.PI 180) I do not know what mathematical formula applies to get the coordinates correctly. Based on feedback so far, I've been able to get this far. The x coordinate seems to work fine, but the y coordinate not. Isometrico() function Isometrico() ctx.translate(0, 300) ctx.scale(1, 0.5) var radianes 45 Math.PI 180 ctx.rotate(radianes) document.addEventListener(\"mousedown\", function(e) CorIsometrico( e.offsetX, e.offsetY) ) function CorIsometrico(xI,yI) RESPUESTA yI yI 300 yI yI 2 xI xI Math.cos(45) yI Math.sin(45) I yI Math.sin(45) yI Math.cos(45) console.log(\"Coor Isometricas \" xI \" \" yI) Edit Each cell is 50x50. Having 10 columns and 50 rows, the information of each cell would look like this 1 50 50 2 100 50 3 150 50 ... 49 450 250 50 500 250 Maximum Y value 250. xI xI Math.cos(45 180 Math.PI) yI Math.sin(45 180 Math.PI) yI yI Math.sin(45 180 Math.PI) yI Math.cos(45 180 Math.PI) yI yI 2 yI yI 300 Click in X 1 Y 1 138.5929291125633 531.5575746753798 Click in X 1 Y 5 198.69700551341987 90.3229432149742 Y exceeds the maximum value. Edit2 var xI2 xIMath.cos(45 180 Math.PI) yIMath.sin(45 180 Math.PI) var yI2 xIMath.sin(45 180 Math.PI) yIMath.cos(45 180 Math.PI) yI2 yI 2 yI2 yI 300 xI2 xI2 150 console.log(\"Coor Isometricas \" xI2 \" \" yI2 ) x coor 100 to 400 px if x 150 y coor 0 to 155. Been thinking that the problem is not necessary on isometry. What I'm looking for can be simplified to get the coordinates of a 2d plane by having it rotated X degrees"} {"_id": 2, "text": "How can I clear explosions in my function? Hi I have a function to place bombs, and a for loop that places explosions on the tiles where possible. My problem is that I can't remove the explosions after a while. I've tried everything I can come up with so now I turn here as a last resort. The function looks like this function Bomb() var placebomb false if(placeBomb amp amp player.bombs ! 0) map player.Y player.X .object 2 var bombX player.X var bombY player.Y placeBomb false player.bombs setTimeout(explode, 3000) function explode() var explodeNorth true var explodeEast true var explodeSouth true var explodeWest true map bombY bombX .explosion 1 delete map bombY bombX .object for(i 0 i lt player.bombRadius i ) if(explodeNorth amp amp map bombY i bombX ) if(!map bombY i bombX .wall) if(!map bombY i bombX .object) map bombY i bombX .explosion 1 else var explodeNorth false delete map bombY i bombX .object map bombY i bombX .explosion 1 else var explodeNorth false if(explodeEast amp amp map bombY bombX i ) if(!map bombY bombX i .wall) if(!map bombY bombX i .object) map bombY bombX i .explosion 1 else var explodeEast false delete map bombY bombX i .object map bombY bombX i .explosion 1 else var explodeEast false if(explodeSouth amp amp map bombY i bombX ) if(!map bombY i bombX .wall) if(!map bombY i bombX .object) map bombY i bombX .explosion 1 else var explodeSouth false delete map bombY i bombX .object map bombY i bombX .explosion 1 else var explodeSouth false if(explodeWest amp amp map bombY bombX i ) if(!map bombY bombX i .wall) if(!map bombY bombX i .object) map bombY bombX i .explosion 1 else var explodeWest false delete map bombY bombX i .object map bombY bombX i .explosion 1 else var explodeWest false player.bombs If anyone can think of a good way to remove the explosion after a delay please help."} {"_id": 2, "text": "Implementing navigatable achievement menu in javascript I am in the process of learning javascript for game design, and wanted to make a separate achievement page that the user can navigate to that will allow them to check their achievements on various games. (at the moment I am not concerned with implementing localstorage cookies etc, I just want to work on the page for now) So the requirements of my base idea is as follows Able to drag around the viewport page to view all the achievement categories as they will likely not all be in view on smaller screens Able to click on a category to open a small box containing all achievements belonging to that game category Able to mouse over all achievements in the boxes to get text descriptions of what they are OPTIONAL have lines connecting each box on the \"overworld\" to show users where nearby boxes are if they are off screen At first, I thought I would need canvas to be able to do this. I learned a bit about it and got decently far until I realized that canvas has a lot of restrictions like not being able to do mouseover events unless manually implementing each one. Here is the current progress I was at in doing a test run of learning canvas, but it's not very far var canvas document.getElementById('canvas') var ctx canvas.getContext('2d') canvas.width window.innerWidth canvas.height window.innerHeight function resize() canvas.width window.innerWidth canvas.height window.innerHeight ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.translate(panning.offset.x, panning.offset.y) draw() window.addEventListener(\"resize\", resize) var global scale 1, offset x 0, y 0, , var panning start x null, y null, , offset x 0, y 0, , var canvasCenterWidth (canvas.width 2) var canvasCenterHeight (canvas.height 2) function draw() ctx.beginPath() ctx.rect(canvasCenterWidth, canvasCenterHeight, 100, 100) ctx.fillStyle 'blue' ctx.fill() ctx.beginPath() ctx.arc(350, 250, 50, 0, 2 Math.PI, false) ctx.fillStyle 'red' ctx.fill() draw() canvas.addEventListener(\"mousedown\", startPan) function pan() ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.translate(panning.offset.x, panning.offset.y) draw() function startPan(e) window.addEventListener(\"mousemove\", trackMouse) window.addEventListener(\"mousemove\", pan) window.addEventListener(\"mouseup\", endPan) panning.start.x e.clientX panning.start.y e.clientY function endPan(e) window.removeEventListener(\"mousemove\", trackMouse) window.removeEventListener(\"mousemove\", pan) window.removeEventListener(\"mouseup\", endPan) panning.start.x null panning.start.y null global.offset.x panning.offset.x global.offset.y panning.offset.y function trackMouse(e) var offsetX e.clientX panning.start.x var offsetY e.clientY panning.start.y panning.offset.x global.offset.x offsetX panning.offset.y global.offset.y offsetY body overflow hidden canvas top 0 left 0 position absolute lt canvas id \"canvas\" gt lt canvas gt So I guess my question is now what is the best way to implement this? Is it feasable to do it with canvas, or should I just scrap that and try to figure out something with div movement? Should I be concerned with performance issues and should that affect how I implement it?"} {"_id": 2, "text": "How to include a new file js in a project cocos2d js? I'm trying to include a new js file containing a new scene on a cocos2d js project, but every time try occurs the following error Uncaught ReferenceError GameScene is not defined. I included my file in jsList and in appList \"jsList\" \"src game scene.js\" , \"appFiles\" \"src game scene.js\" The code of my scene looks normal var GameScene cc.Scene.extend( onEnter function() this. super() var gameLayer new GameLayer() this.addChild(gameLayer) ) The code on app.js to call my scene looks good too var gameScene new GameScene() cc.Director.runScene(gameScene) What should I do?"} {"_id": 2, "text": "Is it possible to rotate an image on an HTML5 canvas, without rotating the whole canvas? So I basically want to rotate single sprites on the canvas without rotating the whole canvas, is that someway possible. I also don't want to create a new canvas for each object I have. Also, it would be interesting to know which solution is then the most performant."} {"_id": 2, "text": "How can I imitate interaction and movement in Diablo II? I'm prototyping a simple browser based game. It's played from a top down perspective on a 2d canvas. You left click on a point on the map, and your character will begin walking to it. If you click on a different point on the map, then your character will begin walking to the new point. It's similar to Diablo II. (a demonstration video) How can I best imitate this movement system for a player? Ideas... Track current coords and target coords If target coords are exactly up, left, right, or down, then increment appropriate direction until you get there Implied else target coords are in a quadrant. To make this movement look natural, character will have to move diagonally. For example, pretend the target is to the northeast. For each game frame, alternate incrementing current coordinates in the north and then east directions."} {"_id": 2, "text": "Capitalizing on JavaScript's prototypal inheritance JavaScript has a class free object system in which objects inherit properties directly from other objects. This is really powerful, but it is unfamiliar to classically trained programmers. If you attempt to apply classical design patterns directly to JavaScript, you will be frustrated. But if you learn to work with JavaScript's prototypal nature, your efforts will be rewarded. ... It is Lisp in C's clothing. Douglas Crockford What does this mean for a game developer working with canvas and HTML5? I've been looking over this question on useful design patterns in gaming, but prototypal inheritance is very different than classical inheritance, and there are surely differences in the best way to apply some of these common patterns. For example, classical inheritance allows us to create a moveableEntity class, and extend that with any classes that move in our game world (player, monster, bullet, etc.). Sure, you can strongarm JavaScript to work that way, but in doing so, you are kind of fighting against its nature. Is there a better approach to this sort of problem when we have prototypal inheritance at our fingertips?"} {"_id": 2, "text": "How do I fix these touch events? Events respond if there are 2 fingers but not 1 I am making a simple game of mine mobile friendly. The goal is to Make character walk if a touchstart event is sensed on right half of screen. Stop character if a touchend event is sensed on the right half. Jump the character if a touchend event happens on the left half of the screen. I have the logic working perfectly for mouse up and down events so I'm pretty sure it's something to do inside the touchstart and end functions. If two fingers are used as one press it seems to work fine. If only one finger is used it doesn't work properly touching anywhere starts the movement but nothing will stop it. Here is the code for the touch inputs and associated function CheckWhichScreenHalf function(e) loc WindowToCanvas(e.pageX, e.pageY) onScreenY loc.y gt 0 amp amp loc.y lt gameCanvas.height leftSideX loc.x gt 0 amp amp loc.x lt gameCanvas.width 2 rightSideX loc.x gt gameCanvas.width 2 amp amp loc.x lt gameCanvas.width if (onScreenY amp amp leftSideX) return 'left' else if (onScreenY amp amp rightSideX) return 'right' else return 'neither' TouchMove false TouchJump false gameCanvas.ontouchstart function(e) if (imagesHaveBeenLoaded) e.preventDefault() for (var i 0 i lt e.touches.length i ) var side CheckWhichScreenHalf(e.touches.item(i)) if (side 'right') TouchMove true gameCanvas.ontouchend function(e) if (imagesHaveBeenLoaded) e.preventDefault() for (var i 0 i lt e.touches.length i ) var side CheckWhichScreenHalf(e.touches.item(i)) if (side 'right') TouchMove false else if (side 'left') playerJumping true The game can be played here http webstudentwork.com jgossling MMWD mp2 mp2.html"} {"_id": 2, "text": "Y and X Am I doing it wrong? I sometimes run into small issues when doing my JavaScript projects. That is because most build in functions of JavaScript run X,Y if positions are needed. (In that order). But when I build a 2D Array I start out with Y, it seems more logical for me to to run the X axis horizontal. If I am bad at explaining it, let me show you So my loops look like this for(var y 0 y lt 10 y ) for(var x 0 x lt 10 x ) console.log(\"Doh!\") Is this so insane? I would like to convert to the normal practise so that I have an easier time while building my game and don't have to do constant switcherroos. So why is it X before Y ? Edit Here is another example, and probably the main reason for my confusion X is Horizontal, and Y is Vertical in my books.. 0,1,2,3,4 , 0,1,2,3,4 , 0,1,2,3,4 , 0,1,2,3,4 ,"} {"_id": 2, "text": "Planck.js (rewritten of Box2D.js) 8 direction box movement I have a box in Planck.js. I want to move this box with some keys. How can I do that? My code planck.testbed(\"boxworld\", function(testbed) var pl planck, Vec2 pl.Vec2 var world new pl.World(Vec2(0, 0)) Box var box world .createDynamicBody(Vec2(0.0, 10.0)) .createFixture(pl.Box(0.5, 0.5), 20.0) box.render fill \" FA8072\", stroke \"black\" return world )"} {"_id": 2, "text": "Javascript 2D game tile textures I am using a texture atlas for my tiles. Of course I need to get the sub images to draw them on the canvas as separate tiles. Right now I can think of two ways to implement this. Divide the texture atlas into separate Image instances. Then draw them onto the canvas accordingly. Use a single image, and just draw part of it by adding extra parameters to CanvasRenderingContext2D's method drawImage. I'm not sure which is better. My thoughts were that the first option would be more manageable and flexible, since each tile is separated. What would be better? What are the ups and downs of each?"} {"_id": 2, "text": "Anti cheat Javascript for browser HTML5 game I'm planning on venturing on making a single player action rpg in js html5, and I'd like to prevent cheating. I don't need 100 protection, since it's not going to be a multiplayer game, but I want some level of protection. So what strategies you suggest beyond minify and obfuscation? I wouldn't bother to make some server side simple checking, but I don't want to go the Diablo 3 path keeping all my game state changes on the server side. Since it's going to be a rpg of sorts I came up with the idea of making a stats inspector that checks abrupt changes in their values, but I'm not sure how it consistent and trusty it can be. What about variables and functions escopes? Working on smaller escopes whenever possible is safer, but it's worth the effort? Is there anyway for the javascript to self inspect it's text, like in a checksum? There are browser specific solutions? I wouldn't bother to restrain it for Chrome only in the early builds."} {"_id": 2, "text": "Behaviour of containers in Phaser 3 framework I don't understand the behaviour of containers in this example Phaser example The part I don't unerstand is line 41. Why is lastContainer assigned to newContainer? In line 40, newContainer is added as a child of lastContainer my intuition would be that the effect of line 40 is so that the rotations can be performed on lastContainer (or, rather, on containerTails, which seems to contain four nested container structures, one for each arm), and propagated to its children. It makes no sense to me that the variable containing the parent container should be assigned to its own child how does that not overwrite the nested structure of containers, effectively removing the parent container from the picture?"} {"_id": 2, "text": "How do I change the level of my game by changing the file loaded? I am making this 2d canvas game in JavaScript and I want to switch to file level2 level2.html when the boss of level 1 (level1 level1.html) is dead. This way I can have my stuff organized better. This is the condition statement where I want to put the file change. if(e.bosshealth lt 0) enemies alert(\"LEVEL 1 COMPLETED\") I want the file switch to be here if possible."} {"_id": 2, "text": "How to get projectile direction vector in a 2d grid? I am having trouble figuring out how to trace the path of my projectiles in an Asteroids clone. Currently the ship is locked to the center of the screen and can be rotated a full 360 degrees. I know the angle the ship is pointing at any given time, but I am not sure how to calculate the vector that the projectile should use for its trajectory. I know that I can find the correct vector by subtracting the end point from the start point.. but the issue is that I do not know the end point. Theoretically.. the end point is whenever the projectile touches the edge of the screen or some object. This is the current game code https jsfiddle.net m6sxrk8w just using a hardcoded movement vector of x 1, y 1 . Can anyone give some advice on how to dynamically determine the true vector given the current direction of the ship? There must be some simple math I am missing here..."} {"_id": 2, "text": "Experience embedding javascript I'm looking into scripting languages to embed in my game. I've always assumed Lua was the best choice, but I've read some recent news about embedding V8 as was considering using it instead. My question is two fold Does anyone with experience embedding v8 (or another javascript engine) recommend it? How does it compare with embedding Lua? I like that v8 has a c embedding API. However Lua API has had lots of time to be refined (newer isn't always better and all that). Note At this point I'm not too concerned with which is better language or which library has better performance. I'm only asking about ease of embedding."} {"_id": 2, "text": "DOM for GUI display animated objects I'm creating an HTML5 game using Canvas, but want to use DOM for the GUI for the reasons mentioned in there articles http blog.sklambert.com html5 game tutorial game ui canvas vs dom http www.html5gamedevs.com topic 29569 how do you guys build your ui http www.html5gamedevs.com topic 802 gui methodologies That being said, we have a component on the GUI that needs to be animated which will be through a sprite. Is it possible to render sprite animations through a DOM element?"} {"_id": 2, "text": "TypeError R o5R.F6s is not a function in changing states in phaser box2d i build my game using phaser.2.4.3.min.js and phaser.2.2.2.box2d.min.js When trying to change states this error is being raised TypeError R o5R.F6s is not a function and i can't seem to figure out the problem PS i took The source code of box2d plugin from the example folder in phaser , and i did not purchase the full plugin yet i was just testing it . is there anyway to fix this issue ? here is the game code http jsfiddle.net fbdtq1tg 5 and here where the error is raised SetGameOver function () this.game.state.start(\"TheGame\")"} {"_id": 2, "text": "p2.js body position is NaN when spawned inside of each other I'm working on a project for which I need a physics engine. At the moment I'm playing around with p2.js but I'm running into a problem When I try to create multiple bodies (circles and or boxes) which overlap the positions are set to NaN as soon as world.step() is called. The bodies have a mass of 5 and are dynamic. In very rare occasions it does actually work. How can I make sure it works every time? Do I have to wait for the bodies to be initialized? 4 circles before the simulation starts, once world.step is called the positions of these circles is NaN var world new p2.World( gravity 0, 9.82 ) function PhysicsBody(type, x, y, widthOrRadius, height) this.body new p2.Body( mass 5, position x, y , ) this.type type if (this.type 'rectangle') this.shape new p2.Box( width widthOrRadius, height height ) else if (this.type 'circle') this.shape new p2.Circle( radius widthOrRadius ) this.body.addShape(this.shape) world.addBody(this.body) var bod1 new PhysicsBody('circle', 0, 0, 32) var bod2 new PhysicsBody('circle', 10, 0, 32)"} {"_id": 2, "text": "How to implement map scrolling inertia formulae I'm looking for a mathematical formulae to calculate map scrolling inertia. Basically I have an HTML5 Canvas displaying part of a map and I capture the mousedown mousemove mouseup to calculate my new offset. And when I scroll the map I want the map to continue scrolling for a few moments after the user stopped dragging the cursor. I do have a sample implementation but I'm not really satisfied with it. I'd be looking for a nice clean math formulae to achieve this. I'd like my map to behave for example like in Civ 5 when you scroll the map around. Here is part of my implementation (working jsfiddle https jsfiddle.net CowWarrior dkxnj5d8 1 ) mouseup stopMapDrag function (e) var movementX (e.pageX this.startX) var movementY (e.pageY this.startY) this.mapOffsetX parseInt(this.mapOffsetX) movementX this.mapOffsetY parseInt(this.mapOffsetY) movementY this.isDragging false this.displayMap() calculate last vector ui.vectorX parseInt(e.pageX ui.absStartX) ui.vectorY parseInt(e.pageY ui.absStartY) show inertia setTimeout(function() ui.dragInertia(2) , 30) console.log(\"(vectorX \" ui.vectorX \", vectorY \" ui.vectorY \")\") (' canViewport').css('cursor', 'default') , need to find a good formulae for inertia dragInertia function (factor) var movementX parseInt(ui.vectorX factor) var movementY parseInt(ui.vectorY factor) ui.mapOffsetX parseInt(ui.mapOffsetX movementX) ui.mapOffsetY parseInt(ui.mapOffsetY movementY) ui.displayMap() if (factor lt 8) setTimeout(function() ui.dragInertia(factor 1.2) , 30) ,"} {"_id": 2, "text": "How do I make an entity move once per second in crafty.js I am trying to implement \"Snake\" using crafty.js but I can't seem to get the snake entity to move just once in a second. How do I do this?"} {"_id": 2, "text": "Unity 5 Animation attaching I have created the walking and idle animation for my fps player. I've added a JavaScript script to access it, but when I run it and press button(w), it stops and says that the animation is not attached to the object. When I drag the walking idle animation and drop to that object, it creates an animation controller. Again I run it, still same error. I can't find where to attach the animation Here's my script function Update () if(Input.GetKeyDown(\"w\")) GetComponent. lt Animation gt ().Play(\"walk anim2\", PlayMode.StopAll) if(Input.GetKeyUp(\"w\")) GetComponent. lt Animation gt ().Play(\"idle anim2\", PlayMode.StopAll) Where do I need to attach the animation?"} {"_id": 2, "text": "Canvas slowly degrades in performance after a while I was creating a simple game and was shocked to see how the performance started to degrade. It never happened to me before, most probably because I use images and not the context drawings. So I used this function and the whole game becomes so slow, it just cannot be played after 30 seconds. Office.prototype.draw function() for(var i 0 i lt this.tables.length i ) for(var j 0 j lt this.tables i .length j ) Canvas2D.ctx.rect((373 j) 75, (370 i) 250, 170, 20) Canvas2D.ctx.fillStyle 'green' Canvas2D.ctx.fillRect((373 j) 75, (370 i) 250, this.moneyBar (i 4) j , 20) Draw the experience bar. Canvas2D.ctx.rect((373 j) 75, (370 i) 270, 170, 20) Canvas2D.ctx.fillStyle 'yellow' Canvas2D.ctx.fillRect((373 j) 75, (370 i) 270, this.expBar (i 4) j , 20) Draw the tables. Canvas2D.drawImage(sprites.items 0 , new Vector2( (250 j) 50, (250 i) 200)) So as you can tell from the code, there is the multidimensional array table which has bars on top displaying moneyBar and expBar. If I am to use Canvas2D.ctx.stroke() inside the for loop, the game performance drops right away. Outside of the loop, it keeps up a bit, then it degrades. If I don't use stroke at all, works better, but degrades anyway. So I am really confused as to why this degrades so fast. Also am using requestAnimationFrame and have used the same engine in previous games and performance never degraded. If I was to remove fillStyle, keeps up 3 4 seconds more. There are 8 tables in all, which means the for loops run 8 times per draw. Vector2 function. function Vector2(x, y) this.x typeof x ! 'undefined' ? x 0 this.y typeof y ! 'undefined' ? y 0"} {"_id": 2, "text": "Approaches for storing grid like information I am drawing this simple grid on my NodeJS server var grid for(var x 0 x lt 20 x ) grid x for(var y 0 y lt 20 y ) grid x y 0 console.log(grid) The outcome looks like this I know, pretty right?! 0 is supposed to indicate FREE, thus if a player requests to move to a field with 0, he will! The problems come when I want to add more then just Free Occupied, for instance I would like to give each Array Element an ID number for the Client Updates, or certain features on the field to be stored. I tried to assign something N, something2 N But thought it looked rather performance expensive in the long run. (On a big Grid) I read about using a single Object for several elements, but I cannot find this any more.. Should I perhaps use an Array of Objects, or an Additional Array inside each X,Y element? Any performance convenience anything goes tips are welcome D Edit Thank you for the ideas so far, I was now thinking to perhaps using Strings. Storing Variable A \",\" Variable B and then later using the .split to use the information. Any thoughts on this?"} {"_id": 2, "text": "Good practices when optimizing HTML5 Javascript Game Developement I'm just starting out as a game developer and have created a few crappy but playable clones of classic games like pong, and bomberman. Being self taught (bless the internet) I do this by just stuffing in code to make the games work. Now I feel the time has come to create something complete, for this I need to know how a game is structured. I've searched on the web but there isn't that much to be found. The only \"high level\" language I know is javascript so reading a tutorial or article based on C doesn't help me that much. I'm looking for good resource's pedagogically covering the theory and possibly examples (in Javascript or pseudo code that is understandable for a beginner) of how the game pieces fit together. From the start screen to asset loading and running the game loop. I'm not looking for anything complicated like reading through a 4000 line source code. All I want to learn is where, how and when the main parts of every game should be called. If you know any good resources to share, or maybe even have an answer for me I would deeply appreciate it."} {"_id": 2, "text": "Make a variable go down as another goes up? I am making a JavaScript game called \"Spoop The Clicker\", and I have a variable shown by text stroke(\"blue\") fill(\"purple\") textSize(30) text(\"Spoop Cash \" spoopCash, 130, 10) This is inside the draw loop, as it is always shown. The thing is, I need textSize to be set shrink as my other variable spoopCash increases. How could I do that? If you can, please include a way to stop it from going too small (such as size 10 being the smallest allowed.)"} {"_id": 2, "text": "Mouse position to grid position not working I have a function which converts my mouse position to grid position in the game but it is not working properly... its slightly off. I have two functions one which converts from grid to screen position (this particular one, works fine) and the code is function mapToScreen(gridX,gridY,screen) var grid 64 var x (gridX gridY) (grid 2) x screen.offsetX camera scroll offset X axis x grid 2 centre of the iso tile on X axis var y (gridX gridY) (grid 4) y screen.offsetY camera scroll offset Y axis y grid 4 centre of the iso tile on Y axis return x,y So my function to do the opposite looks like this function screenToMap(pixelX,pixelY,screen) var grid 64 pixelX screen.offsetX pixelX grid 2 pixelY screen.offsetY pixelY grid 4 var gridX Math.floor((pixelX (grid 2) pixelY (grid 4)) 2) var gridY Math.floor((pixelY (grid 4) (pixelX (grid 2))) 2) return gridX, gridY The problem is as shown below in the image, it doesn't return the correct number. The first corner tile should be 0,0 . Also notice the co ordinate doesn't change correctly with the tile border. I don't know how to solve that either."} {"_id": 2, "text": "How to get the Javascript equivalent of GameMaker's hspeed and vspeed given only direction and speed ? I'm using a NodeJS server to control NPC movement in a multiplayer game, and when they get too close to the edge of the room I need to reverse either the horizontal or vertical components of their velocities (how to decide which, is a bridge I'll cross when I get there). The problem is I already have their direction and speed, and am able to convert it to hspeed and vspeed, but not back again. I need the inverse of this function function velocityToSpeeds(direction, speed) return x speed Math.sin(Math.toRad(direction 90)), y speed Math.cos(Math.toRad(direction 90))"} {"_id": 2, "text": "how can i make an object in a canvas always look at the mouse cursor this is my code var myGamePiece function startGame() myGamePiece new component(30, 30, \"red\", 10, 120) myGameArea.start() var myGameArea canvas document.createElement(\"canvas\") start function() this.canvas.width 480 this.canvas.height 270 this.context this.canvas.getContext(\"2d\") document.body.insertBefore(this.canvas, document.body.childNodes 0 ) this.interval setInterval(updateGameArea, 20) window.addEventListener('keydown', function (e) myGameArea.keys (myGameArea.keys ) myGameArea.keys e.keyCode (e.type \"keydown\") ) window.addEventListener('keyup', function (e) myGameArea.keys e.keyCode (e.type \"keydown\") ) , clear function() this.context.clearRect(0, 0, this.canvas.width, this.canvas.height) function component(width, height, color, x, y) this.gamearea myGameArea this.width width this.height height this.speedX 0 this.speedY 0 this.x x this.y y this.update function() ctx myGameArea.context ctx.fillStyle color ctx.fillRect(this.x, this.y, this.width, this.height) this.newPos function() this.x this.speedX this.y this.speedY function updateGameArea() myGameArea.clear() myGamePiece.speedX 0 myGamePiece.speedY 0 if (myGameArea.keys amp amp myGameArea.keys 37 ) myGamePiece.speedX 5 if (myGameArea.keys amp amp myGameArea.keys 39 ) myGamePiece.speedX 5 if (myGameArea.keys amp amp myGameArea.keys 38 ) myGamePiece.speedY 5 if (myGameArea.keys amp amp myGameArea.keys 40 ) myGamePiece.speedY 5 if (myGamePiece lt 299) myGamePiece.speedX 5 myGamePiece.newPos() myGamePiece.update() I want myGamePiece to look exactly were the mouse cursor is looking. How can I do this?"} {"_id": 2, "text": "Top down four directional movement snap to tiles, not feel like crap I want to make a topdown rpg movement, I need to update these parameters based on user input User input four directions . Update parameters Position x, y, Flip sprite flipx, flipy, Sprite number s, eg 1 for horizontal sprite, 17 for vertical sprite Sprite Animation si, eg 1 to 4 for walking animation This is my crappy implementation function init() p t 0, x 0, y 0, dx 0, dy 0, mtimer 0, s 1, si 0, flipx false, flipy false end function update() local input x 0 local input y 0 if btnp( ) then input y 1 elseif btnp( ) then input y 1 end if btnp( ) then input x 1 elseif btnp( ) then input x 1 end if p.dx 0 and p.dy 0 then if input x ! 0 then p.dx input x p.mtimer 4 elseif input y ! 0 then p.dy input y p.mtimer 4 end end if p.mtimer gt 0 then p.mtimer 1 p.t 2 p.x p.dx 2 p.y p.dy 2 if p.mtimer 0 then p.dx 0 p.dy 0 end end p.t 0.5 if p.dx ! 0 then p.s 1 elseif p.dy ! 0 then p.s 17 end p.flipx p.dx 0 and p.flipx or p.dx lt 0 p.flipy p.dy 0 and p.flipy or p.dy lt 0 p.si flr(p.t 30 30 4) end function draw() spr(p.s p.si, p.x, p.y, 1,1, p.flipx, p.flipy) end This is the end result As you can see it's so bad looking, I want you to implement this movement so it's fun and juicy. Or what can I do to improve the looks and feel of this."} {"_id": 2, "text": "Why can't i change the background color in Phaser? what is wrong with my code? i'm using game.stage.backgroundColor but the screen remains black. main.js var demo demo demo.game new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '') demo.game.state.add('state1', demo.state1) demo.game.state.add('state2', demo.state2) demo.game.state.start('state1') state1.js var demo demo demo.state1 function() demo.state1.prototype preload function() , create function() game.stage.backgroundColor \" 4488AA\" , update function()"} {"_id": 2, "text": "How to make an infinite map I was wondering if someone could explain to me how to implement a seemingly dynamic infinite map like the one at http wordsquared.com My main issue is really generating new tiles in any direction when the user drag the board. I'm also trying to figure out how to handle the coordinate system, and actually what how to store the map in a database."} {"_id": 2, "text": "How to access files in Chrome So, I am making a game like html file that needs to load a few assets. I have a loading animation which uses the timing of the loading files to create a progress bar. This all goes fine. The files all load, and the app launches. However, none of the files can access each other as they are all in different script tags. And I cannot merge them because the JS is never actually put into the html. So what I need to do is to access the local file system (it uses the file prototype) and read the file, then stick the text into a script tag. However, all of the examples I have found on the web throw this error Xhtmlrequests can only access (list of protocols not including file) What I need is a JS way to access the files with no input from the user (other than opening the application). How can this be done?"} {"_id": 2, "text": "Creating an Array of 1s and 0s (with all 1s touching) I am a novice programmer trying to add an unnecessary and complicated element to a text adventure! ...and I've run into a question I am not sure how to research further (I suspect due to lack knowledge of the proper terminology). I am working on a small text adventure that uses an 11x11 array. Player is capable of moving into spaces with a 1 and incapable of moving to a 0. I need to a) retain the outer boundary 0s, b) randomize the content inside the border, and c) ensure that there is a linked path of 1s that will eventually connect to a 2 (the exit) 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 1 1 1 1 1 1 1 0 0 1 1 0 1 0 1 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 1 1 1 1 0 1 1 1 2 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I'd appreciate any pointers here not sure what direction I should be looking in. Thinking of scrapping this feature so if it's not viable I don't mind hearing that ) Thanks for reading."} {"_id": 2, "text": "Three.js camera turning leftside right In Three.js I am trying to implement an orbiting camera can be rotated around the x and the y axis. I am using these two functions function rotateX(rot) var x camera.position.x, y camera.position.y, z camera.position.z camera.position.x x Math.cos(rot) z Math.sin(rot) camera.position.z z Math.cos(rot) x Math.sin(rot) camera.lookAt(scene.position) function rotateY(rot) var x camera.position.x, y camera.position.y, z camera.position.z camera.position.z z Math.cos(rot) y Math.sin(rot) camera.position.y y Math.cos(rot) z Math.sin(rot) camera.lookAt(scene.position) Now the x rotation works fine but the y rotation does not. Once I go over the top of the model as in that the camera's z position becomes negative then suddenly the lookAt method rotates the camera by PI amount on the Z axis and suddenly the left side of the model is on the right and vice versa. Now I can fix this by checking for a negative Z and then just fixing the camera's rotation but this then causes a malfunction when using x ad y rotation at the same time, the x then suddenly gets this inverting behavior. How should I go about fixing this?"} {"_id": 3, "text": "How to make my model's top section rotate without rotating the entire model? I'm trying to learn a bit of Maya modeling so that I can be self sufficient when it comes to creating super basic assets for my game development. I'm trying to understand skeletal rigging and how it modifies the model geometry itself. I've got the most basic model a cube with proportions that make it into a 3D rectangle. I've rigged it with a very simplistic skeleton. My goal is to learn how all of this works, and create a character that has motion similar to maybe the magic carpet from Aladdin it's a rectangle but the edges somewhat move like it has arms and legs. When I rotate some joints, it distorts the entire model. I added a bit more geometry thinking that it'd allow the top section of my model to rotate a bit more without having to deform the entire model, but it still just seems to do the same thing. How can I make the top section of my model be capable of moving forward and backward in such a way that it does not cause the entire model to move forward? Here are some screenshots to help explain and show my situation ... This is my model and skeleton (I told you it was super basic, lol) ... And here is what happens when I rotate around the neck joint ... And here is sort of what I was hoping to achieve ..."} {"_id": 3, "text": "How to flip sprite and all collision children of a KinematicBody2D at the same time? I have tried to use the scale property of KinematicBody2D to flip at the same time the sprite and the collision area raycast children. For flipping, one just has to set scale.x 1. If it works in the editor, it does not work properly because the engine seems to reset scale.x to 1 each frame (as stated here) NB Here the original sprite is looking left (that is why it is blinking when going to the right, not very didactic sorry). How to do the same without flipping every collision children one by one?"} {"_id": 3, "text": "HTML5 Canvas Tileset Animation How to do in HTML5 canvas Image animating? I am have this code now http jsfiddle.net WnjB6 1 In here I am can add animations something like Animation.add('stand', 0, 1, 2, 3, 4, 5 ) But how to play this animation? My image drawing function is drawTile(canvasX, canvasY, tile, tileWidth, tileHeight) Animation 'stand' return 0, 1, 2, 3, 4, 5 I am need something like when I am run Animation.play('stand') run animation from 'stand' array. I am try to do this something like one day, but no have more idea how. ( Thanks and sorry for my bad English language."} {"_id": 3, "text": "Turn based game in HTML JS CSS new joiner messes with state of game while animations are still running for other players I developed a playing cards web app using HTML JS CSS. Communication with the server is performed using WebSocket. The server is developed in Java Spring. The game proposes to join one of the many available tables where you can immediately perform an action. The players who are already in the table are perfectly in sync with each other, as when they receive a message from the server, I show a screen overlay preventing them from clicking on any element on the table while an animation is running. After the animation is terminated, the game becomes available and runs normally. My problem is that if a new player joins the table after a message has been sent by the server, then he can perform an action while the animation is still running for the other players, thus starting a new animation for them at the same time and the game becomes messy. Is there a way to either prevent the new joiner from performing an action before the animation has ended for the rest of the players ? Do you have any other idea how I can solve this issue ? Thanks for your help"} {"_id": 3, "text": "How do I make a 2D sprite flash green when tapped? I have a sprite that is based on an image of a gray circle. When the user touches the sprite, I want the sprite to flash green, as in I want the circle to appear to turn green for 0.2 seconds. I tried setting the color of the sprite via SpriteRenderer's function SetColor, and it blended the color with the initial gray color of the sprite, so I got a very dark green even though I'm really sure I didn't mess up the values when I created the color. Now I'm trying to get my flashing effect by using separate images. I have the images I need, and I have a message getting logged when I tap the circle, I just need to setup a non looping animation and trigger that animation in my code."} {"_id": 3, "text": "texture won't move OpenGL ES 2.0 I want be able to move my texture in GLSL I have set my texture to wrap S and wrap T but not sure why it wont move my fragment shader looks like this at the moment uniform sampler2D n mapTex uniform sampler2D n mapTex2 varying mediump vec2 TexCoord varying mediump vec2 TexCoord2 This gets updated within the main code uniform mediump float vTime void main() gl FragColor texture2D(n mapTex, vec2(TexCoord.x vTime, TexCoord.y vTime)) within my code I have a made a function to calculate FPS and I use the delta time of that function to pass into the fragment shader void OGLESIntroducingPVRTools timer() This method records to the time to start rendering a frame and hold that value in another variable we then start to count again. To get delta time we subtact the current time from the previous time this will give us in milliseconds how long it took for a frame to render. We then divide this by 1000 this converts it from ms per frame to FPS FrameCount p Time c Time c Time PVRShellGetTime() elapsed c Time 1000.0f DT ((float)(c Time p Time)) 1000.0f fCount DT if(fCount gt 1.0f) if time is over 1 second reset counters and recount FPS FrameCount FrameCount 0 fCount 0 and in my renderscene method which updates I have this code to pass the value to the uniform within the fragment shader glUniform1i(glGetUniformLocation(m ShaderProgram.uiId, \"vTime\"), DT)"} {"_id": 3, "text": "Unity How to transition to a different animation during the blend phase? I have a set of animations Idle, start walking, stop walking, and walking full speed. I have the animations all blending nicely...and the controls are fairly responsive during most of the motion...but there are odd transitions where the blends take away control I can't transition to the walking animations when I am blending between the \"stop walking\" and \"Idle\" animations, for instance. How do I get the animations to transfer during the blend phase??"} {"_id": 3, "text": "Running two simultaneous animations on a model? I am just looking for a broad answer to this question. I am more curious about the general information rather than the specific. Also, I tried to search for this, but I think it's hard to word it so you get the right question. Anyway One common thing I see in a lot of games is multiple animations on the same model. i.e. A character runs, but also raises his arms an shoots. A character has a walking animation, but can also be carrying resources as he walks. I am curious if the first model has a \"run\" animation and a \"run while shooting\" animation. Or if they have a \"run\" animation and a \"shoot\" animation and run them at the same time. Obviously the first is possible, but I am wondering how the second one is done. Do they use two models for upper and lower body or is there a way to ignore certain parts of a model when animating? I know this depends a lot on the model, the programmer, language and the way the animation is done. But broadly, if you were making a model with the intent of it doing multiple animations at once, what would be the best way to go about it? Again, not after detailed specifics, just an overview ) Thanks!"} {"_id": 3, "text": "What constraint (if any) limits crowd animation variety? I have recently noticed something in a large number of sports games relating to the animation of the crowd. Scenario Player holes the golf ball and the crowd all clap their hands. Whilst the faces and attire of the crowd members are different the animation is exactly the same. That is, the arm and hand movement of each member is identical. Similar scenarios exist in other sports games in football games the crowd often stand up and sit down together as well as doing things like \"fist pump\", wave, etc. in a perfectly synchronised manner. Question Why is there no (or very little) variation in the crowd animation? Is this a memory constraint? If so, what is the general architecure design of this functionality and why is it so constrained? Is it along the lines of \"It is more efficient to animate a collection of objects than multiple individuals\"? Or do game developers simply not see crowd variation as an important enough requirement? As technology and game \"realism\" advances so quickly, this is something that still strikes me as \"wooden\" and unrealistic."} {"_id": 3, "text": "Turn based game in HTML JS CSS new joiner messes with state of game while animations are still running for other players I developed a playing cards web app using HTML JS CSS. Communication with the server is performed using WebSocket. The server is developed in Java Spring. The game proposes to join one of the many available tables where you can immediately perform an action. The players who are already in the table are perfectly in sync with each other, as when they receive a message from the server, I show a screen overlay preventing them from clicking on any element on the table while an animation is running. After the animation is terminated, the game becomes available and runs normally. My problem is that if a new player joins the table after a message has been sent by the server, then he can perform an action while the animation is still running for the other players, thus starting a new animation for them at the same time and the game becomes messy. Is there a way to either prevent the new joiner from performing an action before the animation has ended for the rest of the players ? Do you have any other idea how I can solve this issue ? Thanks for your help"} {"_id": 3, "text": "How To Animate Skeletal Interactions (Hugging, Handshakes etc.) I am fairly new to animating and IK systems, but I've got the basics down to some extend. Now I am looking into how to go about skeletal actor animation interactions such as handshakes, fighting, horse riding, hugging or sex animations and such, to be used in unreal engine 4. I would like someone to point me into the right direction on how to go about this. As I am new to this, if the question is too broad or vague please do let me know."} {"_id": 3, "text": "Head bone not found when importing .blend to Unity I have created a model, rigged it(using rigify), and created several actions(animation clips) for it Blender. Everything seems to be fine. However, when I import the .blend to Unity I get a console warning that \"Required human bone 'Head' not found\". I know that there is a bone called \"head\" in my .blend. The animations work, except the head rotation does appear to not be deforming. Has anyone experienced this? Is this just a naming convention thing. Should I try to rename my \"head\" bone to \"Head\"? I just don't know the inner workings of the the import process well enough to know what to do."} {"_id": 3, "text": "Animation in top down 2d How is this usually done? Especially when the character might need to use different animations, for instance at his hands and legs. I noticed some skeletal animation solutions but they were only applicable to platformer games. Any ideas?"} {"_id": 3, "text": "How can I manipulate a static 2D sprite so that it looks alive? I've got a stick figure in the corner of my UI, but I don't like the way he's just standing there, without moving. I'm stuck without additional frames of animation, so my only recourse is the manually move the sprite up and down, left to right, rotation, or whatever else you can think of. Basically I can do everything besides drawing another sprite of animation. I've tried things like have it subtly bounce or rotate a bit to give it a little bit of dynamism, but I don't believe its the best approach. I've got a static sprite of a stick figure, how do I give it a bit of life?"} {"_id": 3, "text": "why animated tiles aren't animated? So I got some code and I'm using pytmx to load the maps, but the animated tiles don't seem to animate in my pygame game. Is there a setting to change that or do I need to write the animation code myself?"} {"_id": 3, "text": "How to handle animations for a turn based deterministic game? I have a turn based combat system where all monsters act one turn, then all players, etc. The combat mechanics are completely deterministic I can pre calculate the outcome of a turn. I'm interested if I should do all calculations ahead of time (monster A will be at X, monster B will be at Y), and then just play a bunch of animations based on these calculations (Calculate for A) (Calculate for B) (Animate A move to X) (Animate B move to Y) OR do one animation per calculation? (Calculate for A) (Animate A move to X) (Calculate for B) (Animate B move to Y)"} {"_id": 3, "text": "Blending effect on textures Hi i am trying to build screen animation like flickering, interlace, color separation similar to old style malfunctioning Amiga screens. The intended effects are shown in this video. I am using libgdx and I already discovered the universal tween engine, which helps a lot to build transitional animations, but how should I approach those blending effects, any suggestions? I will specify my question once I learned more about libgdx, but maybe you could give me some hints already. Thanks!"} {"_id": 3, "text": "Skeletal Animation No initial bone rotation I am currently trying to implement animations in my game. I am having an issue where the bones do not rotate properly. In my program, I apply an inverse bind pose to each bone to move them to bone space. Then I recursively calculate the transformations for each bone for the keyframe. The bone transformation looks like this bone.Transform InverseRootGlobal Global bone.InversePose InverseRootGlobal is the inverted root node transformation Global is the recursively calculated transformation bone.InversePose is the inverse pose matrix It appears that all is correct apart from the bones initial rotation. When I move the bones to bone space, they loose their rotation from the bind pose and 'point up'. Here's what it looks like If it helps, I am using Assimp to import the data. Thanks in advance."} {"_id": 3, "text": "What constraint (if any) limits crowd animation variety? I have recently noticed something in a large number of sports games relating to the animation of the crowd. Scenario Player holes the golf ball and the crowd all clap their hands. Whilst the faces and attire of the crowd members are different the animation is exactly the same. That is, the arm and hand movement of each member is identical. Similar scenarios exist in other sports games in football games the crowd often stand up and sit down together as well as doing things like \"fist pump\", wave, etc. in a perfectly synchronised manner. Question Why is there no (or very little) variation in the crowd animation? Is this a memory constraint? If so, what is the general architecure design of this functionality and why is it so constrained? Is it along the lines of \"It is more efficient to animate a collection of objects than multiple individuals\"? Or do game developers simply not see crowd variation as an important enough requirement? As technology and game \"realism\" advances so quickly, this is something that still strikes me as \"wooden\" and unrealistic."} {"_id": 3, "text": "Timing in fighting game using animations time? I am developing a 2D fighting game in C . I have made the basic components such as moving, guarding and even a combo system that works perfectly well. My main concern now is that I want the game to be as balanced as possible, and thus I am entering a testing phase. I am even requesting the help of my father to play against as no AI has been implemented (yet). In the game you can chain attacks using a punch kick (PK) button. But you can also charge the attack by pressing the PK button longer, which basically pauses the animation, resuming it when the attack is fully charged or the player releases the button. One thing that I have noticed is that if your opponent is simply pressing the PK button when being hit, it can counter attack pretty easily if you end up charging your attack. This behaviour basically makes charging useless, because it can never go through if your opponent knows that. So my point is that I need to add a delay so that the counter cannot occur (I do not want it to, because the game is based on an actual PS2 game where you cannot counter that way for the record, there is a way to escape, either by pressing the guard button, or by hitting a button at the right timing to teleport behind and counter). To add this delay, I can either modify the actual duration of the \"damage\" animation so that it does what I want or I can internally add a timer where the character enters a state where he cannot do anything. I would want to go for the first one, since that way you SEE that you cannot counter using a punch since you are still in the damage animation. But the thing is that each character has its own set of animations and thus in theory, the developer or the designer (which is me in both cases) can modify the duration of one character while the others still have an old value. My question is thus more on the design level. Is it a good idea to let the timing be decided via animation duration? Is it what is actually done ? If I have fifty characters when I discover another timing issue, it would mean to modify the animation of each and every one of them... But adding a timer internally seems more like a patch that actual fine tuning..."} {"_id": 3, "text": "Unity Implementing Fall with Animation I have a character controller. I am primarily using FSM with the animations and blends. However, I am running into some trouble with the fall. I walk up to a ledge and walk off...sometimes I will make it off the edge and the falling animation will play...but sometimes I get stuck halfway off the edge. Also, the falling animation completely disregards any motion vectors I had prior to transferring to the falling state. Is there a way to transition to fall, retaining the current x y velocities? In an effort to fix this, I tried giving the attached rigidbody a force vector slightly up and in the direction of travel so that the character gets a little hop over the edge...but again, no luck."} {"_id": 3, "text": "How does \"Cut the Rope\" do such realistic animation? \"Cut the Rope\" is so smooth and real life like, while some apps are very \"bitmap\" like. How does \"Cut the Rope\" do such realistic animation?"} {"_id": 3, "text": "Head bone not found when importing .blend to Unity I have created a model, rigged it(using rigify), and created several actions(animation clips) for it Blender. Everything seems to be fine. However, when I import the .blend to Unity I get a console warning that \"Required human bone 'Head' not found\". I know that there is a bone called \"head\" in my .blend. The animations work, except the head rotation does appear to not be deforming. Has anyone experienced this? Is this just a naming convention thing. Should I try to rename my \"head\" bone to \"Head\"? I just don't know the inner workings of the the import process well enough to know what to do."} {"_id": 3, "text": "Unable to enable IK on someone else's rig I'm using someone else's character rig for reference but I'm not sure how I can enable IK solvers for the arms. The hand controller has a NURBS control with an ikBlend attribute, but when I try to use the \"Enable IK Solvers\" tool, I get an error saying the attribute is locked or connected. Clicking \"Unlock Selected\" on the attribute doesn't fix it. Breaking the connections also breaks the ability for it to drive the enabled disabled state of the IK handle. The rigged character can be downloaded here if anyone wants to try to help me out http www.antcgi.com 2014 06 03 free model 15 kila lods rig dynamics"} {"_id": 3, "text": "What's the best head bob formula? Given a point in space, a direction of travel, and a time since start, what's a convincing, non sickening formula to simulate head bob? What's been successful in previous games? Has there been any research on what bobs induce sickness the least? An example naive head bob formula, applied to the up axis http www.wolframalpha.com input ?i abs 28sin 28x 29 29"} {"_id": 3, "text": "How to set the runtime of an animation based on attack speed? Based on an answer I received on this question How to make an action perform only after an animation has run? I am using notifications in animations to perform certain commands actions. See in the documentation https docs.unrealengine.com en US Engine Animation Sequences Notifies index.html Before resorting to this site, I researched elsewhere for something about modifying the animation speed and the closest question I found was this https answers.unrealengine.com questions 509654 how do you change the ratespeed of animation.html Simply changing the speed of the animation, I know how to do it, but I want to control its runtime. Sort of determining how much time the animation has to play. In the image below I show more or less the scenario I have Note that the notification happens at the end of the animation (where I apply the damage). So based on the speed I set for animation to perform, every time it's finished the notification happens, applying the damage. It turns out that the animation doesn't necessarily have the exact duration of an attack starting when the other one ends (the image below will make it easier to understand) There is one more scenario I imagined. In the latter case, assuming the animation is (usually) 1 second long, and the character has the maximum attack speed (I set the maximum to 2 attacks per second). So the animation would be running 2 times faster But the attack speed will not always be a \"simple\" number, I would like to know how to calculate set it time so I have no problems when the attack speed is any number. I want to know how to set the animation runtime and a time interval between the animation running."} {"_id": 3, "text": "How to animate a flip of a card in Cocos2d? I am working on a card game and would like to ask if someone could advice me how to implement a flip of a card in Cocos2D?"} {"_id": 3, "text": "Trade offs of linking versus skinning geometry What are the trade offs between inherent in linking geometry to a node versus using skinned geometry? Specifically What capabilities do you gain lose from using each method? What are the performance impacts of doing one over the other? What are the specific situations where you would want to do one over the other? In addition, do the answers to these questions tend to be engine specific? If so, how much?"} {"_id": 3, "text": "Syncing first person arms and enemy character for struggle in games Some FPS have it where your arms are struggling or doing something melee to a character model. Both the arms and the character you're interacting with are sync'd up in the animation. What's the general idea behind how that syncing is done?"} {"_id": 3, "text": "Transition between two Views i want to animation the transition between game screens , in my game loop i have a function called getCurrentScreen() which returns a Screen object this Screen Class has a function called present() this function draw on the framebuffer , when i want to change to another screen i call setCurrentScreen(Screen) , so it will draw the screen i set , What i want is to animation the transition between these screens any suggestion , is the a book or an article that discusses this"} {"_id": 3, "text": "Where to find animated matrix transformations in an fbx file? Where can I find matrix transformation animation data in an fbx file? I have an fbx file with animations. I have successfully read the indices, matrix, and weight from it. How can I get the frame by frame changes in the matrix? Unfortunately, I haven't been able to find the answer in the Autodesk documentation."} {"_id": 3, "text": "How can I manipulate a static 2D sprite so that it looks alive? I've got a stick figure in the corner of my UI, but I don't like the way he's just standing there, without moving. I'm stuck without additional frames of animation, so my only recourse is the manually move the sprite up and down, left to right, rotation, or whatever else you can think of. Basically I can do everything besides drawing another sprite of animation. I've tried things like have it subtly bounce or rotate a bit to give it a little bit of dynamism, but I don't believe its the best approach. I've got a static sprite of a stick figure, how do I give it a bit of life?"} {"_id": 3, "text": "What animation technique is used in 'Dont Starve'? While playing a few games in my personal time off development I've stumbled across a survival 2D 3D survival game. The game was apparently made in SDL and GLUT (Dont starve) but what really amazed me was the animations in the game. The animations are extremely smooth and fluent. There is no distortion while animating, what usually happens in hand made animations is that pixels get removed, animations are jaggy and they simply aren't as smooth. That got me thinking on how they managed to accomplish such a quality of animations. Were they really handmade (If they were, then it must've taken a very talented artist), is it bone animation or are they using another technique?"} {"_id": 3, "text": "What is next to interpolate camera position with smooth speed changes? I am working on a path camera to be used in demo playback. (3d game) The spline math used is catmull rom. I am on my second attempt to get constant position speed ( (someone else is doing rotation). The path cam keyframes are position time. I have a step now when the path is recalculated, it also generates the arc distance time lookup table which I have normalized. I have the duration of each segment(k through k 1)as well as each segments linear velocity calculated from that data. I am not very good at reading anything except basic equations. I could use an explanation or psuedo code of what is needed next in order to get the camera to smoothly accelerate or decelerate depending on the velocity of the next segment. Right now it's instant changes and no good. I tried googling for hours and was going in circles."} {"_id": 3, "text": "MVC How To Handle Animations? I am working on a turn based game that utilizes the model, view, controller design pattern to separate logic from input from rendering. I am still a little new to the pattern, but from my understanding I have laid out the following MVC system. The model(s) comprise a set of pawns with game flow and interaction logic. Pawns models know how to interact with each other and the model world, but only when signaled to do so via function calls. (i.e. pawn.move(startLocation, endLocation) or pawn.attack(enemyPawn)) The view(s) make up everything that is viewable by the player. This includes menus, visual representations of the pawns models, and any user interface components like cursors and buttons. The view(s) query the model for data to draw visual representations of pawns. The view(s) also can dispatch user interface events to any observers interested in these events. The controller(s) handle all transition and input logic. When an interesting user interface or input events occur, the controller decides what the model should do and signals the model to do it. The controller also handles swapping out of views when necessary. I know there are many ways to implement MVC and I am open to suggestions if something seems off with this design, but the real problem I am having is how to handle animations in the view. Say the user commands a pawn to move 5 spaces North and 1 space West. I want an animation to show this over several seconds. How would I handle something like that?"} {"_id": 3, "text": "Game thread, render thread, animation inverse kinematics, and synchronization In a multithreaded setup with a game logic thread and a render thread, with some kind of skin mesh animation with inverse kinematics plus etc how does animation work? Does the game logic thread just update a number saying time T in the animation and then the render thread infers Who owns the skin mesh animation, the game logic thread or the render thread? How is it stored in the scene graph if it is stored there at all? When the game logic updates does it do the computation of the skin mesh animation and the computation of the inverse kinematics and then store the result directly in the scene graph or is it stored indirectly and the render thread does the computation?"} {"_id": 3, "text": "How to add (not blend) non looped animation clip to looped animation with Mecanim? I have a GameObject with Animator and looped animation clip. This animation changes X coordinate from 0 to 10 and back. I need to add another animation to the first one that increases GameObject's scale and changes its color to red simultaneously. After scale and color change GameObject keeps these parameters and continues to move according to the first animation clip. The only way I managed to work it around is writing a custom script with couroutine IEnumerator Animate() float scaleDelta 0.2f float colorDelta 0.02f for (int i 0 i lt 50 i ) spriteRenderer.color new Color( spriteRenderer.color.r, spriteRenderer.color.g colorDelta, spriteRenderer.color.b colorDelta) transform.localScale new Vector3( transform.localScale.x scaleDelta, transform.localScale.y scaleDelta, transform.localScale.z) yield return new WaitForSeconds(0.02f) This works for linear interpolation, but requires to write additional code and write even more code for non linear transformations. How can I achieve the same result with Mecanim? Sample project link https drive.google.com file d 0B8QGeF3SuAgTU0JWNGd2RnpUU00 view?usp sharing"} {"_id": 3, "text": "How do I scale a motion capture animation? I used motion capture in my room using the Kinect. As I don't have much space I make compressed running moves, i.e. I put my legs up and down while not moving far forward. How can I stretch the animation, so me walking 1 meters amounts to the skeleton walking 3 meters or similar while not exaggerating movements to the left right?"} {"_id": 3, "text": "Calculating the correct roll from a bone transform matrix Read this forum topic for more info http blenderartists.org forum showthread.php?260602 transform matrix to bone 28head tail roll 29 bug I'm trying to get my Blender3d modeller importer to create correct bones from my file's transform matrices. The Blender Python API doesn't have a way to do this (anymore!), so people had to dig the Blender C source to find out how Blender does it and port that. Here's a Python port of the needed functions, not by me (I don't know C) def vec roll to mat3(vec, roll) target mathutils.Vector((0,1,0)) nor vec.normalized() axis target.cross(nor) if axis.dot(axis) gt 0.0000000001 this seems to be the problem for some bones, no idea how to fix axis.normalize() theta target.angle(nor) bMatrix mathutils.Matrix.Rotation(theta, 3, axis) else updown 1 if target.dot(nor) gt 0 else 1 bMatrix mathutils.Matrix.Scale(updown, 3) rMatrix mathutils.Matrix.Rotation(roll, 3, nor) mat rMatrix bMatrix return mat def mat3 to vec roll(mat) vec mat.col 1 vecmat vec roll to mat3(mat.col 1 , 0) vecmatinv vecmat.inverted() rollmat vecmatinv mat roll math.atan2(rollmat 0 2 , rollmat 2 2 ) return vec, roll How to use them pos mymatrix.to translation() axis, roll mat3 to vec roll(mymatrix.to 3x3()) bone armature.edit bones.new('name') bone.head pos bone.tail pos axis bone.roll roll Sadly, it seems even the Blender C code is buggy and doesn't take into account cases when the bone is parallel to (0,1,0). So such bones can get assigned wrong (by 180 degrees) rolls and mess up animations. Does anyone have better code for generating roll which takes into account such cases? The old Blender 2.4 API generated correct ones. Its C code can be found here http svn.blender.org svnroot bf blender branches blender 2.47 source blender blenkernel intern armature.c I'm no C coder myself, again."} {"_id": 3, "text": "Compensate for animation time in multiplayer network game I'm developing a multiplayer turn based card game. In certain scenarios, the clients are required to perform an animation before moving on with the game. For example, the server informs the clients to animate dealing cards to all players. This animation takes around 5 seconds. Afterwards, the server informs a client to make a move, with a timer showing how long they have to play. How can the server wait for the animation to finish before moving on and starting a timer and informing a client to play? The timer obviously needs to start after the animations are complete. I've thought of the following 1) Hardcode the animation durations on the server side and delay sending out the next message to the clients until after the duration of the animation. 2) Have the clients inform the server when an animation is complete. ..but I feel that there should be a better way. Is there any other way to do this?"} {"_id": 3, "text": "How do I spread a LookAt rotation over 3 bones with different percentages? I'm trying to rebuild the RE4 controller. At first, I thought that only the chest bone is used to rotate the pistol towards a target. I have then however found a hack to put the camera in a fixed position so that I could actually see the bone rotations. Juding the logic that I have recorded, I believe that first a LookAt rotation is used, and then this rotation is spread over the abdomen, abdomen2 and chest bones. Looking at the video that I have recorded, I think that the rotation is not quot divided by 3 quot , but procentually and then again changing towards the limits (for example, at the limits, the rotation is mostly done only by the chest). Can anybody tell me if my judgement is correct, and if yes, how to split a rotation this way? Would this be correct? gt The chest bone moves the most, the abdomen2 less, and the abdomen bone moves the least. In percentages chest bone 60 abdomen2 bone 30 abdomen bone 10 Let's assume a rotation of 200 . Am I right to assume that the rotation of each bone is calculated like this? Chest bone Gets 60 of 200 , that is 120 Abdomen2 bone Gets 30 of 200 , that is 60 Abdomen bone Gets 10 of 200 , that is 20 . Thank you! ps Here are a few screenshots, but it's much easier to estimate from the video"} {"_id": 3, "text": "Following a path in a smooth fashion I am currently making a 2d tower defense game with a static, predetermined lane that the enemies follow (i.e. towers cannot block the path and path finding is not the problem I am trying to solve). I am trying to figure how exactly to make units follow this lane in a smooth way. I have two rough ideas about how to do this, but I would love some input on which is likely to be easier to implement the more standard technique. Or of course if I there is some totally different way that I haven't considered I would love to learn about that as well. Waypoints My first idea was to define the path as a series of hard coded waypoints. Units would then use a basic \"seek\" steering algorithm (such as this one) to move to each waypoint along the path in succession. However, I have wondered if it might be hard to keep the units from deviating to much from the lane I want them to follow. I wonder if inability to turn sharply enough might cause them to sort of \"glide\" out off of the desired lane. I suppose I might be able to prevent that though by allowing for a relatively strong steering force to be applied? Bezier Curves The second solution I have considered is to define the path with a bezier curve and at each time step calculate the point along the curve with is (dt speed) away from the unit's current location. I suspect that this technique would make it much easier to precisely define the path that units will follow, but I don't know know how exactly to go about implementing this. Any suggestions? Also, I don't this will change anyone's answers, but units also must be able to travel at a constant speed along the path. Additionally, I am programming this game in python using the pyglet framework. If anything about the question is unclear please let me know. Edit Also for whatever its worth, I'm sort of trying to replicate the movement behavior of enemies in the Kingdom Rush."} {"_id": 3, "text": "How can I generate isometric sprite sheets from 3D animations? I want to generate sprite sheets for an isometric projection of various 3d assets purchased from the Unity3D asset store. I'd preferably also render the normal maps. I am a programmer, but new to 3D modeling software (Blender, etc.) I found two tools for this SpriteForge and SpriteWorks, but neither supports enough formats to be worth their cost. There must be an efficient way of isometrically rendering various animations of a 3d assets in Blender mdash but I don't know how. How can I do this?"} {"_id": 3, "text": "How to flip sprite and all collision children of a KinematicBody2D at the same time? I have tried to use the scale property of KinematicBody2D to flip at the same time the sprite and the collision area raycast children. For flipping, one just has to set scale.x 1. If it works in the editor, it does not work properly because the engine seems to reset scale.x to 1 each frame (as stated here) NB Here the original sprite is looking left (that is why it is blinking when going to the right, not very didactic sorry). How to do the same without flipping every collision children one by one?"} {"_id": 3, "text": "Importing skeletal animation from vertex coordinates in maya I have files of different frames of an animation which have the vertex co ordinates of a human skeleton in 3D space. I want to import the animation from these keyframes into maya to perform motion retargeting. Please help me get some direction in this. Also is there any other way to retarget motion from one skeleton to other(different size) other than in maya?"} {"_id": 3, "text": "How to flip sprite and all collision children of a KinematicBody2D at the same time? I have tried to use the scale property of KinematicBody2D to flip at the same time the sprite and the collision area raycast children. For flipping, one just has to set scale.x 1. If it works in the editor, it does not work properly because the engine seems to reset scale.x to 1 each frame (as stated here) NB Here the original sprite is looking left (that is why it is blinking when going to the right, not very didactic sorry). How to do the same without flipping every collision children one by one?"} {"_id": 3, "text": "How to implement scene changing in real time? I want to implement real time scene changing effects to make my game could changing from spring to summer, summer to fall, fall to winter. And Chaning effects like this game. Giana Sisters. I think Giana Sisters use animation to transit from two scenes, but I dont know how to make these animations. Is any other suggestions could make this effects?"} {"_id": 3, "text": "Automated animation retargeting I am currently developing a video game using my own game engine I develop at the same time. While making a good progress in the past months, I am currently stuck. I assume I only miss a minor thing, but I need another pair of eyes and I really hope you can help me! I wrote a converter which reads FBX files (using the official FBX SDK 2017.0.1) and converts them into my own custom file format. I am able to read meshes, texture and material information, the skeleton and all animation stacks. In my game (engine) I am able to display the textured meshes and animate them with any of the read animation stacks. However, there is one problem for me. I bought meshes for NPC characters from a 3D artist and I also bought a huge animation pack from another artist. The character meshes include the perfectly textured and rigged mesh with all joints and the animation pack contains a rigged dummy mesh with all joints and animations. I want to be able to use any animation from the animation pack on any mesh from the character artist. My first step was to write a joint mapper. When reading the files I know which joint has which type. So, I am able to map the joints from the character mesh to the animation mesh and vice versa. The skeletons of both meshes are pretty similar and the mapping is going to work out. In the FBX samples the animation calculation for a given vertex is Inv(Mesh GlobalPosition Mesh GeometryTransform) Joint GlobalPosition Inv(Joint TransformLinkMatrix) Joint TransformMatrix Mesh GeometryTransform Since Mesh GeometryTransform is the identity matrix for all files I have bought, I can remove it from the term above. The result is Inv(Mesh GlobalPosition) Joint GlobalPosition Inv(Joint TransformLinkMatrix) Joint TransformMatrix Joint GlobalPosition is the transformation in Bone Space and the only matrix that is time dependent in this equation. Inv(Joint TransformLinkMatrix) Joint TransformMatrix is used to transform the World Space to the Bone Space, as I understood. Finally, Inv(Mesh GlobalPosition) is used to transform the result back to World Space. If I understood something wrong, please correct me!!! The joints which are used for the animation mesh are in a different space than the joints from the character mesh, because they come from different artists. I believe the missing part is to map between the joint spaces of both meshes. However, I do not know where to enter the mapping and I also don't know which spaces do I need to map? Object Space? Bone Space? I'd appreciate any kind of help and will reward a useable solution with credits in my game!"} {"_id": 3, "text": "How to avoid wagon wheel illusion of a rotating gun barrel reversing direction? I didn't know which forum to post this in, but I'm going to try here first. I am making a shotgun with 3 barrels which spin. However, I also want it to have kickback in the animation, but every time I add that recoil it breaks the animation, making a strange wagon wheel style illusion. No matter what I try, it always reappears once I add the recoil. Here is the animation Here is how the animation is supposed to be perceived, with the barrels spinning in one direction But this is what I often see when I look at it, where it seems to snap backwards one step It may be a bit hard to see, but if you look at it long enough it will flip between the two, similar to that animation of a ballerina which can be spinning in either direction. I have tried having it only spin when it is down, only spin when it is up, changing the interpolation of the spinning and of the recoil, everything I can think of, but none of it works. How do I solve this problem? Can I stop the optical illusion while keeping the recoil?"} {"_id": 3, "text": "How to animate a character from a sprite sheet? I'm making an online game, and I had been using a blank square as the character until recently. Now I want to add a real, animated character. I downloaded a free sprite sheet which has 12 (3x4) character sprites. What is the general method to animate the character? I see why having all the character animations in one file can be useful, but I don't understand how it would be done. I don't want code or anything, I just want to know how you normally use the sprite sheet to animate a character so I code it afterwards."} {"_id": 4, "text": "Literature about Open World Games, Freedom to Choose I'm doing a diploma thesis about the development of games with freedom to choose or open world. Topics will be i.e. development issues in programming and the design itself, mechanics etc. For that I need literature and lot's of it. Do you have any suggestions?"} {"_id": 4, "text": "Is it unethical to make a game AI that is secretly non competitive? In several games the AI is designed to give the player an easy time without their knowledge. This can be having a 0 chance to hit the first time you appear, enemy letting you sneak up on them by not turning around, or the lowering of difficulty when the player is hurt or has restarted several times. I would be offended if at the end of a board game or sport I was told that a human had not tried their hardest. Does the same ethics exist for an AI? edit As in the title, my main concern was keeping the handicap hidden from the player, for example, when playing a shooter it is reasonable to expect the player knows the AI has an artificial reaction time and poor aim but my question was about games that hide things such as enemies not using the best weapon or lowering their difficulty when the player is inured."} {"_id": 4, "text": "Why do most video game guns reload without losing unused ammo in the magazine? If I have picked up 500 spare ammo and I 73 100 bullets in my current gun, why will I end up with 473 spare ammo instead of 400 (losing the 73 unused rounds in the previous magazine)? Is this just to make it easier on the player? I want to make a challenge shooting game and it seems like timing your reloads would be interesting. Is there any reason I should stick to the norm?"} {"_id": 4, "text": "Handling non automatable, repetitive, game tasks A problem I'm currently having with a project of mine is deciding how to handle repetitive, but important, in game tasks. As an example (Though there will be many other instances of this), earlier in the game, the player must smelt and shape iron without modern tools. After iron ore has been smelted, it must be shaped into tools, this requires manual labor. So how are some ways I could handle the shaping process (A repetitive, time consuming, task)? Having the player sit in a GUI until the shaping process is complete is obviously not a great idea. I don't want to make the process instant and simply rely on the speed of the smelting process to cull production, as the player could just utilize a huge number of furnaces to bypass that. For other reasons, it would be incredibly difficult and time consuming to create a short mini game for each of these situations. Is there an easy way to solve this?"} {"_id": 4, "text": "How do they made Pok mon games so flawlessly balanced? I find it hard to believe how well balanced the Pok mon games are. Not just within the games, where you'll find amazing balance from the very beginning to the very end, but, surprisingly, even when things get more competitive. If you have ever played the simulators that are available, you'll know what I'm talking about www.smogon.com. There are thousands of unique Pok mon characters, moves, traits and items. Yet, if you try to find a single broken strategy, You can't. And if you do find something obscure that could give you a good advantage, you'll realize it's impossible. The emerging competitive scenario is one of the most amazing strategy games I've ever seem, and it's not even a feature of the Pok mon games!"} {"_id": 4, "text": "Can a scrub design develop a strong competitive fighter? The definition of Scrub in this question comes from David Sirlin's famous article, Playing To Win I am a fan of fighters, and I am fairly well versed in design (I get my daily dose of gamasutra). However, I am also a MASSIVE Scrub. I don't like using tactics characters that I feel lessen the experience or go against the spirit of the game (for example, Street Fighter's roll cancel glitch, MVC2's infinite combos, Cable, etc). I will practice and get good at using those tactics characters, so that I can better defend against them, but I'd never use them against another player. My question is, can someone like me design develop a strong competitive title, or does my outlook prevent me being able to appreciate elements of design that are a necessity for developing a competitive scene? My question is, are such elements necessary in creating a competitive fighter? What are the \"gotchas\" a scrub would by hindered by when designing developing a competitive fighter?"} {"_id": 4, "text": "Particle systems on multiplayer games I'm working on a 2D javascript Three.js multiplayer game, using web sockets and an authoritative server currently written in Python. The combat mechanic will be similar to Geometry Wars however i'm struggling to get my head around how to implement this in an efficient way. There are several drawbacks concerns I need to take into account Efficiency is key Three.js particle systems aren't mutable, you cannot add or remove particles once the system has been created, only move them off screen All calculations with respect to collision and damage must be done server side My game currently implements entity interpolation with fixed time step updates from the server Potentially several different weapons projectile types I can see several solutions Handle each 'bullet' particle individually Pros Most accurate way of doing thigs Cons Slow on server Lots of bandwidth Hard to batch draw objects, will have to draw each individually Use ray casting on server and have some form of network synced particle emitter Pros Much easier on the server and network Cons Network synching issues What happens when a bullet hits an object? Bullet will pass right through Use ray casting on server for collision damage and use raycasting on client for more accurate particles Pros Much easier on the server and network Will look more accurate Cons May still have some synching issues More work for the client Obviously the amount of players currently connected will have an impact on the implementation, I would ideally like to allow hundreds of players to share a game world but there may only ever by 20 or so on screen at once. The mutable particle system is an issue for all of these but I would still like to use it as it is more efficient that drawing each particle individually. In a test I could have over 10000 particles all moving and still get 60fps. Any help or comments on my though process would be greatly appreciated. Is there another approach that would be better?"} {"_id": 4, "text": "Need help with making number system for idle game So, I want to create a new game. I have problems with how to store large numbers in the game and how to output them. I have written a small pseudo code that contains everything I need to play the game (Did I forget anything?). represent our number struct BigNumber double base (or mantissa) double exponent create new number function NewBigNumber(double b, double exp) return BigNumber base b exponent exp now if we have to BigNumbers we want add operation ( ) and other operations ( ), ( ), ( ) function adding(BigNumber n, BigNumber m) if numbers have same exponent part if (n.exponent m.exponent) adding base here double new base n.base m.base create new BigNumber with new base return NewBigNumber(new base, n.exponent) else ????????? function subtraction(BigNumber n, BigNumber m) function multiplication(BigNumber n, BigNumber m) function division(BigNumber n, BigNumber m) As you can see, I will use Scientific notation I have a problem with the addition operation (and other), what if the exponent part of numbers are different? Next I have this code. If we have achievement systems we need function equals of two numbers function equals(BigNumber n, BigNumber m) if (n.base m.base amp amp n.exponent m.exponent) return True else return false And finally, I need the function to output numbers nicely. suffices 'K', 'M', 'B', 'T', 'Qa', 'Qi', 'Sx', 'Sp', 'Oc', 'No', 'Dc', 'Ud', 'Dd', 'Td', 'Qad', 'Qid', 'Sxd', 'Spd', 'Od', 'Nd', 'V', 'Uv', 'Dv', 'Tv', 'Qav', 'Qiv', 'Sxv', 'Spv', 'Ov', 'Nv', 'Tt' now we need \"good view numbers\" function for exapmle 1000 1000 1000000 1Million function(BigNumber n) ????????"} {"_id": 4, "text": "Sprites Are there any tools to scale sprites individually without using Photoshop GIMP? I am using TexturePacker as tool to pack my 2D sprites, it is good but it doesn't provide the possibility to scale individual sprites to a specific scale. I am wondering whether there is any good tool or command line to scale the files in the original folder without having to use TexturePacker. What I am trying to do is to fix some scaling errors that the illustrator that produced the files did without having to re scale fix things using Photoshop that is more time expensive."} {"_id": 4, "text": "How complex should enemy AI be in a dnd alike? I'm writing a text mode (python ncurses), turn based rpg based loosely on 3rd edition D amp D and Neverwinter Nights (the PC game) rules. It's not going to be a full implementation, but 'in the spirit' of them. I already have quite a bit of the basics in place movement, a few base classes and races, rule based encounters (shop npc monster X shows up when condition Y is true), dynamic generation of monsters, player and enemy stats and random, levelled equipment etc. It's enough to start moving around a basic world, talking to people, examining objects and location and now I'm moving on to (melee) combat. I'm interested in what people would expect of an algorithm that co ordinates the computer controlled attacks of an enemy party against the player. How smart should the computer controlled enemy be (in my implementation the player will take control of each of his own characters in turn, and they wont be AI controlled, but the enemy party will attacking, spell casting etc at will). For example if an enemy character initially chooses a random pc from the players party on round 1, should that enemy continue to attack the same target in subsequent rounds. How about if another pc then attacks that enemy? What if the enemy is unable to cause damage to that pc (ie say the pc has something crazy like damage reduction 100 5 should the programme know in advance?), should they switch to another in the players party? Has anyone implemented anything similar and would be able to provide any pointers?"} {"_id": 4, "text": "How do I fairly distribute new powerful cards to players in a collectible card game? I'm writing a game in which users start with a few cards. They use those cards to play against other players. The winner can steal a card from the other player. The aim is to get more different rare higher powered cards. If everyone starts with 10 low powered cards, how would anyone ever get higher powered cards? They'd just be playing against people who have the same type of cards as them. How do you fairly distribute these more powerful cards among players?"} {"_id": 4, "text": "Who has ownership of publicly developed projects? After seeing the comments on selling an idea to developer for a game, the general concencus is that without a game, or atleast a demo, it s not going to happen. So someone (yes, Noctrine, I am looking at you) suggested that it might me an interesting idea to turn it into a public project. A few people have asked if I minded if they turned some of my concepts into models, something I always have agreed on. They tell me that it would be to use as work for their portfolio or for practice. Still waiting on those, but that is another story. If I do this, set up a group to help starting modelers and programmers practice or get stuff for their portfolio, after everything is said and done, who has ownership of the project. I ask in case we end up with an actual demo and a studio get s interested. Who do they buy it from? I have no issue with paying accordingly to all participants, but in the legal aspect, who owns it before a publisher buys it?"} {"_id": 4, "text": "What is the purpose of adding non gameplay elements to a game? As an example, I'll reference scientists in Jetpack Joyride. I do understand there are achievements that involve scientists, that you can kill them or you have a nerd repellent, but I am not asking about any of those. I want to understand whether there is any very important reason to have such an element in a game, since (at least initially) it seems quite insignificant. More precisely, does the presence of scientists (or any equivalent, apparently insignificant \"actor\" in a game) has any psychological effect or influence of any kind to the players? Or they are simply there as a small little feature of the game that barely makes any difference to the player's feelings amp attitude whilst playing the game?"} {"_id": 4, "text": "In a visual novel game with optional sidequests, how to encourage the sidequests without requiring them? Context I'm working on a small visual novel style game, telling the story of a defense attorney and investigator. The story is split into chapters, with each chapter being a new case, and there are also recurring characters who develop throughout the story. It's a mini Phoenix Wright style experience, with some point and click detective work mixed in. As part of the game, you can embark on optional character based sidequests, each of which focus on a different character and showcase some development between them and the protagonist. A few of these sidequests unlock after completing each case, and are usually related to the case that just happened. For example, after finishing a case involving a video game convention, you unlock an optional sidequest where you can take one of the supporting characters (the quot tough guy who's secretly a dork on the inside quot , of course) to the convention before it leaves town. I want to make these sidequests optional, and not force the player to do all of them or make them feel like they have to say quot yes quot to all of them that is, I want to establish that they're free to decline an invitation if they don't like a particular character as much as the others and would rather not take them out for ice cream. However, I still want to make sure the player does some of them, because I feel many of them, if missed, would cause the player to miss out on really neat parts of the game. (If it helps, the game doesn't have a quot completion percentage quot or anything, just small achievements for doing certain things.) My question Given this design, I have a conundrum. I want the player to do at least some of the optional sidequests, but I don't want to force it or make them feel like it's necessary to see every single one of them. I don't want to place an arbitrary quot you must do 3 sidequests to proceed quot roadblock, but I also don't want the player to skip all of them and do the entire story without developing any of the characters. That obviously defeats the point of a heavily character based visual novel! So, this is my dilemma What game mechanics in a visual novel are best to encourage optional sidequesting, but not require it for story progression or completion? I have a couple ideas for this, since a lot of games have offered solid solutions for this problem already Making the sidequests optional, but having rewards for doing them. This is the approach that most games take nowadays. You don't have to do the sidequests, but maybe if you do one, it unlocks a palette swap, an item, or a hint coin. Affinity mechanics. Maybe if you do enough sidequests for your prosecutor buddy, he gets closer to you and gives important hints in a later cases. This would work similarly to quot friendship quot in other games, where there's a number that keeps track of how good your relationships with different characters are and doing quests increases that number. At the same time, I think this encourages too much of a quot metagame quot approach, where players will just do every sidequest for a character all at once to unlock their bonus. It also makes the difficulty curve of the game wonky, since I want the cases to start easy and get progressively harder, and giving substantial bonuses in the late game might mess with that design. Requiring the player to do at least X of them. This is the roadblock approach blocking the progression of the story until the player does at least 1, 2, or 3 of the available sidequests. I dislike this because it feels like I'm being arbitrary and might frustrate the player if they don't like the current sidequest options and really want to do the next case. Ideas and other suggestions are welcome!"} {"_id": 4, "text": "Collision with User Input and Object I am curious on how to handle collision detection involving a moving target and user input. Basing myself in the mobile space, I get events from a set framework, but I do wonder about the amount of lag involved. Say the object moves faster and faster, then position of the input and the object is very important. What I want to know is what is the best design for handling user input and then also the best way to make sure to accurately work out when the input point collides with the object, keeping threads in mind?"} {"_id": 4, "text": "How do I make players believe they're doing something wrong even when they're not? You're doing it right. right? In the game Cart Life, you are led to consider this, even though you are doing fine. This effect is created by making you do mundane jobs, earn little money, and have and things happen that feel like your fault. Is there a better way than life like mundane and unfortunate encounters to make you feel like you're failing at the game? I want to use this to mess with how my players play the game. Overwhelm them. Make a little success feel huge. Make them feel depth. Any ideas?"} {"_id": 4, "text": "Separating game logic and rendering I know this has been asked before but I would like some things cleared up. I understand that game logic and rendering should be separated but my problem is more or less how? For instance, should the renderer get ALL info from the sprite object and use that to draw? Also should the renderer be a seperate class or member function. If it's a separate class should it be able to get the necessary info via public functions or should it be a friend of the class to draw it? Also some clarification as to what the main object should contain, e.g, is it okay for the main class to have other sprites, shapes, fonts, and effect data? Or, should the renderer somehow contain or produce that data? I'm asking this because I'm making a menu list class in SFML. And, although it technically works, I'm confused because it's implemented in a way that is considered by many to be bad. Thus, I would like to know as to how to implement it and fix it correctly because I have currently blended both the logic and rendering together. class MenuList private bool m visibility true std vector lt std pair lt MenuItem, sf Text gt gt m items sf RenderWindow amp m window SEL EventManager amp m manager sf Font m font sf RectangleShape m highlighter sf Color m highlightColor sf RectangleShape m box size t m size 0 size t m rowSpacing static const uint16 t indent public MenuList(sf RenderWindow amp window, SEL EventManager amp manager) MenuList() get a certain option, no range checking MenuItem amp operator (size t index) get a certain option, with range checking will report an error to the console if range is out of bounds MenuItem amp getOption(size t index) update the menu void Update() set the visibility of the menu void setVisibility(bool value) get the visibility of the menu bool getVisibility() const add another option void addOption(const MenuItem amp item) add multiple options via a list void addOption(std initializer list lt MenuItem gt items) remove an options index void removeOption(size t index) remove an option by name void removeOption(const sf String amp name) resize the amount of submenus void resize(size t size) get the local position of the menubox sf FloatRect getLocalBounds() set the amount of spacing between each menu in pixels void setRowSpacing(size t rowSpacing) get the amount of spacing is in between each menu in pixels size t getRowSpacing() const void addSeperator(size t index, sf PrimitiveType Type sf PrimitiveType LinesStrip) get the amount of sub menus size t getMenuCount() const noexcept get the position of the menu, the top left const sf Vector2f amp getPosition() const noexcept move the menu to a completely new position, overides the previous position void setPosition(float x, float y) move the menu to a completely new position, overides the previous position void setPosition(const sf Vector2f amp pos) void setOutlineThickness(size t thickness) size t getOutlineThickness() const reset the menu such as the size, menus, and box void reset()"} {"_id": 4, "text": "Why are most characters all the same height in games? In the majority of video games I play, I notice that NPC's are the same height. What's up with that? It kinda takes me out of the experience, when I see ten people in a row that are 5 foot 8. Anyone else notice this, or am I crazy?"} {"_id": 4, "text": "How to measure skill in a pinball game? I am trying to come up with a system to measure or estimate the skill of a player at a single player game (so no head to head rating system help here). Specifically, it is a pinball game, but I do believe it is similar to most point based single player games. I have thought of 3 approaches total points scored with a threshold for each skill level average points scored over all time average points scored over last X games All of them use points, which I think is probably the right metric anything a player does in pinball grant points, with the most difficult objectives worth more points. Points also take into account all of the rare combination of objectives (like score multiplier multiball) that would be hard to track manually. However, I am not sure which approach to use and I bet other games have implemented similar skill measuring system that I can use as a guide, so I'd appreciate any and all help on this."} {"_id": 4, "text": "How do Action RPGs make different weapon types feel unique? I'm getting feedback on my game which has Action RPG elements (think Diablo, Torchlight, etc.) but you control a team of heroes. When you kill enemies sometimes new weapons will drop. In my game the DPS of the weapon will be randomized but stronger the further you get. Each weapon type has a hard coded range and rate of attack, but it differs between types. As an example, every Pistol will attack once per second and every Machine Gun will attack 5 times per second. A common complaint I'm getting is The weapons needs more variety, there's not really many reasons to change weapons because they all have the same speed and small damage differences. I'm struggling to achieve this. I can vary speed and range for each type, and this seems like an \"ok\" solution but it's not good enough. This just feels like a sliding scale that looks like this range lt gt rate of attack dps 10 Here you can change the range and the rate of attack, but the DPS is still going to be based on the level of the enemies. In the end, it's still not going to matter which weapon you choose because they'll all have about the same DPS. If I make it so they don't have the same DPS, then yeah, there will be reasons to change weapons, but it'll be because some weapons suck and some weapons are good. I don't think this puts me in a better place. I want the player to feel like weapon type X has pros and cons over weapon type Y. How can I achieve this?"} {"_id": 4, "text": "What is the term for the level progression paradigm in Bejeweled? Looking at the various level progression paradigms for my puzzle game, I decided to rule out the common ones such as 3 star per level, linear campaign like story, etc. I like the idea of Bejeweled's classic mode where the player simply keeps on going. What exactly is this paradigm called? I can't find any write ups on it so I can't quite tell what its structure is like. Is it infinite? Does the difficultly increase with each level in some shape, way or form (more likely to get \"No moves\")?"} {"_id": 4, "text": "Hinting at Steganography I'm working on an ARG which will be implemented mostly through a standard website. I'd like to give some of the images on the site steganographic content (hidden content stored in an image, e.g. an 8 color image of the same dimensions stored as even and odd color values in the pixels). Technologically, this is fairly easy to do. However, I'm having trouble figuring out a subtle way to hint at the presence of this content. The effect itself is invisible to the naked eye, and nobody just randomly checks for this kind of thing. What can I do to draw players' forensic attention to these images, while still maintaining an amount of subtlety (i.e. something that doesn't make it glaringly obvious)?"} {"_id": 4, "text": "What are examples of games with \"minimalist\" models art assets When teaching game development, my student's obsess about building realistic or complex art models animation. And spending wayyy to much time trying to get accurate collision detection between two 3D models despite my best efforts However I would like them to spend more time thinking about developing the game mechanics, interaction and game play. I'm looking for some games where the visuals are simple but have good game play. Things I am thinking about are Cubes' vs Spheres or Impossible Game. What are more examples of visually simple (preferably 3D) games to help inspire my students?"} {"_id": 4, "text": "Characteristics, what's the inverse of (x (x 1)) 2? In my game you can spend points to upgrade characteristics. Each characteristic has a formula like A) out in for one point spent, one pont gained (you spend 1 point on Force so your force goes from 5 to 6) B) out last level (starting at 1) so the first point spent earns you 1 point, the next point spent earns you an additional 2 and so on ( 3, 4, 5...) C) The inverse of B) You need to spend 1 point to earn one, then you need to spend 2 to earn another one and so on. I have already found the formula for calculating the actual level of B when points spent x charac (x (x 1)) 2 But I'd like to know what the \"reverse\" version of B) (usable for C) is, ie. if I have spent x points, how many have I earned if 1 spent gives 1, 1 2 3 gives 2, 1 2 3 6 gives 3 and so on. I know I can just calculate the numbers but I'd like to have the formula because its neater and so that I can stick it in an excel sheet for example... Thanks! ps. I think I have nailed it down to something like charac sqrt( x m k) but then I'm stuck doing number guessing for k and m and I feel I might be wrong anyway as I get close but never hits the spot."} {"_id": 4, "text": "Does inflating scores make players happier? I realize that this will depend on a game to game, situation to situation basis and that this is not a very technical question, but I remember hearing in a tech podcast a few years ago that inflated numbers of points (e.g. 1000 points vs. 1 point) was preferable in games because it was either a standard or because it had been shown to produce better feedback experience from users. Either case, it seemed to make users happier than lower numbers of points. I have since been unable to find supportive evidence either way for the theory that inflating scores can keep the user engaged. Is this inflated point theory true? Where can I find more information and, particularly, some experimental data on different approaches and their effectiveness?"} {"_id": 4, "text": "If I design a game that has both guns and melee weapons, how do I make them equally viable? I have a plan to make a 2D action platformer game, and I've started prototyping a bit in Godot 2D. My intention was to make the character fight with both guns and melee weapons, with gunplay like the Metal Slug series and melee mechanics akin to what's found in Dead Cells. The gun would be bound to the right mouse button as a secondary attack and the melee to the left mouse button as a primary attack , though I do plan on making it so that the player can switch their primary attack type. The gun used and the melee weapon would be different per character one would have a high caliber revolver and a greatsword, while another would have a high RoF assault rifle and a knife, for example. The basics, I get (right now I use a free game art sprite set, and I can use the frame number in the animation to fire a bullet or enable the melee attack hitbox). It's the balancing issues that got me stumped. I want to make both ranged and melee combat viable, or as close to equally viable. Though, with the existence of guns, I'm not sure anyone would want to use the characters' melee weapons. I know it's possible to make guns and melee weapons fulfill different functions, like guns only able to attack one target at a time (except shotguns) with varying fire rates, while most melee weapons are able to attack faster than guns but with a much shorter range, or able to attack multiple targets at once within its hitbox but much slower than guns. For example, make the melee weapon have a large hitbox and able to apply some non elemental Damage over Time but with low damage itself and, when charged, able to pull an enemy in front of the character , and the gun a quad barreled shotgun that delivers massive damage at close range but with long cooldown. Would that be a viable option to make both melee and guns equally viable, and are there other ways to do it?"} {"_id": 4, "text": "Logarithmic spacing of FFT subbands I'm trying to do the examples within the GameDev.net Beat Detection article ( http archive.gamedev.net archive reference programming features beatdetection index.html ) I have no issue with performing a FFT and getting the frequency data and doing most of the article. I'm running into trouble though in the section 2.B, Enhancements and beat decision factors. in this section the author gives 3 equations numbered R10 R12 to be used to determine how many bins go into each subband R10 Linear increase of the width of the subband with its index R11 We can choose for example the width of the first subband R12 The sum of all the widths must not exceed 1024 He says the following in the article \"Once you have equations (R11) and (R12) it is fairly easy to extract 'a' and 'b', and thus to find the law of the 'wi'. This calculus of 'a' and 'b' must be made manually and 'a' and 'b' defined as constants in the source indeed they do not vary during the song.\" However, I cannot seem to understand how these values are calculated...I'm probably missing something simple, but learning fourier analysis in a couple of weeks has left me Decimated in Mind and I cannot seem to see it."} {"_id": 4, "text": "Professional game design documents Possible Duplicate How should I structure a design document? I'm planning to apply for a game designer position at a big company. But the problem is, according to my CV, I'm not fit for being a game designer. (I'm a programmer). But, I don't like this and still would like to try my chances. Even though I'm a programmer, I have lots of ideas which I can put on paper in any detail depth imaginable. (It's not like \"bro, I have this cool game idea in which you fly a spaceship and you see these scary monsters just like in ....\", I can really make it professional). To be able to achieve this, I want to send a game design with my application, written in proper way, that will make it easy for them to accept me. Question is, what is the proper format for game design documents? Is there a template? What is the detail level? Where can I find a final game design document for a released professional game?"} {"_id": 4, "text": "How would you code an AI engine to allow communication in any programming language? I developed a two player iPhone board game. Computer players (AI) can either be local (in the game code) or remote running on a server. In the 2nd case, both client and server code are coded in Lua. On the server the actual AI code is separate from the TCP socket code and coroutine code (which spawns a separate instance of AI for each connecting client). I want to be able to further isolate the AI code so that that part can be a module coded by anyone in their language of choice. How can I do this? What tecniques technology would enable communication between the Lua TCP socket coroutine code and the AI module?"} {"_id": 4, "text": "Make a place or city feel crowded in procedural generated worlds I have thought about this while thinking about a game concept, but it should be applicable to many game types. Imagine an RPG or something else with an open world. Normally you would want to populate your world to make it feel alive and allow for interaction with NPCs in any form (talk, steal from, kill.. whatever). Now, what if you don't have the option to fill it with NPCs or similar. My example would be a procedural generated RPG world where you want to enter a house filled with people or even a city. It would be strange for none of the NPCs to talk to you. Another example might be a space station your ship is docking to. There might be only one or two NPCs you are able to talk to, but the space station could be steaming with other people, but you might not acces them somehow. Sure, one possibility would be to have procedural generate NPCs with random messages as well, but depending on the size of the city and or the amount of NPCs you would need a lot of NPCs with different messages. And then it would be easily possible to have to NPCs with identical messages. The other problem would be that you would end up with to many NPCs, that make the place feel overfilled instead of just crowded. I image that a hard number or relation for space to NPCs is impossible to pinpoint, but you surely get my point. So, my question is, what other possibilities are there to make a city place feel crowded? Maybe with NPCs, or maybe even without?"} {"_id": 4, "text": "How to desing an RPG system with regard to PVP When you design a RPG system focused on PVE, one usually goes \"mob of level X has Y hp and Z damage\". How about when we do PVP with multiple classes? Lets say we go Diablo, so we have STR DEX INT VIT, how do you balance those between classes? Do I say I want a fight to last 10 rounds on average (lets assume its turn based) barb starts with 300 hp, demon hunter 250 hp, wizard 200 hp And now try to manipulate DPS health using stats skills so it matches the \"10 round on average\" by giving mage a mana shield an a lil bit more damage per fireball than barbarians melee attack? How would You approach this?"} {"_id": 4, "text": "How can I find the valid words in a grid of characters? I am creating a game similar to Tetris, with two main differences the screen already begins filled with tiles (like in Puzzle Quest for Nintendo DS and PC) and each individual tile has a letter in it. The player's objective is to eliminate tiles by forming valid words with them. Words are formed by placing letters next to each other, in any direction, except diagonally. The player can move an entire row of tiles to the left or to the right or an entire column of tiles up or down, for as many spaces as he desires (if the movement of a row column surpasses the limits of the board, the letter that crosses the limit will \"cycle\", appearing at the other end of the row column). After the player's action, the game should check the entire board to look for valid words and remove the letters that form those words from the board. The letters above those that were removed will fall down in the place of those letters that were removed and new letters will drop from the top of the screen until the board is filled up again. I have already written a linear algorithm that, given a sequence of characters, determines if it is a valid english word. The problem I am having is how can I check for valid words on the board? Is brute force the only way? Testing all possible combinations from the board to see if they are valid is very slow, even for a small (5x5) board. Any help will be very appreciated, thanks!"} {"_id": 4, "text": "Using the MVC pattern in games I saw a lot oft tutorials about the mvc pattern, but always it was only a small example Situation explained. There was always only one model, one controller and one view. But what if I have a lot oft models with complex logic, I cant put all the rendering code in one view and all the logic code in one controller. How I split all in smaller pieces, because the models logic depends in each other(for example collision). Know someone a good tutorial, or example game that explains this pattern in advanced games?"} {"_id": 4, "text": "Things that make a game more interesting for kids What makes a game more interesting or fun to play for children ages 8 to 14 ? Does the age of the consumer play an important role in his her interest in the game? What can I put in a game to make it more fun, educational, and interesting to play?"} {"_id": 4, "text": "Multiplayer matchmaking algorithm I'm building a game in which there are tournaments. During the tournaments we want players to play against each other in an efficient way. What I'm looking for is a generic algorithm that will match players together in an optimal way in order to Have the lowest amount of games possible Be reasonably sure that after all games are played, the highest ranked player is the best Tricky part Games can have 2, 3 or 4 players in a death match depending on the tournament. Tournaments have two or more players, no other constraints. Does such an algorithm exist? Note For the ranking, I will probably be using an ELO based algorithm (unless you have a better suggestion)."} {"_id": 4, "text": "Endless runner player detect player drop Starting to learn write my first game using Corona Solar2d game engine. And have a very basic question on how do people handle a such this situation which I assume should be common to any game engine. I am trying to build an endless runner game, where I have an uneven terrain player have to jump between different height platforms while moving forward. Here is the closest to what I have in mind. https youtu.be qWz0vOywFdY How do I find if the player has fallen between the the two platforms while jumping ?"} {"_id": 4, "text": "Game ideas for a platformer I have created a platformer which currently has the features listed below. I would greatly appreciate any further ideas which I could implement! (I don't play a lot of games which is why I require help) Walking jumping movement player can shoot lasers enemies also walk, fly, and shoot lasers water (you can swim in this) mud (slows you down on contact, and stops you from jumping) ladders damage when falling from a large height, unless falling into water moving platforms springboards (jumping on them shoot you into the air) growing platforms (allow you to reach new places) key and door system gem and coin collection system teleporting turrets"} {"_id": 4, "text": "How to make a simple score system for my game? I'm making a simple game and I can't seem to impliment a simple score system. As the object moves 10 units forward the score should increase by 10. My issue is that when I turn the object around and move backwards the score decreases."} {"_id": 4, "text": "What is the best way to manage 'state' in Phaser? I have heard that this is not the best way to manage state in phaser var game new Phaser.Game(800, 600, Phaser.CANVAS,'YourGameName') game.state.add(\"Boot\", Boot) game.state.add(\"Preload\", Preload) game.state.add(\"MainMenu\", mainMenu) game.state.add(\"Play\", Play) game.state.add(\"GameOver\", GameOver) game.state.start(\"Boot\") so what is the best way to do it. I am newbie in Phaser game development."} {"_id": 4, "text": "What is an alternative to scratch damage to solve combat deadlocking? Scratch damage is a game mechanic whereby any successful attack always does some minimal amount of damage. This is often used in subtractive combat systems, where the defense is subtracted directly from the damage done by an attacker. Therefore, the target will always take some minimal damage. The downside of such a system, for me at least, is that it's a hack. It takes a simple formula like Damage Attack Defense and turns it into a (slightly) more complex one Damage max(Attack Defense, 1). I also feel that it detracts from a player's skill in developing their character etc. No matter how many defense bonuses they get, every attack will do some small damage. So why get your defense so high, if it won't mean anything? Furthermore, this now encourages the use of larger numbers for Hp and damage, so that the scratch damage is truly negligable. After all, if the minimum damage is 1, and you only have 10 Hp, that's still 10 of your health. Even with 20 Hp, that's 5 . And I would rather avoid using larger numbers like that unless it's absolutely necessary. However, there is one very important upside of scratch damage it solves the deadlock problem. Deadlock happens when neither side is able to do damage to the other. If you invest all of your resources into defense, and few into attack, then your character may not take damage, but they won't be able to deal very much either. Thus, you could come upon an encounter where neither side will be able to inflict damage, so battle continues forever. This is especially if you don't have random mechanics like critical hits (which I also hate). At least with scratch damage, someone will eventually win. It may only be the one with the most Hp or highest number of attacks, but the battle will end. So I like having a combat system where there will always be an outcome. But I don't like having scratch damage. What are my alternatives? Alternatives that don't involve rolling random numbers I want combat to be 100 deterministic. If the same battle is fought, the exact same outcome must happen. If you want specifics on the gameplay, think in terms of turn based combat, where battle can be automated (you design your forces, then pit them against others)."} {"_id": 4, "text": "Setting up CCMenu for Cocos2d I am very new to Cocos2d programming and was thinking to build up my first app. I learnt some basics related to CCMenu and CCMenuItems. But I was wondering whether I could provide animations in such a way that every CCMenuItem would animate first and then appear in the CCMenu. Will that be possible in Cocos2d? Can I get some tutorials or samples regarding this? Thanks."} {"_id": 4, "text": "How to implement an experience system? I'm currently writing a small game that is based on earning experience when killing enemies. As usual, each level requires more experience gain than the level before, and on higher levels, killing enemies awards more experience. But I have a problem balancing this system. Are there any prebuilt algorithms that help to calculate how the experience curve required for each level should look like? And how much experience an average enemy on a specific level should provide?"} {"_id": 4, "text": "Am I allowed to use a real life celebrity in a game? In previous questions many users asked whether or not an athlete can be used in a game. Yet the answer was no due to multiple copyright their images and names had. However anyone can use a politician's name and physical appearance due to the fact that they are \"public figures\" (example Obama). In this case, I want to use famous game developers such as Kojima and Gabe Newell in a game. Am I allowed to use them? or should I make references to them using distinct names (I.E. Lord Gaben). How can I find out whether or not a person is a \"public figure\" and if their appearance name is protected?."} {"_id": 4, "text": "Progression in a Sandbox Game (to xp or not to xp) I'd like to know the strengths and weaknesses of different progression methods through a game (or a part of a game), where they're suited best, and where they should never appear. I have several subsystems a player can progress through in a project I'm working on and I'd like to be able to work out if any of them would benefit from tallying xp. Not sure why this is on hold, I'm asking about the concrete merits of things not simply asking everyone for their favourite?? At the moment the player's character becomes more powerful by equipping better and better gear as they progress through randgen levels however they like, but are given clear indication that going in a particular direction will increase difficulty and the quality of items. I'm not sure in what circumstances I would add in xp for fighting monsters, or which I'd have the monsters drop good gear, or parts to make good gear out of. On top of that I have a magic system and a crafting system that I'm considering progressing though with xp but I wouldn't want to implement it if the side effects don't suit the rest of the game. As far as I know games usually progress in the following ways, often in combination Level by Level Like in old school Mario, you go through a sequence of levels which become more difficult and require you to master the basic techniques of game play. Power by Power You gain new abilities which makes it possible to access more and more difficult content. Metroid comes to mind for this. Xp Growth Your stats increase every level so you can fight the harder mobs in further content. You may or may not be able to choose where your stats go. Xp Talent Tree You get points to put into learning new skills, often from increasingly better pools of skills. Item by Item Equipment determines what content can be accessed next, either because the item unlocks something (including methods of transportation), or it increases player abilities such that they can survive certain areas. The distinct thing about items is that they can be removed from a player at pretty much any time. A grappling hook that can't be removed is a Power, not an Item. Quest by Quest Like Level by Level, only what triggers the newer content isn't getting to the end of a stage, it's the completing the requirements of a quest (explicitly stated or not). Zelda would be an example of a game that does both LbyL and QbyQ. Each dungeon is a level and between levels you have to do a bunch of little quests to unlock the next level. Score You just rack up points like in pinball, it doesn't really have an effect on the game. If you have a clear idea of the underlying purpose of these or others, I'd like to hear it! At the moment I only know that these systems exist, but only vaguely what they're for. As an aside, I'm also interested in your thoughts on how to display progression to a player. When is it best to give them numbers, if ever? Are visual demonstrable displays preferred for certain things? What is the function of doing it one way or another?"} {"_id": 4, "text": "Conceptual question regarding Belief Desire Intent agent I've been researching the Belief Desire Intent model and the way they used it in the original Black and White Game(which is the same, but they also defined decision trees as opinions). I have a question about the distinction between opinion and belief. From what I understand, beliefs are linked lists in the form of attribute value. So let's say a tree would be something like Condition Inanimate Type Plant So let's say I try to apply the command cut on it and the npc cuts down the tree in like 2 turns, by doing 50 damage each turn. So the newly formed belief is that the hp of a that tree is more than 50. From what I understand, that this is now a newly formed belief, so the new belief about the tree would be Condition Inanimate Health 50 Type Plant What about the fact that the npc now knows it takes 2 turns to cut down the tree, is that now a newly formed belief or an opinion? If it's not, what kind of opinion could be formed out of that? Help from anyone who's dealt with this would be appreciated as I'm finding it hard to find open source code examples of this."} {"_id": 4, "text": "Repetition of move in Draughts game I am having a little problem in my draughts game. Lets say my red piece (moving through AI) has arrived at the border of black pieces and now it has become a king, lets assume it is at index 2. Now when its next AI's turn, this piece moves to index 5, thats ok. But on next turn it moves to index 2 and then this transition between index 2 and 5 continues in every turn. I can't figure out whats wrong. I have revised my generate moves() and it seems ok. Any idea what can be wrong? My evaluation function is as follows public double Evaluation(int type, int aBoard ) double reds, blacks, ret 0.0 int loop for(reds blacks loop 0 loop lt 32 loop ) switch(aBoard loop ) case 2 redKingType reds 1 case 0 redType reds 1 break case 3 blackKingType blacks 1 case 1 blackType blacks 1 break default break switch(type) case 0 redType case 2 redKingType if(reds 0) return 0.0 if(blacks 0) return 24.0 ret reds blacks return ret case 1 blackType case 3 blackKingType if(reds 0) return 24.0 if(blacks 0) return 0.0 ret blacks reds return ret default break return ret Note I know this a very simple evaluation function ,but please consider the fact that I am doing this for the first time, under a hard deadline."} {"_id": 4, "text": "How can I refactor \"attack cooldown\" into \"attack speed\"? I'm building a game where the player's character can attack bad guys and vice versa. I built this with the concept of an \"attack cooldown\" because I don't want units to be able to attack each other every single frame. I want there to be some delay between attacks. Here's roughly how it works if unit.ticksUntilAttack lt 0 unit.attack(target) unit.ticksUntilAttack unit.attackCooldown unit.ticksUntilAttack unit.ticksUntilAttack 1 I also have a page where I show the character's stats and list this as \"Attack Cooldown\". I was showing my friend and he said, \"Why don't you rename that to 'Attack Speed'\"? I explained that it's not really the speed at which you attack because \"smaller is better\". We both agreed that \"attack speed\" is a more standard way to show this concept and that I should change things the way he suggests. The problem for me is that \"attack cooldown\" is a much more intuitive way for me to program the solution. I'm wondering if there's some \"trick\" to refactoring the current code I've got. I'm thinking something like this if unit.attackSpeedAccumulator gt SUM NEEDED TO ATTACK a constant that's the same for every unit unit.attack(target) unit.attackSpeedAccumulator 0 unit.attackSpeedAccumulator unit.attackSpeedAccumulator unit.attackSpeed Is there a smarter way to do this?"} {"_id": 4, "text": "How important is music to mobile phone (smart PDA) games? Specifically iPhone iTouch, Droids, and the new Windows Phone 7? I don't know how to quantify this, or if any research has been done. I am wondering how important the music is to the gaming and what of games come with music at all, if good music at that."} {"_id": 4, "text": "For my first 3D engine, should I go for one that is already made, or minimalistic? I've been meaning to transition from 2D games to 3D games for some time, now. I have the most experience with RTS games, so I will be doing that. On one hand, there's a lightweight renderer Irrlicht. However, considering it's a renderer and not a game engine (only basic collision, etc..) , I would have to write most of the things, myself. On the other hand, there's a full blown engine like CryEngine 3, for example. Although it is mostly complete, I would first need to understand the various parts of the engine and it's implementation enough to be able to try and transform it into an RTS engine. My question is, which would be easier for me to transition to?"} {"_id": 4, "text": "What is \"game state?\" The terminology \"game state\" is a bit vague to me. Could anybody clarify what is included in the game state, please? Is it a state of all the variables and objects within the game at particular moment?"} {"_id": 5, "text": "Why does my world generation code perform poorly on large inputs? I'm writing some code to procedurally generate some islands in real time. The idea is to choose some points for each chunk, and for each tile calculate the distance from those points, then combine it with a Perlin Noise to decide if it will be water or land. Anyway here's the code local function number() local n math.random() if n lt .4 then return 0 elseif n lt .8 then return 1 end return 2 end Just a custom weighted random function, used to choose how many points will be in each chunk. chunks setmetatable( , index function(tab, x) local xtab setmetatable( , index function(xtab, y) local xs, ys x 32, y 32 local islands for i 1, number() do islands i x math.random(xs, xs 31), y math.random(ys, ys 31), r math.random(16, 32) end xtab y islands return islands end ) tab x xtab return xtab end ) This block just initializes the chunks table, setting its metatable so that if a non existing chunk is being called, that chunk gets initialized by choosing a number of points the chunk will contain, and for each point choose its position inside the chunk and its range. However here's the buggy code function generatechunk(x, y) local xs, ys x 32, y 32 for xm xs, xs 31 do for ym ys, ys 31 do for xc x 1, x 1 do for yc y 1, y 1 do local points chunks xc yc for p 1, points do local po points p local d math.max(0, math.min(math.sqrt((po.x xm) 2 (po.y ym) 2) po.r, 1)) end end end end end end It isn't even completed yet. Basically what it should do is choosing for each tile if it will be sea or land by combining the Perlin Noise value and the influences of the points of the chunks around its chunk. But here's the bug if I call (for testing) generatechunk(n, n) for n lt 0, it executes in little to no time. But as n increases I get results of about n seconds of execution. Why is it?"} {"_id": 5, "text": "How does one generate mountains out of a Fourier transform? I am watching this IGN video of No Man's Sky in which the founder programmer of this game talks about how different is his game from other games. Here he talks about how mathematical equations instead of art is used to render graphic of planets and animals and even their behavior. Then he says that instead of seeing mountains he sees only equation like Fourier transform. I have no knowledge about game development and its intricacies, but I'm curious how one might use a Fourier transform or similar mathematical operation to generate terrain without art?"} {"_id": 5, "text": "Perlin Noise Variations Currently I'm making a voxel survival game. About a month ago I embarked on procedurally generating terrain using Perlin noise. I understand how to use and apply it for the most part. However I do not understand how to vary terrain structure. Let me say that in a way you probably can understand because \"me no grammar good\". By changing frequency and amplitude I know I can change the resulting terrain, varying it from rolling hills to jagged peaks. However the end result will always be the same either never ending hills or never ending mountains. I don't understand really how I would mix those two \"terrain structures\" together to get area's of hills and area's of mountains."} {"_id": 5, "text": "Realistic planetary terrain generation with weights I need terrain generation for a planet. The planet will be divided up into several hundred hexes, and I need it to be realistic and based on weights. I have dabbled in terrain generation before, but nothing like this. So I figure it would be a good idea to ask the community for answers, recommended articles or the like. By realistic, I mean not just random hexes, but continent shaped things with a few islands. More desert around the equator and more ice around the poles. I also have two weights I need to base it around ice percentage and water percentage. That means that around XX of the planet will need to be water. Does anyone have any advice or places to start? Generating arbitrary terrain is easy, but something a bit more \"organic\" like this seems rather difficult. It also needs to be seamless. Should be obvious since it's a planet, but no harm in pointing it out."} {"_id": 5, "text": "Procedurally generating non tile based top down 2d game worlds I ve been fascinated by procedural generation for over two years now. I have played around with many types of noise generation and even wrote some myself. I ve been looking into water erosion and procedurally generated biomes and during this time I ve managed to build some nifty little map generators. Something that has always escaped me, however was generating a procedural map that is not tile based . So far, all the procedural map generators I have built relied on one axiom the map is represented as a 2d matrix containing some sort of information about the terrain that is to be found there. This means that I, by definition, can t build anything that is not tile based. And this is why I come here asking for your help. I am curious about how one could render a procedurally generated map in a non tile based fashion. My end result is the image I posted. The solution that immediately jumped to my mind is drawing each end every pixel individually, thus making the map look essentially non tile based. This, however would require enormous memory and is unfeasible. So I am turning to the masters how can I procedurally generate (and more importantly render) such a map? How would I go about representing the sprites to be drawn? Where do I even get started? This feat is so much out of my grasp that I do not even understand where I should be looking Note I know about marching squares and wang tiles. These approaches are however not something I m fond of because of the huge workload that would go into drawing the resources. I am looking for something more in the realm of algorithms Thank you!"} {"_id": 5, "text": "Letter game board creation I currently have a game concept similar to the mobile app Alphabetty where you are given a grid of letters and are tasked with spelling words. When you use a letter in a word, it disappears and new letters fall in from the top to replace the used ones. I have been playing around with ways of making the new letter spawning more \"interesting\" so that players can get more complex words. I tried making it so each letter spawns based on how common it is, kind of like scrabble but didn't get great results. I have also tried representing each grid tile as a Boggle die which re rolls each time its used, which was better but far from perfect. The main issues are Vowels and consonants often end up grouped together, creating unusable areas on the board. This also goes for letters of the same type (i.e. 3 s letters side by side) With Boggle dice it's very hard to spell words like \"Blizzard\" as only 1 or 2 dice have rare letters such as z, v, and k etc For the sake of a game mode, I need to be able to seed the grid with words of my choosing slowly (i.e. as new letters fall in) so that players have the ability to spell these special words if they are particularly careful Are there any solutions, theories or discussions out there that could help? Thanks!"} {"_id": 5, "text": "2d Procedural universe generation I want to create a flat universe, where at first the whole universe is blank. That would be represented by a parallax scrolling nebula background image. What I want to do is represent the planets as disc shaped objects in the universe. They can be of various sizes. The inside of the discs will consist of a landmass, then outside that will be a body of water and after that air. what would be the best way to go about creating those tiles procedurally as for example the air would consist of various gases and the land of various minerals and resources. My first thought is to create texture images and then stamp out the circles out of those textures, but problem is that those textures would have to wrap horizontal and vertically. Is there a fully procedural way of doing this?"} {"_id": 5, "text": "How can I simulate a randomly generated universe? Possible Duplicate How to generate a universe? Were would I start looking if I wanted to develop an engine to simulate space at random. Things like black holes, galaxies at distance and moving stars, asteroids and so on? I would like to know if anyone has some good tips for this, or if there is some information online?"} {"_id": 5, "text": "Combining Minecraft and Dwarf Fortress Simulating autoplay in a pseudo infinite procedurally generated world? One of the interesting things about Dwarf Fortress (and other procedurally generated games like Civilization) is that the game simulates multiple AI factions interacting with each other over time (what might be termed \"autoplay\") to generate an evolving world which changes over time, even whilst the player is playing the game. On the other hand, simulating all the factions simultaneously is surely going to become a bottleneck as the map grows. With a bigger map and more factions, the performance requirements become exorbitant. Minecraft gets around this problem by simply storing the inactive chunk in memory as is as soon as the player leaves the area. The minecraft world is a static, never changing place. When a player comes back from a trip, the chunk is exactly as he left it. No world evolution occurs. Everything is always the same. The most straightforward approach to this, which is to just to make chunks remain loaded in memory even after the player is no longer in them, has the same performance issues as mentioned earlier as the player moves across thousands of blocks, you will sooner or later run into computation limits. Moreover, this does not solve the general problem of faction simulation factions can expand or contract through many chunks, whereas keeping one chunk loaded in memory would not affect its neighboring chunks, so that doesn't quite achieve the same effect as autoplay. The \"solution\" that I thought of is to come up with a closed form formula that simulates autoplay somehow. That is, a function f(time,coordinates), such that given the time and and coordinates of a block, will tell you what state that block should be in. The problem with this is that this assumes a truly predeterministic world evolution, in which players have control over only their local chunk and no others. In other words, no butterfly effect. Furthermore, when a player leaves a chunk, he has made some changes to it, but the function cannot take those changes into account when computing the state of the block the next time the player enters it, in other words all changes that the player made to the block are lost as soon as he leaves. This is obviously not ideal. Am I asking for something impossible?"} {"_id": 5, "text": "Workflow for creating spherical heightmaps I'm wondering how I can create a spherical heightmap. In my ideal workflow, you'd see a 3D sphere that you can edit using procedural terrain techniques (like World Creator) and that spherical terrain can be exported into six seamless images based on what layout you want your images to fold up into a cube in game to create your planet. Another option would be if you can at least tell the program you want specific images to tile with other images, such as the designated 'front, right, back, left' images tile with each other and the 'up, down' images seamlessly. Specifically, I'm making planets for a game that wraps six images into a cube and 'inflates' them into a planetary terrain. I've made a few basic heightmap sets in a program called Scape, and flipped them so at least four of the images mirror each other, then I edited the interior of those maps to all be different so the landscape isn't repetitive. However, manually editing the top and bottom maps is very daunting to get perfect, and I'm creating a dozen or more planets. I'd like to know how to make 'front, right, back, left' images tile with 'up and down' images and I can edit the interiors of the images in a 3D program of choice. I've been directed to this site from search queries many times, but I'm a newbie to all things code so I have no clue how to use things such as the Diamond Square method or any algorithms to achieve seamless textures (what program do you actually use, literally a python script you write in Notepad or something?)."} {"_id": 5, "text": "How to make more jagged terrain I need some help with some terrain I'm working on. I'm developing a plugin for Minecraft, but these concepts will apply to any game with terrain. I am using Simplex noise to generate cavern like terrain. I am using the power of the noise to generate hills that look like this As you can probably tell, it inst looking very cavern like. What can I do to improve this terrain?"} {"_id": 5, "text": "Basic Random Tile Map Generation Currently I've got a map like this It's pretty simple but what I want is that area of tiles to be random, with the number of tiles present being random (Within a minimum and maximum amount of tiles of course) and the positions of the tiles being random (but still all connected to each other), but I'm not exactly sure how I should go about implementing that. I'm sort of looking for a system that will generate random sections of tiles, a bunch of tiles within a group at random positions around the screen with all these sections being connected to each other via a larger section of tiles. Like the example shown in this perfect drawing I've quickly done Each square would be a group of tiles, they're all of different shapes and sizes but all connected together via another large (or small) group of tiles in the middle. I have looked into grid map generation before making this post but all the information I found would tend to go over more advanced map generation methods that have multiple layers which is not really what I need for my game so I was wondering if someone would possibly be able to advice me on what the best method would be to do this? I'd very much appreciate it."} {"_id": 5, "text": "What GPU culling techniques are appropriate for voxel spheres other than octrees? I'm creating a dynamic smooth voxel based world in the shape of a sphere. Right now my current approach is to spherize a cube, generate voxel terrain on each of the six patches, and then use octrees to cull the data further. Octree's are best served with cubes. Is there a better system for storing accessing data in a sphere? I've heard some talk of Octree's not being the best way to store voxel data, even for cube worlds. How can this be? What would be better? A Hash Table? Surely multidimensional arrays wouldn't be faster? Perhaps it's just more of a design decision than performance? As in, maybe someone didn't like chunks popping in so they would rather load individual rows and columns? If it matters, I'm probably going to keep relevant geometry in GPU memory and stream in the surrounding area over time as the player gets closer to it from main memory. I bring this up because I'm really not sure if GPU memory benefits from any particular structure. All I really know is that the parallel powers of the GPU are, well, unparalleled (I had to). How can I tap into that?"} {"_id": 5, "text": "Which parts to draw in an infinite world? I have an infinite world (from Perlin Noise). The world is generated in sectors that are that are big cubes (each with a random colour, in the image above my sectors are 10x10x10). I'm currently putting the sectors in a hash table tagged by their top left front corner coordinate. I can loop through all the sectors I've already generated and see if they intersect the frustum. But how can I compute instead the sectors that I haven't generated but are visible and need generating on demand? Even if I have an octree or some other spatial index, I need to compute the sectors that are visible inside the frustum rather than those I've already generated."} {"_id": 5, "text": "uv tiling and offset for uvs not min max 0 1 For the purpose of the question, a unit 1 meter. So, I have a triangle strip that is 4x8 meters (for argument's sake it is procedurally generated by player). I also have a texture which is 512x512px. For normal UV mapping, I just make U 0 or 1 (depending on the side of the strip), and I make V a value normalized between 0 and 1, based on the distance \"traveled\" along the strip. Then I set tiling based on the distance, and the texture. In this case, the tiling would be 2 along Y, since the texture is a square. I am having trouble dealing with a scenario where I do NOT use UV 0 to 1 though. I only want to sample the \"middle\" of the texture,. such that the min max of the UV coords are 0.0x0.25 to 1.0x0.75. When I try to make this work, I notice that as I lay my strip (done by player in game mesh updates continually during placement), the texture moves along the strip. I figure I need to adjust the offset, but I am having difficulty figuring out the formula to use to determine what the offset should be based on the tiling (which in turn is based on the length of the strip). when the tiling is 1, there is no problem with the offset (0). A tiling of 3 is also correct with no offset. Same for tiling 5, 7, etc. Odd numbers basically. When the tiling is an even number though, or a fractional number, offset 0 no longer works. On top of that, the needed offset seems to change based on the tiling. How would one go about calculating this? In addition, if I lay two of these strips end to end, and I want the texture to be continuous how would one calculate the offset based on the tiling offset of the previous strip behind it?"} {"_id": 5, "text": "1D Perlin Noise Game in Unity I'm working on a 2D side scrolling game in the Unity engine. I am using the 1 Dimensional Perlin Noise function and using pseudo code. I can't use two links so I'll provide a link to imgur with the images and the links in numerical order. First link in imgur links to the pseudo code implementation of perlin noise I am using. My implementation so far is showing good results. Here is a picture This image uses the values Persistance 0.7 Octaves 4 From the first article I linked, it states Now, you'll want several different random number generators, so I suggest making several copies of the above code, but use slightly different numbers. Those big scarey looking numbers are all prime numbers, so you could just use some other prime numbers of a similar size. This block of text is referring to this part of code which is an Integer noise function float Noise (int x) x (x lt lt 13) x return (float)(1.0 ((x (x x 15731 789221) 1376312589) amp 0x7fffffff) 1073741824.0) Another site I found the author adjusts the Integer noise function from discrete to continuous (allowing the range not to be limited). I've made this change although I am not sure if my implementation of both links I've provided is entirely correct. The results are promising but when you change these variables values to Persistence 1 Octaves 8 the terrain starts to have little gaps at the bottom like so I am not quite sure how to fix this, I know lowering the persistence provides smoother results resolving this issue but that makes the terrain's amplitude rather low for a side scrolling platformer. Here is the complete code void Start () objectArray new GameObject width, height for (int i 0 i lt width i ) float x PerlinNoise 1D (i, persistances, octaves) for (int j 0 j lt height j ) objectArray i,j (GameObject)Instantiate (gameobject, new Vector3 (i, j x, 0), Quaternion.identity) float Noise(int x) x (x lt lt 13) x return (float)(1.0 ((x (x x 15731 789221) 1376312589) amp 0x7fffffff) 1073741824.0) float CoherentNoise (int x) int intX (int)(Mathf.Floor(x)) float n0 Noise (intX) float n1 Noise (intX 1) float weight x Mathf.Floor (x) float noise Mathf.Lerp (n0, n1, weight) return noise float SmoothedNoise (int x) return CoherentNoise (x) 2 CoherentNoise (x 1) 4 CoherentNoise (x 1) 4 float InterpolatedNoise (float x) int integer X (int)x float fractional X x integer X float v1 SmoothedNoise (integer X) float v2 SmoothedNoise (integer X 1) return Cosine Interpolate (v1, v2, fractional X) float Cosine Interpolate (float a, float b, float x) float ft x (float)Mathf.PI float f (float) ((1 Mathf.Cos ((ft))) .5) return a (1 f) b f float PerlinNoise 1D (float x, float persistance, int octaves) float total 0 float p persistance int n octaves 1 for (int i 0 i lt n i ) float frequency (float)Mathf.Pow (2, i) float amplitude Mathf.Pow (p, i) total InterpolatedNoise (x frequency) amplitude return total Thank you for your help and time."} {"_id": 5, "text": "How to display procedurally created rooms as a schematic map? In most games, a map can be generated by essentially doing a \"top down\" view of the specific area. This will accurately show the size and positioning of any rooms, as well as how they connect.There might be special icons for stairs, doors, etc. In a game I am working on I am intentionally keeping some concepts rather loose. The map is not there so much to display distance between rooms or the relative size of rooms between each other, but just to most clearly show the connections between the rooms. The easiest real life example I can show is an electronic schematic. Now, I only know some of the symbols on there, but in this case you might just substitute them for various rooms. You can easily imagine then that this layout could have many actual physical representations. A connection could be a door, but it could also be stairs or even an abstract \"border\" between two regions. I currently generate \"rooms\", without size or even position. I then assign them connections. Not exactly \"random\" connections but I am still playing with the generation so I don't have any hard rules at this time. The task I am having a difficult time with is How do I take these rooms with connections and arrange them in such a way to maximize clarity of which rooms connect to which?"} {"_id": 5, "text": "Quad sphere subdivision algorithm I like to generate some planets like Kerbal Space Program does. By some videos of the developers I know that they use a quadsphere, which consists of six entities as a minimum. These are all plane meshes, which get subdivided the closer you get. This allows a ground to orbit level of detail. However, I have some problems understanding this subdivision algorithm Since I have six separate meshes, how do I know where I have to subdivide them, if they are all separate? If I always just subdivide the quad the camera is over and I end up with something like this even though I want something like . So how can I ensure a sense full 2 1 subdivision with neighbour quads?"} {"_id": 5, "text": "Derivatives usage in FBM core So I learned now about derivatives and fbm, but can not figure out the effect of this code example (credits https www.iquilezles.org www articles morenoise morenoise.htm, bottom of page) const mat2 m mat2(0.8, 0.6,0.6,0.8) float terrain( in vec2 p ) float a 0.0 float b 1.0 vec2 d vec2(0.0) for( int i 0 i lt 15 i ) vec3 n noised(p) d n.yz a b n.x (1.0 dot(d,d)) b 0.5 p m p 2.0 return a What effect does (1.0 dot(d,d))? As the slope is more it flattens the fbm sum?"} {"_id": 5, "text": "Realistic planetary terrain generation with weights I need terrain generation for a planet. The planet will be divided up into several hundred hexes, and I need it to be realistic and based on weights. I have dabbled in terrain generation before, but nothing like this. So I figure it would be a good idea to ask the community for answers, recommended articles or the like. By realistic, I mean not just random hexes, but continent shaped things with a few islands. More desert around the equator and more ice around the poles. I also have two weights I need to base it around ice percentage and water percentage. That means that around XX of the planet will need to be water. Does anyone have any advice or places to start? Generating arbitrary terrain is easy, but something a bit more \"organic\" like this seems rather difficult. It also needs to be seamless. Should be obvious since it's a planet, but no harm in pointing it out."} {"_id": 5, "text": "Rule based procedural terrain generation How one generates procedural terrain is pretty straight forward. But once you setup your terrain you don't really have a fine level of control where which details will go. One solution I can think of is to store rules as functions, i.e. Square, circle, etc., which will override rules in the area. For example, in mountains terrain we could place a function which will make them flat or terraced. What I have trouble figuring out is how to store those functions (assuming terrains can be in principle infinite or at least planetary scale). Should they be placed within existing coordinate system, or stored locally to terrain ? I seen something like that done in Star Wars Galaxies, but it's really hard to find any details about implementation of system."} {"_id": 5, "text": "How can we generate 3D architecture in a racing game's background procedurally with respect similar to the real world? In the last few days, I jumped into searching is there a conventional convenient way to build 3D architecture quickly, most likely by some accessory software like CityEngine, BIGEMAP, or google maps' Maps SDK for Unity. However, I couldn't figure out the most suitable solution that typically suits the requirement of quot generate 3D architecture models by the racing road which is referencing the real world map quot , or just simply quot build a massive amount of 3D architecture models quot , efficiently and handily. I want to achieve buildings similar to those seen in Need For Speed and Asphalt. Their buildings in the scene are quite outstanding to me. How can I generate buildings similar to this?"} {"_id": 5, "text": "Generating a town layout in a grid I want to generate a town layout in a square grid (rendered isometrically, but that doesn't matter) using the following elements 2x2 Houses Roads, 1 unit wide Canals, 1 unit wide Sample layout I always have a specific number of houses, and as many roads and canals as necessary to connect them all. The houses need to have two pieces of road in front of their front door (which is always pointing to the right) It would be nice to have fields of grass (emptiness) inbetween. Is there a ready made algorithm for this? If not, what direction should I be thinking of to implement this?"} {"_id": 5, "text": "How can you use Fractals to perturb an image? I've been playing around with Procedurally Generated World. I've so far managed to create the Height Map, and a translate map, but now i'm attempting to create Caves, The main idea is to use another Noise map, with values being either 0 or 1, and multiply it with the Height Map. I've managed to achieve this This is currently described with a float Width, Height , which has value 0 for those points (x,y) such that (x,y) is black, or 1, for those which (x,y) is white. I want to apply some fractal to this to achieve this However, i have no idea how to do this! (I also apologize for any grammatical errors. I haven't slept in like 18 hours and i can't think straight)"} {"_id": 5, "text": "How can I generate an infinite procedural road? I'm currently trying to make a game where the player races others along an infinite, more or less straight, road. By \"more or less straight\", I mean that the road goes straight ahead (the player can't turn their vehicle to face left or right), but there are bends in the road for them to pass through, as if they were switching from one lane to another on a highway. There will also be different \"areas\" to race through (all on the same road), for example, deserts, jungles and over water. And, finally, there will be gaps in the road for the player to jump over, as well as checkpoints every so often. Starting with a seed, how can I generate the road ahead of the player as they race? I can't generate the entire road in advance (obviously), but each player needs to see the same thing at the same places along the track. How can I do this?"} {"_id": 5, "text": "Where can I find code examples of different variations of Perlin noise? I have seen the PCG wiki, and it is a great resource. But a lot of the articles are very brief and it is hard to find good links on specific things. I have been searching for ways to transform my Perlin noise height maps to make ridges, rivers, and other terrain features. I also can't find any articles on how to divide up the map into different areas for calculating texture coordinates or other values specific to the game. I have only been able to find websites detailing their software that can generate the different things, but no code or explanations. Are there any good sources of code examples explanations on how to do the above mentioned with Perlin noise? PS. This should probably be a community wiki. I don't know how to make it as one though."} {"_id": 5, "text": "Generate next chunk with perlin noise I'm actually trying to generate a level with procedural generation using perlin noise. So one chunk has a size of 30x30, it's a float 2d array and at first I'm filling it with values between 0 and 1. Next step is to calculate 7 octaves and merge them. In the end I normalize the values. All this works quiet well if I only want to create one chunk but how can I create one more chunk beside my first so that they fit together smoothly?"} {"_id": 5, "text": "How can I randomly generate achievements? Novice programmer here. To challenge my self i want to create an achievement system that randomly generates achievements for me based on a set of trackable metrics within my game. To keep it as abstract as possible my game is a turn based highscore chaser. Each game has 13 turns. Each turn consists of placing 4 tiles, each tile can have an individual score which together form the turn score. There are 5 different tile types that can be individually combined to raise each tile's score differently. Each turn one of the 5 tiles gets a bonus making it worth double points. Also in each turn you can form \"hands\" similar to poker where for example two tiles of the same type next to each other are a pair, which nets a hand bonus for individual turns. Here's what my generated achievements should look like Get a turn score of 15 and create a pair using tile type x. Create a tile type y that has 5 points. Create 5 hands of type x and use tile type x or y. Get a total score of 50 without creating more than 3 hands of type x. Obviously this seems kind of complicated and i'm kind of asking myself how to create such \"complex\" achievements. Seems like i need to establish some kind of syntax that i can feed the system to produce these kinds of requirements. But i'm kind of stuck since i couldn't find any info on this issue yet. Maybe you have done something similar?"} {"_id": 5, "text": "Procedural generation of jagged peaks I would like to generate random cave type backgrounds similar to the one shown below. I doubt anything I generate will look as good as the image, but something with that feel of sharp, jagged peak should be possible. I don't have any experience in procedural generation and as such have no idea where to start.... Note I am using libGdx on Android"} {"_id": 5, "text": "Manipulating Perlin Noise I've been learning about Procedurally Generated Content lately (in particular, Perlin noise). Perlin noise works great for making things like landscapes, height maps, and stuff like that. But now I am trying to generate structures more like mountain ranges (in 2D, as 3D would be way over my head right now) or underground veins of ores. I can't manage to manipulate Perlin Noise to do this. Making a cut off point (i.e. using only the tops of the 'mountains' of a heightmap) wouldn't work, because I would get lumps of mountains veins. Any suggestions? Thanks, Numeri"} {"_id": 5, "text": "How can I randomly generate achievements? Novice programmer here. To challenge my self i want to create an achievement system that randomly generates achievements for me based on a set of trackable metrics within my game. To keep it as abstract as possible my game is a turn based highscore chaser. Each game has 13 turns. Each turn consists of placing 4 tiles, each tile can have an individual score which together form the turn score. There are 5 different tile types that can be individually combined to raise each tile's score differently. Each turn one of the 5 tiles gets a bonus making it worth double points. Also in each turn you can form \"hands\" similar to poker where for example two tiles of the same type next to each other are a pair, which nets a hand bonus for individual turns. Here's what my generated achievements should look like Get a turn score of 15 and create a pair using tile type x. Create a tile type y that has 5 points. Create 5 hands of type x and use tile type x or y. Get a total score of 50 without creating more than 3 hands of type x. Obviously this seems kind of complicated and i'm kind of asking myself how to create such \"complex\" achievements. Seems like i need to establish some kind of syntax that i can feed the system to produce these kinds of requirements. But i'm kind of stuck since i couldn't find any info on this issue yet. Maybe you have done something similar?"} {"_id": 5, "text": "Domain warping with Perlin noise I'm trying to achieve the effect from https www.iquilezles.org www articles warp warp.htm with no success. Here is the experiment http jsfiddle.net fro5y0jm 15 with canvas. Any ideas?"} {"_id": 5, "text": "How would you generate details like trees, water or caves in a 2D terrain? Yesterday I made a post about generating a 2D planet, which resulted in this I did it by subtracting a radial gradient from simplex noise (explained in my other post). Now of course thats a bit boring, what technique should I use to add details like trees, lakes or caves? Would be able to do something like this (but of course across the whole planet) I know doing it on a planet would make it a bit harder, because you would have to know if f.E. the tree is on the north of the planet or the south. To make it easier, if you want, just assume a flat 2D surface like this"} {"_id": 5, "text": "How do Minecraft know where village's buildings are if the village is not generated yet? I'm trying to understand how chunk generation works in a deep level and all the information I found does not explain how the villages are generated properly without visual glitches during generation. I mean, if you are in an area where you should see some buildings from a village, how does Minecraft know that they must be rendered? Minecraft generates villages from a main \"structure\" that probably it is not generated yet. This video explains the village's generation properly. So with that in main what should happen is that you could see builds appear from time to time when the \"village center\" of a village is generated in a new generated chunk. Here you have a visual representation of the circumstances I'm describing. The buildings inside the loaded area shouldn't be shown if the village is not generated yet The only explanation I can think about is that Minecraft generates way more chunks than the ones that are visually loaded to avoid this problem. If this what happens, what is the generation area compared to the visual loaded area?"} {"_id": 5, "text": "Procedural terrain generation is very slow I've been trying to create procedural generated 2d terrain (similar to a game like Terraria) using Simplex noise. I was able to get the noise function working, and I set up a grid of 16 by 16 tiles that uses the noise to generate the height of the terrain. The problem is that the grid generation is rather slow. I often need to wait 5 10 seconds for a somewhat small grid to generate. My code looks like this var level height of the terrain generate simplex octaves2D( largestfeature, persistance, seed) generate octaves using largestfeature for (var gy 0 gy lt global. gridheight gy ) for (var gx 0 gx lt global. gridwidth gx ) level (global. gridheight div 2) (100 get noise2D(gx 100, gy 100, octaves, frequencys, amplitudes)) get noise value at point (gx 100, gy 100) if (gy gt level) if below level global. testgrid gx,gy TILE FULL set grid position to a full tile else global. testgrid gx,gy VOID set grid position to an empty tile if (global. testgrid gx,gy TILE FULL) tilemap set(global.testmap, 1, gx, gy) This creates terrain that looks fine, it's just too slow. I want to be able to generate terrain in real time to create an infinite landscape. After doing some research, I found that I could maybe use a compute shader to have the GPU help speed up the generation, but I am not sure how to implement a compute shader in my case. Would I calculate the noise in a shader, or generate a noise map using one? Or do something else to generate the terrain faster?"} {"_id": 5, "text": "How can bays and straits be determined in a procedurally generated map? I've got a procedurally generated map using Voronoi cells, with a defined sea level and a believable height map. So far, I've been successful in labelling certain geographic features land, ocean, lakes, rivers, estuaries, confluences, mountains, and biomes. Biomes include tundra, boreal forest, grassland, and temperate forest. There are also a couple other biomes there but for my purposes they aren't important right now. I'd like to label bays, and straits next, but I'm at a loss on how to do this properly. A bay is a recessed, coastal body of water that directly connects to the ocean. A strait is a naturally formed, narrow waterway that connects two parts of the ocean. Basically, where two pieces of land almost touch and there's ocean on both sides. Also called a \"channel\". For determining features, I can loop through any feature by type like this for each (var feature Object in geography.getFeaturesByType(Geography.LAND)) loop through lands for each (var cell Cell in feature.cells) loop through cells for each (var neighbor Cell in cell.neighbors) loop through a cell's neighbors trace(neighbor.hasFeatureType(Geography.LAND))"} {"_id": 5, "text": "Using QuadTree for Procedural Generation so I've been trying to start a new project that focuses on procedural room generation similar to what is seen in Binding of Isaac. I plan to have the code use a QuadTree to help determine where rooms should be placed. Each node in the quad tree represents any of the possible 4 directions the next room can be placed. The problem is this. I'm not sure where to start when trying to implement the QTree and haven't found good resources on the topic. Most implementations of QuadTrees in a procedural generation context use them for partitioning spaces and placing rooms within the partitioned spaces. Not sure if that's what I want to achieve. I'm also unsure of weather I should be going in this direction or if there's a more optimal solution?"} {"_id": 5, "text": "Biome Transition in a Grid Borderless World I have a universe a list of \"Systems\", each with their own center, type and radius. A small part of such a universe could look like this Systems Can be very close to a different system, e.g. overlap Can be inside another, much bigger system Can be very far away from any other systems Spawn system specific entities and particles inside the system radius Have some properties like background color So far so good. However, the player can fly around freely, inside and outside of systems, in real time. How do I interpolate and determine things like the background color now, depending on camera position? E.g. if you are halfway between a green and a red system you should see a background halfway between red and green, or if you are inside a lilac system near the center and at the border of a green system you should get a mostly lilac background etc."} {"_id": 5, "text": "Which parts to draw in an infinite world? I have an infinite world (from Perlin Noise). The world is generated in sectors that are that are big cubes (each with a random colour, in the image above my sectors are 10x10x10). I'm currently putting the sectors in a hash table tagged by their top left front corner coordinate. I can loop through all the sectors I've already generated and see if they intersect the frustum. But how can I compute instead the sectors that I haven't generated but are visible and need generating on demand? Even if I have an octree or some other spatial index, I need to compute the sectors that are visible inside the frustum rather than those I've already generated."} {"_id": 5, "text": "Continents with Simplex noise How do I turn Simplex noise like into something like or The noise has too many white spots and varies too much to represent things like continents. Where it's water, water, water, and then land with cut out edges."} {"_id": 5, "text": "What is the difference between dynamic generation and procedural generation ? When I think of a dynamically generated game, I think of things like Diablo with randomly generated levels. When I think of a procedurally generated game, I think of things like Flappy Bird and other infinite runners. But both of these just randomize a level. Is it that procedurally generated games are constantly being generated and dynamically generated games are all generated up front? Or are these terms interchangeable? What is the difference between a dynamically generated game and a procedurally generated game?"} {"_id": 5, "text": "What are some ideal algorithms for Rogue like 2D dungeon generation? What are some good resources regarding procedural content generation in the context of dungeon generation? Closest article I could find was Algorithm for generating a 2d maze, which isn't quite what I'm looking for. Features, such as rooms and connected hallways, are ideal. Thanks!"} {"_id": 5, "text": "Procedural terrain generation in cylindrical (2D) world I'm fairly new to procedural terrain generation. I know that to generate terrain you would use different calculations with the x and y axis (also z if you have one). But what if you want to generated random terrain on a 2D world that loops around itself? By that I mean a world in which you enter the right side upon leaving the left side (or the other way around). It should also be generated on the fly and not all at once. One solution I can think of is to just generate ocean along the border, but that is not what I'm looking for. I also seem to remember that Civilization generated such types of worlds, but I'm not quite sure how that worked, it's been quite some time since I played that game. So how exactly can one generate such a continuous world?"} {"_id": 5, "text": "Which parts to draw in an infinite world? I have an infinite world (from Perlin Noise). The world is generated in sectors that are that are big cubes (each with a random colour, in the image above my sectors are 10x10x10). I'm currently putting the sectors in a hash table tagged by their top left front corner coordinate. I can loop through all the sectors I've already generated and see if they intersect the frustum. But how can I compute instead the sectors that I haven't generated but are visible and need generating on demand? Even if I have an octree or some other spatial index, I need to compute the sectors that are visible inside the frustum rather than those I've already generated."} {"_id": 5, "text": "3D terrain generation with overhangs caves 3D terrain with 2D noise function as heightmap is kind of 'easy'. Make a plane and adjust height based on the noise. How would one start working on 3D terrain with overhangs caves? There are some older topics (for example related to Minecraft) on the thema, but non of them cover overhangs and in general techniques that can be applied to heightmap generated terrain."} {"_id": 5, "text": "How to decompose a rectangular shape in a Voronoi diagram, only generating convex shapes? I think this is a very straighforward question, lets say i have a building in 2D, a rectangle shape. Now i want to decompose that area in a lot of convex shapes, as seen in a voronoi diagram, or closely like it, just so I can add those shapes to the physics engine, and have a realistic destruction. Bonus Possible suggestions on how to make the effect more dynamic and interesting. Please keep in mind we re talking about realtime calculations.."} {"_id": 5, "text": "What is the state of the art in procedural character animations? I'm a programmer and I'm interested in programmatic character animation walking or running, bipedal or many legged what is the state of the art today? I heard about NaturalMotion's Euphoria system and Ubisoft's IK Rig, and they look amazing. Where can I find more info about similar algorithms?"} {"_id": 5, "text": "How does a game like Minecraft generate new chunks in realtime? I imagine looping through all 65,536 blocks with a noise function to set their type would be very slow. And Minecraft usually generates a ton of chunks at once. I read in one source online that Minecraft creates a column of 16x16x16 chunks, although I can't find any more information on that subject, and that doesn't really change how many blocks there are in one chunk \"column\". I assume there are optimizations made to make it work, although I can't find much about this subject online. Edit The way I am generating chunks in my own (2D) game is by looping through a 16x16 array using a Perlin Noise function for every chunk. With 16x16 chunks it runs fine in realtime. I want the chunks to be 3600 tiles high, and changing the size to be 16x3600 runs very slowly."} {"_id": 5, "text": "procedurally combine a main character with weapons during animations I need to find a way to programmatically place weapons for main character in right position of his body. For example if I am using UMA to procedurally create humans and then use some pre existing models of guns (10 20) of them. Now I need to find a way to place them correctly in the hand positions of the human model. I will use mixamo or IK to apply animations on the human character. But is there any way to programmatically place the objects in the right positions? Probably by marking some joints? I am looking at some efficient approach to begin with on this."} {"_id": 5, "text": "Perlin noise terrain 3 coordinates from one I am making a game with procedural terrain, like minecraft. I have a perlin noise function which takes one integer and returns a number between zero and one. However, for terrain, I need a single density value from three coordinates x, y and z. But my noise function only takes one number. Should I take the average of the noise values for x, y and z for a single density value? Or something else?"} {"_id": 6, "text": "Linear interpolation reach moving destination regardless its speed I'm implementing a camera for a game and I'm using the LERP formula for smooth chasing. However, if the target moves fast enough, the camera can never reach it unless the t ((1 t) v0 t v1) value is high enough, but that is exactly the problem some targets might still move faster than the current t value. This might lead to 2 problems The camera will never reach the object if it's super fast The camera will very slowly reach the object, depending on its current speed How do I scale up my t when the delta distance (abs(v1 v0)) gets lower, so that the camera will starts at a slow chasing rate and increases as it gets closer (therefore no targets could run away)?"} {"_id": 6, "text": "Setup golf ball physics I am developing a simple Golf game as shown in the below image. I am facing below issues Even if I apply small amount of force, the ball continuous move along the grass? Grass friction is not stopping the ball. Sometimes, the ball speed is increased after colliding with the walls instead the ball speed should decreased after collision with the walls. The walls are having box collider. Sometimes, the ball reverses its direction after colliding with walls. Code Physics properties of the ball ball.physicsBody.affectedByGravity true ball.physicsBody.mass 0.0450 ball.physicsBody.restitution 0.8 ball.physicsBody.friction 0.3 ball.physicsBody.allowsResting true Physics properties of the grass golf.physicsBody.friction 0.8 Physics properties of the walls leftWall.physicsBody.friction 0 leftWall.physicsBody.restitution 0.8 I have set the physics world gravity value to 9.8. I am looking for suggestions to fix the above listed issue. Thank you."} {"_id": 6, "text": "SpriteKit How to jump to specific position? I'm would like to achieve something like Object A will jump to position A in parabolic way. For example I am able to make the object jump but i do not know how to calculate to make the object jump to the precise location."} {"_id": 6, "text": "Infinite ball bouncing problem (Unity) I am trying to develop a basic Breakout game using this tutorial using Unity 5. But the ball starts to bouncing infinitely very easily. I cannot understand why this happenes. In my physics knowledge starting an infinite bounce is very hard, and even impossible. To return the ball to same position after bouncing we must send the ball with zero degrees with the vertical axis. To send the ball with zero degrees with vertical axis we must receive the ball with zero degrees with the vertical axis. To receive the ball with zero degrees with the vertical axis we must send the ball with zero degrees, and so on. We can send a ball with zero degrees only in initial ball throw. In all the other cases there must be an angle which is not equal to zero. Am I wrong? I mean the ball does not change its rotation. Ball moves between two plates which are parallel to each other infinitely (for example between paddle and upper wall) I added physics material to ball, paddle and the walls. This material has following settings Dynamic friction 0 Static friction 0 Bounceness 1 Settings of the ball Mass 0.5 Drag 0 Angular Drag 0 Is Kinematic true (I changed to false just before firing) Use Gravity false Settings of the paddle Mass 0.5 Drag 0 Angular Drag 0 Is Kinematic true Use Gravity false"} {"_id": 6, "text": "How do I determine the slope of a curve? I am making a 2D game where the character rides on the curve of a graph. I need to find out whether the player is going uphill or downhill and calculate speed accordingly. The problem is that I am not sure how to determine the slope of the curve on the point that the character is at. Here is an example of what some of the curves look like"} {"_id": 6, "text": "gamemaker getting a ball to bounce 90 degrees off of a 45 angle I am trying to get a circle to bounce off a 45 degree diamond shap using Gamemaker Studio. I would like the ball to bounce in straight lines so my directions would be 0, 90, 180, or 270 degrees, depending on which side of the diamond the collision takes place. Precise bouncing is giving me all sorts of results so I think I would have to do it in code. I tried saying if (direction 0 amp amp direction lt 90) direction 90 And doing this for all the angles, but this did not work. Has anyone encountered this before?"} {"_id": 6, "text": "Rotate a rigid body not around its centre of mass I have a rigid body (a boat) whose centre of mass is towards the front of the object. However, this makes the rotation look strange as the rudder that is turning the object is at the back of the boat so the rotation would be around that point. How can I rotate the object from the a separate point (using forces) without changing the centre of mass? Applying a force at a location still causes the object to rotate around the centre. In real life, you need to pin down the point that you want to rotate around, forcing the object to rotate around that point. This would suggest using constraints but I can't figure out how that would work. You sort of need the rotation point to act as a hinge, but when I apply a suitable constraint, but that would just block the rotation rather than convert it into a rotation around the new point. I want to resolve this using physics driven operations in Unreal Engine 4. I don't want to move the Centre of Mass, admittedly for not a particularly good reason, but this still feels like a valid question even if that was an option what if you want to rotate around two different points."} {"_id": 6, "text": "How can I calculate force and acceleration? I have problem of calculating the movement of the object. At the moment, I have a vectors calculated from the center of the screen minus the position of the object. direction vector centerScreen positionObject To calculate the new position of the object position(new) position(t) directionVector delta The delta is the time frame rate. Does anyone know how can I modify the above formula to calculate forces and acceleration? I want to have an object pulling other objects towards it."} {"_id": 6, "text": "Progressively loading the racing arena in a 3D driving sim I need advice and resources on a 3D car simulator. I want to progressively load the track for the player as I'm thinking of porting the game to mobile devices. This seems too difficult to me as I'm trying to separate the racing arena model design and the code as much as possible. Is there a structured method for achieving that for any model (arena map). I think this is something that comes up a lot in games in general not just this instance."} {"_id": 6, "text": "Why is RK4 better than Euler integration? At the end of these great slides, the author compares all the different integrators presented. One way or another, they all fall short except for Improved Euler Integration and Runge Kutta 4 Integration, which both pass all tests. I suppose I should mention that I am working on a 2D game that isn't very physics intensive. I'm just curious as to where Improved Euler Integration would fall short and RK4 would have to be used instead. My game consists mostly of simple gravity (jumping and falling), movement along the X and Y axes, and bounding box collision. Is it worthwhile to implement RK4 or would Improved Euler be sufficient? I see many discussions where Euler Integration's users are chastised, but from what I can see, Improved Euler is quivalent in simple 2D matters. I imagine it'd also be faster."} {"_id": 6, "text": "Pros and cons of different integrators When creating things like physics in games you need an integrator. I've seen Verlet integration mentioned several places as a great alternative to Euler integration. For instance in the famous document by Thomas Jakobsen. However in this article Glenn Fiedler writes Rather than introduce you to the vast array of different integrators that exist, I m going to cut to the chase and go straight to the best. This integrator is called the Runge Kutta order 4 integrator aka RK4. So apparently there's no silver bullet. What is the pros and cons of different integrators? Regarding simplicity, speed, accuracy, stability, etc. Which integrators is most suitable for which types of games? When would you use Verlet, RK4 or others? Should you ever use Euler?"} {"_id": 6, "text": "Choosing the correct normal for a collision I have taken the task of building a basic impulse physics engine. Circle vs Circle collision resolution has been done and I moved onto Line vs Circle. I can detect a collision and know that the normal should be perpendicular to the line which can be calculated easily (2d physics engine). However it's the direction of the normal that I cannot work out. From the image you can see there are 2 possible normals, one upwards (the correct one) and one downwards. How do I choose the correct normal?"} {"_id": 6, "text": "Pseudo magnet implementation with chipmunk How should I go about implementing \"natural\" magnet on a certain body in chipmunk space? Context is of simple bodies lying in the space (think chessboard). When one of the figures is activated as a magnet others should start moving towards it. Currently I'm applying force (cpBodyApplyForce)to the other figures with vector calculated towards the activated figure. However this doesn't really feel \"natural\". Are there any known algorithms for imitating magnets?"} {"_id": 6, "text": "Why Change from one coordinate system to another? When dealing with affine transformations, why do we need to change from one frame to another? What are some reasons. What are the pros and cons of doing this and the limitations if this was not possible.(Change of Coordinate Transformations)"} {"_id": 6, "text": "What is the logic beyond cube collisions? I am trying to simulate a colliding of two cubes , I actually tried and read a lot for many days but i did not get the idea beyond it,I know how to detect when they collide. Maybe my question is divided for many aspects, How to detect rotation and movement of these cubes after colliding , What is status of two cubes would be ? Sorry if was not clear or dumb, I would thankful if you could help"} {"_id": 6, "text": "Cocos2dx Physics Abort() When Changing Dynamic PhysicBody to Static? I just learned cocos2dx v3.3 integrated chipmunk physics engine. Here ,as you see, I create a simple circle with physic as auto sprite Sprite create(\"circle.png\") auto body PhysicsBody createCircle(sprite gt getContentSize().width 2) body gt setContactTestBitmask( 1) active collisions event sprite gt setPhysicsBody(body) sprite gt setPosition(...) this gt addChild(sprite) When I toggle this circle static dynamic in normal situation everything work fine and when circle become static it stop in its position (as we expect gravity don't move it longer). here is a toggle code which works fine body gt setDynamic(false) scheduleOnce( (float dt) body gt setDynamic(true) ,3,\"Back to Dynamic Mode Timer\") PROBLEM BEGINS But I want when the circle collide with something else ( in my case screen edge with is not important part of scenario), it become static then. so I use below code auto contactListener EventListenerPhysicsContact create() contactListener gt onContactBegin (PhysicsContact amp contact) gt bool return true contactListener gt onContactPostSolve (PhysicsContact amp contact, const PhysicsContactPostSolve amp solve) contact.getShapeA() gt getBody() gt setDynamic(false) gt Cause Abort() ! eventDispatcher gt addEventListenerWithSceneGraphPriority(contactListener, this) But I just face a abort() message and game exit. The call stack ( God bless it) show that the error is comming from line 300 in CCPhysicsBody.cpp if ( world ! nullptr) cpSpaceRemoveBody( world gt info gt getSpace(), info gt getBody())"} {"_id": 6, "text": "Roguelike movement system I'm trying to implement a roguelike movement system for my game. I'm using the ECS architecture. The requirements are entities will have a mass, on which should slow down the entity movement accordingly. fatty ones move slower there will have different terrains, that should apply different friction types, eg ice will decelerate the entity slower a quicksand will almost stop the entity immediately and so on. optionally there will have different weathers that should also impact on the entity movement, eg sandstorm would push the entity to it's direction rains will diminish the friction coefficient a little bit etc... If the two first requirements are solved, the third will probably be as well, I think. How would you do this?"} {"_id": 6, "text": "Serious issues with grid of connected springs So i have a simulation I am trying to make where there is a grid. Each dot will be connected to the dot Above, below, left, or right (If such dot exists) via a logical grid. Theoretically when I create a disturbance it will react slightly like cloth. My problem is it is going all wrong! I didnt know which way to subtract to get the delta so I gave you two samples. Issue one Detract This one is probably the wrong one but it might help. Basically when you cause a disturbance it causes everything to fly away. Its pretty cool looking. Issue two Attract This one is probably using the correct delta, however when left on its own the grid eventually groups in on top of itself. Ignore the diagonal ones at the very beginning those are just an error, I removed them since recording that video. Below is excerpts from the code that causes this. This system works entirely on a 1d array (because they arent always even close to a grid) and as a result I have a bunch of functions that find the index of next door points. I am not showing their implementation unless that is likely to be the error. The velocity resulting from the spring is stored in a variable springV. Each frame the interaction displacement and resulting spring velocity is calculated through function transfer. Then after all of that is calculated it is applied to the positions through function resolveGridS. Transfer() is run on each particle one by one in an order, then resolveGridS is run after that. Theoretically the correct force given from having a spring from the nextdoor point is calculated in the function resolveGridS and added to the total. The \"Resting\" distance of the grid is about 30. var springV Point() func transfer() if (excluded) return Gets rid of points not on the grid, they dont get to be springs let touch MT.getFirstFinger() if (touch.down) let location getPosition() let dist2p Math.dist2P(location, touch.location) Storage.bounds.rb let angle Math.calculateAngle(location, touch.location) pointTowords(touch.location) direction 180 let calc ( dist2p dist2p) 1.0 if (circleIndex 0) print(calc) moveBy(calc 5) let id Int(circleIndex 5) Get the 1d array location of this particle Get the 1d array index of each of the next door points let above moveDirection(id, Direction.Up) let below moveDirection(id, Direction.Down) let left moveDirection(id, Direction.Left) let right moveDirection(id, Direction.Right) Drag springV.x 1.1 springV.y 1.1 if (left.1 1) This check just deals with edge cases SpringC(Storage.particles left.0 .getPosition()) if (right.1 1) SpringC(Storage.particles right.0 .getPosition()) if (below.1 1) SpringC(Storage.particles below.0 .getPosition()) if (above.1 1) SpringC(Storage.particles above.0 .getPosition()) func resolveGridS() Storage.circles circleIndex springV.x Storage.circles circleIndex 1 springV.y func SpringC(loc Point) let pos Point(x Storage.circles circleIndex , y Storage.circles circleIndex 1 ) let delta Math.subtract(loc, pos) let dist Math.dist2P(delta) let norm Math.multiply(delta, 1 dist) springV.x norm.x 0.01 abs(dist 30) springV.y norm.y 0.01 abs(dist 30) NOTE I really dont know how you are supposed to deal with physics when one object has multiple springs connected to it. I made the assumption that you just calculate the force each spring gives for each object. And then after all of the forces are calculated you apply it. That could be wrong."} {"_id": 6, "text": "Looking for a peer reviewed article that details the benefits of a physics simulation within interactive media I'm hoping this is the correct place to ask this question as it is video game related and can be seen as a key ingredient in modern game development. Does anyone know of a peer reviewed article that details the benefits of incorporating a physics simulation into interactive media (such as video games)? I can find books with a few remarks in their introduction (no more than a couple of sentences) but nothing substantial."} {"_id": 6, "text": "Data structures for interpolation and threading? I've been dealing with some frame rate jittering issues with my game lately, and it seems that the best solution would be the one suggested by Glenn Fiedler (Gaffer on Games) in the classic Fix Your Timestep! article. Now I'm already using a fixed time step for my update. The problem is that I'm not doing the suggested interpolation for rendering. The upshot is that I get doubled or skipped frames if my render rate doesn't match my update rate. These can be visually noticeable. So I'd like to add interpolation to my game and I'm interested to know how others have structured their data and code to support this. Obviously I will need to store (where? how?) two copies of game state information relevant to my renderer, so that it may interpolate between them. Additionally this seems like a good place to add threading. I imagine that an update thread could work on a third copy of the game state, leaving the other two copies as read only for the render thread. (Is this a good idea?) It seems that having two or three versions of the game's state could introduce performance and far more importantly reliability and developer productivity problems, compared to having just a single version. So I'm particularly interested in methods for mitigating those issues. Of particular note, I think, is the problem of how to handle adding and removing objects from the game state. Finally, it seems that some state is either not directly needed for rendering, or would be too difficult to track different versions of (eg a third party physics engine that stores a single state) so I'd be interested to know how people have handled that kind of data within such a system."} {"_id": 6, "text": "How does braking assist of car racing games work? There are a lot of PC car racing games around which have this unique driving assist which helps brake your car so that you can safely turn it. While in some games it just an 'assist', it will just help your car brake but won't ensure a safe turn. While in others, the braking assist will help you get a safe turn. I was wondering on what could be the algorithm that is followed to achieve it. A very basic algorithm I could think of was, Pre determine the braking distance of an ideal car for every turn of the track, depending on the radius of the turn, and then start braking the car accordingly. For example, for a turn of less than 90o, the car would start braking automatically at 50m distance from the start of the turn. A more advanced algorithm, which would ensure a safe turn, could be Pre determine the speed of the car at the start of each turn, individually for each track, turn and car. Also, pre determine the deceleration rate of each car individually, which varies because of the car's performance. The braking assist would keep recording the speed of the car at a certain instant of time. Start braking the car appropriately so that the car gets to the exact speed needed at the start of the turn. For example, let the speed of a particular car at the start of a turn 43m in radius, be 120km h. Let the deceleration rate of the car be 200km h2. If, at some instant of time, the speed of the car is 200km h, then the car would automatically start braking at 400m from the start of the turn."} {"_id": 6, "text": "How do I prevent a KActor from changing the orientation of its Z Axis? So I have an object that inherits from KActor that I would like to behave as a dynamic physics object, but I want its Z Axis to remain upright, but very stiffly. I've tried the bStayUpright that triggers the \"Stay Upright Spring\". The problem is, it's a spring, and the object in question oscillates into position when I want it to remain oriented properly without wobbling. In the image above, the yellow block has fallen onto the gray box, and it is currently pivoting about the contact point as it tries to right itself. Should I be tweaking the StayUprightMaxTorque and StayUprightTorqueFactor parameters, or should I be using a Constraint of some sort?"} {"_id": 6, "text": "Bullet Physics Applying a force at the point of collision Suppose I want to simulate some kind of gripper with two \"fingers\" (such as pair of pliers, or two fingered robot hand), picking up an object from the ground. Both the gripper and the object are dynamic rigid bodies. I want to start with the object roughly in the centre of the gripper, and then move the two fingers towards the object, to determine the point at which they make contact with the object's surface. Then, I want to apply a certain force from the fingers onto the object, before finally lifting the fingers (and hence the object) upwards. Is there any simple way to achieve this just by treating the two fingers as two individual rigid bodies? I want to just move the fingers towards the object to find the point of collision so can I treat them as kinematic objects (with zero mass so they don't fall under gravity, which is what I want), and move them manually by slowly changing the pose of each finger over time? But how will I know at what point the fingers and object collide, so that I should stop moving the fingers and start applying a force? Thank you!"} {"_id": 6, "text": "game physics contact constraint and relative velocity For two rigidbodies (2D boxes), A and B, I have been colliding A with B and finding the collision normal pointing towards A i.e. the direction that would separate A from B. When it comes to calculating the relative velocity for the contact constraint, does it matter which body has the edge that the collision normal is perpendicular in terms of which velocity to subtract from which?"} {"_id": 6, "text": "Creating a simple ripple propagation with variable resolution I am trying to do a simple simulation of a ripple propagating through a medium. I do not have a physics engine at my disposal so setting up a complicated set of spring constraints doesn't seem to be like the way to go. In the past when I have done this the simulation has been resolution dependent. Which means that because on each step each unit of the simulation only samples things one unit around them that if the resolution is high waves propagate slowly. Similarly if the resolution is low they travel quite quickly. I need to figure out a sampling method other than just the nearest neighbor that can make it so I can up the resolution of the simulation without majorly changing the sense of propagation speed. Are there any solutions to this kind of situation?"} {"_id": 6, "text": "What is the logic beyond cube collisions? I am trying to simulate a colliding of two cubes , I actually tried and read a lot for many days but i did not get the idea beyond it,I know how to detect when they collide. Maybe my question is divided for many aspects, How to detect rotation and movement of these cubes after colliding , What is status of two cubes would be ? Sorry if was not clear or dumb, I would thankful if you could help"} {"_id": 6, "text": "Progressively loading the racing arena in a 3D driving sim I need advice and resources on a 3D car simulator. I want to progressively load the track for the player as I'm thinking of porting the game to mobile devices. This seems too difficult to me as I'm trying to separate the racing arena model design and the code as much as possible. Is there a structured method for achieving that for any model (arena map). I think this is something that comes up a lot in games in general not just this instance."} {"_id": 6, "text": "Movement arriving using forces 3D. Given a point mass m, inital position p0 initial velocity v0, and a desired location d, how do I apply forces (with magnitude no greater then fMax) to move m to d and stop. I know how to apply forces, it's the strategy for determining what force to apply each frame. You would think this would be easy but it's turned out to be difficult. A solution that only converges at the limit is not acceptable (i.e. having the mass oscillate back forth over the destination by smaller and smaller distance) Edit This is not the same as this question. Finding the stopping distance is trivial, but is (maybe) only part of the solution. Edit Also not the same as this question, because the highest answer is incorrect (as stated by my constraints)"} {"_id": 6, "text": "Friction due to gravity in an impulse based physics engine In my physics engine, I'm using impulses to solve collisions. I'm basing all calculations on these equations impulse desired velocity change mass impulse force time friction force lt normal force coefficient If an object moves along flat ground (infinite mass), after integration it'll be moving slowly \"into\" the ground due to gravity. This means that the impulse needed to react to that (given the restitution equals 0) will be the velocity in the direction of the contact normal, multiplied by mass. The issue here is that gravity is a constant acceleration, which means that the object, no matter the mass, will always \"dip\" by the same amount given a constant frame rate. So the mass is never a factor in this situation, outside of the impulse calculation, which is just a flat velocity change. Now, I can use impulse to calculate the force that was needed to react to the collision, this force can then be used in the friction equation as such friction impulse time lt normal impulse coefficient time Since time is always greater than 0, I can just multiply both sides by it, and then I can use the impulse equation, as such planar velocity change mass lt velocity change along normal mass coefficient And again, I can just remove mass from the equation, which leaves me with planar velocity change mass lt velocity change along normal mass coefficient This is the desired velocity change along the contact surface due to friction. The issue is, obviously, that none of this depends on mass, which means that no matter how heavy or light an object is, it'll always continue sliding along the surface by the same amount given a constant initial velocity. What am I missing? It really looks like there's a logical mistake here. Should the dynamic friction depend on the mass in the first place? Moving a heavy object requires higher force, so static friction should be modeled properly, since it just flat out removes velocity, though it'd be nice to hear if this has merit or just \"looks good\"."} {"_id": 6, "text": "Custom Physics Preventing objects from losing velocity in certain situation Illustration http s22.postimg.org 7agd30vap Untitled.png So the little box is my character. The red arrow shows the current velocity(Some force to right gravity). Below it are 2 blocks which has the same height. The problem is that my algorithm would false solve the collision normals.(You can see them in green). These would mean that my character would not slide, but will stop in one place. I'm following this tutorial http gamedevelopment.tutsplus.com tutorials how to create a custom 2d physics engine the basics and impulse resolution gamedev 6331 Is there something I miss and how can I fix this problem?"} {"_id": 6, "text": "2D object move evade obstacle Description Actor int x,y,width,height float speed, angle actor is an object that move around the map every frame, actor change position(x,y) according to it s speed amp angle Problem If Next frame actor A will collide with actor B Then A should turn to what angle to evade B?"} {"_id": 6, "text": "Reimplemented steering seek behavior from PyGame to L VE is much slower than original I'm learning about steering behaviors and watched this nice explanation tutorial https www.youtube.com watch?v g1jo qsO5c4 amp feature youtu.be with the source code available at https github.com kidscancode gamedev blob master tutorials examples steering part01.py. The example app is written in python and PyGame and behaves like The main code parts of it are MAX SPEED 5 MAX FORCE 0.1 def seek(self, target) self.desired (target self.pos).normalize() MAX SPEED steer (self.desired self.vel) if steer.length() gt MAX FORCE steer.scale to length(MAX FORCE) return steer def update(self) self.acc self.seek(pg.mouse.get pos()) self.vel self.acc if self.vel.length() gt MAX SPEED self.vel.scale to length(MAX SPEED) self.pos self.vel ... I tried to reimplement this example in lua with Love2d framework and HUMP vector utility, source code is available at https github.com voronianski on games sandbox blob master src steering seek love2d main.lua. The code is pretty similar with the same constant values of MAX FORCE and MAX SPEED function Mob new () ... self.maxVelocity 5 a.k.a MAX SPEED self.maxSeekForce 0.1 a.k.a MAX FORCE ... end function Mob seek (target) self.desired (target self.pos) self.desired normalizeInplace() self.desired self.desired self.maxVelocity local steer (self.desired self.vel) if steer len() gt self.maxSeekForce then steer steer trimmed(self.maxSeekForce) end return steer end function Mob update (dt) self.acc self seek(vector(love.mouse.getPosition())) self.vel self.vel self.acc dt if self.vel len() gt self.maxVelocity then self.vel self.vel trimmed(self.maxVelocity) end self.pos self.pos self.vel dt ... end But behavior is different. Square is much more slower in lua implementation though the values are the same What could be a problem? Or what is the difference that I couldn't notice?"} {"_id": 6, "text": "How to calculate detect the force of a collision? (Game Maker Studio) How can I use game maker to detect the force in a collision between two mobile (not fixed) objects? This is used for damage calculation and possibly compression calculation. My problem is this while net force can be calculated using mass and acceleration, the idea of damage is focused on the individual components of the force applied on an object. For instance, if a car is pushing another car against a wall, even though there are no acceleration, people will logically feel like some damage must be done to both cars because forces were conferred on them. I want to know if there is some underlying mechanism in game maker's physics system (I use the latest version) that actually calculate a reaction force from the wall on the car so I can use it to calculate damage."} {"_id": 6, "text": "Benefits of going full AABB? By \"going full AABB\" I mean using only AABBs for all of your objects (both dynamic and static), with dynamic objects colliding both with each other and static objects. In what specific ways does this simplify physics calculations? Are there any special techniques that require a world made entirely of AABBs? Some way to, say, remove the need for TOI ordering (or similar) by taking advantage of that fact that all objects are AABBs? In particular I'm looking for specific large scale benefits, not just small things like collision detection being slightly faster. There seem to be quite a few games that use only AABBs, like Minecraft for example, so there must be a significant benefit to it or they wouldn't be doing it. Only thing I can think of is getting to do position velocity corrections per axis, though I'm not sure how one would exploit that to its full potential."} {"_id": 6, "text": "Does client side prediction sync with the server in the past? I've spent some time now messing around and just trying to learn dead reckoning and client side prediction for the fun of it. Most of what I do doesn't need it, so i've never had a need to go down the path. I get how to predict the client and i've got a completely deterministic setup with a lockstep of 60fps for the physics on client and server. Both client and server use the same movement code, and i'm using constant velocity to reduce complexity. I also understand how to interpolate for corrections. I also have the server and client ticking at nearly the same time (as close as one can really get it). The problem i'm having, that doesn't seem clear to me in anything I've read (i'll put links at the end to a few things), is what does the client message sync against on the server? So, for example, the client is at 0, 0, 0, with a heading of 0, 0, 1 at tick 0. At tick 5 the client presses the button to start moving forward at 40u s and sends the message to the server. We'll say that the trip to the server takes 50ms and 50ms back. So the server gets the message at tick 8 (roughly), and here is where I am slightly lost. The client sent the tick they pressed the button along with the position and new velocity. Does the server do A. Look back at tick 5 and say \"you're good b c you were where you should be at that tick\" B. Check against tick 8 and say \"well you where at 0, 0, 0 at tick 8, so you didn't start moving until then\". It would seem with B, which is what i'm currently doing, that the server is always sending back a correction. B also has a bad side affect that when I stop, I'm almost never where the server is and the interpolation of this feels impossible to get right. While with A, it would seem I have to redo all collisions for that object from tick 5 thru 8 on the server, but this sends less corrections and would give a smoother feel. I understand that A is used for lag compensation when firing a weapon or taking some action that would affect other entities, but is that also used for motion? Things I've read http gafferongames.com http www.gabrielgambetta.com fpm1.html Various articles out of books and other websites that seem to skip past this detail Thanks in advance for any help."} {"_id": 6, "text": "Resolving a collision between point and moving line I am designing a 2d physics engine that uses Verlet integration for moving points (velocities mentioned below can be derived), constraints to represent moving line segments, and continuous collision detection to resolve collisions between moving points and static lines, and collisions between moving static points and moving lines. I already know how to calculate the Time of Impact for both types of collision events, and how to resolve moving point static line collisions. However, I can't figure out how to resolve moving static point moving line collisions. Here are the initial conditions in a point and moving line collision event. We have a line segment joined by two points, A and B. At this instant, point P is touching colliding with line AB. These points have unit mass and some might have an initial velocity, unless point P is static. The line is massless and has no explicit rotational component, since points A and B could freely move around, extending or contracting the line as a result (which will be fixed later by the constraint solver). Collision is inelastic. What are the final velocities of the points after collision?"} {"_id": 6, "text": "How to make character gain acceleration? I want to create more realistic physics for my 2D games. Currently, the character and the other game objects in my games start moving instantly (achieve maximum speed instantly) and stop instantly (achieve 0 speed instantly). There is no transition between speed levels resting and moving, moving and resting. I heard about 'steering behaviors', but am pretty sure they're mostly for designing AI agents' movements. Should I learn steering behaviors to make more realistic character movements in general? (In the physics aspect). Is this the way to go? If the answer is 'yes', could you recommend a good source to learn them?"} {"_id": 6, "text": "Numerical differentiation to calculate size of circular buffer I'm using Allegro 5 to create a software generated \"motion blur\" effect for my 2D sprites. I basically just have a boost circular buffer of some length which holds \"snapshots\" of the sprite going back in time. Each render cycle a new \"snapshot\" of the main sprite is pushed onto the front of the buffer, and the last is popped off the back. The \"snapshots\" are then rendered with alpha values scaled by how old far back in the buffer they are. To save on CPU power I'd like to have the circular buffer dynamically resized so that the length of the trail is proportional to the object's velocity, i.e. don't store and push back lots of snapshots for trail sprites that won't be needed anyway because the object is moving too slowly. The inputs I have to the data structure that holds the main sprite and its associated effect buffer are just the dx and dy values of how much its position vector changed since the last update cycle of the game logic. So I'm looking for a suggestion for an algorithm that can use that to increment decrement some kind of unsigned counter that can be used to resize the buffer proportional to velocity."} {"_id": 6, "text": "How can I simulate physics on my curved LED strip? I have a LED strip with 300 LEDs that I can control one by one https github.com cipold pyledstrip You can think of them as Adafruit NeoPixels https www.adafruit.com category 168 I have code to detect the physical positions of all LEDs using a camera and generate an x y heightmap https github.com cipold pyledstrip detector There is some experimental code to make use of the heightmap and let pixels race along the strip like on a rollercoaster https github.com Pixe1 pyledstrip particles Video http mnagel.net oneshot 2018 03 02 particle.mp4 975a194be7cc6fc8 particle.mp4 The \"physics engine\" within that code is very ad hoc, however. I want to rewrite it into something that more explicitly encodes the physical laws of classical Newtonian mechanics. I can easily simulate particles with mass, position, velocity (acceleration gravity forces). With multiple particles and gravity between them, I would end up with some kind of solar system. Or with constant overall gravity, one particle would fall down in a straight line, accelerating all the time. What I really want is \"global gravity\" but restrict the particles to move along the path dictated by the LED strip heightmap of waypoints (one degree of freedom along that path). How can I adequately model this restriction with formulas that are still reasonably physically accurate?"} {"_id": 6, "text": "Calculating impulse propagation through a rigid body after a collision I'm working on a game. I need to work out what the impulse is at different points on a body as a result of a collision. For example, in the following diagram, if there is a collision that results in an impulse being applied to the body at A, what will the resulting impulse be at B? I know the mass, center of mass and dimensions of the body."} {"_id": 6, "text": "Player moving up, is he jumping or climbing? In a 2D physics based platformer game that has ladders in it, how do you determine whether the player moving up is caused by a jump or him climbing a ladder, such that you know what animation to play? And in general, obviously the direction vector is not enought to determine the animation to play how do you also determine the cause of the movement (so you know the correct sprite to use)?"} {"_id": 6, "text": "Is this a correct backward Euler implementation? I want to simulate a mechanic object like this init acceleration a init velocity v init position x loop get delta time dt v v a dt x x v dt I use the velocity (which is the derivative of position) at the end of each time step to approximate the new position. So this should be exactly what the backward euler method does. Do I have an error in reasoning?"} {"_id": 6, "text": "Shapes and sprites in SVGs I understand SGV images are used in 2D games to store shape data for the physics engine of the game. I'm unsure though, should the raster sprite also be stored in the SVG or should it be separate? Also, what about animated sprites? In a non skeletal based animation system, how should the shape of the character be handled? Is a simple rectangle enough?"} {"_id": 6, "text": "Changing orientation by applying torques Suppose you've got an object floating freely in space. You have a vector you want this object to point towards, and a vector representing the direction it's currently facing. From these two, you can get the rotation (matrix, quaternion, whatever) that represents the change in orientation to bring the two vectors into alignment. If you only have the ability to apply torque (derivative of angular velocity) to your object, what's a good algorithm for applying torque over time that won't over undershoot the destination? (In this case, it's a space ship that wants to automatically orient itself in the direction of travel using thrusters. Roll is irrelevant.)"} {"_id": 6, "text": "Clothing and physics asset collisions not working I quot m making a character in Blender where there's a character mesh and a simple skirt. The skirt has a different material slot, which allows me to use the Unreal Clothing tool. I created the clothing data, applied it, painted it so the top part isn't moving at all and bottom has 100 quot dynamics quot . I also created a physics asset, however no matter what settings I try, the skirt will always poke through the thighs like they don't exist. All the colliders are capsules. I also get the feeling that the hip collider actually works. But only that one! The skirt works perfectly with the wind, which makes it even weirder. Does anyone know what can cause this?"} {"_id": 6, "text": "Relative Position Rotation calculation I have 2 objects each with a 3x3 Matrix (Orientation) and a Vector3 (Translation). Both are relative to world coordinates. How do I calculate the position and orientation of object B in relation to object A? I'm using the JVector, JMatrix that are a part of the Jitter3D physics library. (http code.google.com p jitterphysics ) Any help would be greatly appreciated!"} {"_id": 6, "text": "Best physics engine for OpenGL ES (different implementations)? Can you recommend a good physics engine which is easily portable between WebGL and other OpenGL ES implementations like in Android and iPhone? I don't want a game engine. Only the physics part."} {"_id": 6, "text": "Sliding loose dirt shader material effect Im sure there is some sort of technique with a name I don't know or didn't think to search, but how would I go about making an effect similar to loose dirt sliding down the face of a slope when something disturbs it? I guess I think of it as a mini avalanche or something. I have attempted it a couple times with pretty poor results, but some of the properties i tried to replicate was the sliding dirt spreads out the further it gets from its start position depending on the surface shape, angle of repose, rocks or larger pieces of debris causing even more dirt to slide(quasi recursion?), loose dirt 'sliding' over other dirt, etc. I assume id need to combine the right ratio of shaders, particles and textures to look right but I cant seem to find any real info on this type of effect. Would something like this be too intensive to do real time?"} {"_id": 6, "text": "Applying multiple forces on a particle If I have a particle, say in a polar coordinate grid, and I want to apply multiple vectors to it, how can I calculate where it's final position will be given those vectors? Ex. Imagine there's a force represented as a vector, that moves the particle a radius magnitude of 8 at an angle of 45 . Another vector that acts on it at the same time, at magnitude 3 at 90 . How would I calculate the final position of the particle?"} {"_id": 6, "text": "Targeting with a ballistic gun I am trying to determine the gun elevation angle of a gun that fires ballistic projectiles. For a target at a certain distance D, I will have to compute an angle that increases with D. This relation ship is non linear, by the way, because the projectile loses velocity as it travels, for starters, due to drag. In the past, I have done this with a lookup table.... for a whole bunch of test firings, see where the projectile hits the ground. But this only works if there is no delta in the elevation between gun and target. A target that is on a hill top, will need adjustment for extra range. Whereas a target in a valley below, would mean a lower gun elevation. This means that the table lookup will break down, and a 2D table seems like a kludge. What would be an effective way to compute this targeting? I know things also depend on nozzle velocity and air drag, but these will not vary (but drag will be non zero.) Neither will I be modeling the wind. Additional information This is for AI assisted targeting. NPC or player targets a point in the world. The algorithm will find the corresponding angle to hit the target. Currently, I am using Bullet Physics, with a discretely stepped world."} {"_id": 7, "text": "Vectors and corners of squares I am having some problems with some vector math. Imagine a square and coming from each corner of the square is an invisible vector, which starts at the square's centre and ends at the edge of the screen. a d b c THIS IS A VERY CRUDE IMAGE AND THE ANGLES OF THE VECTORS ARE NOT EQUAL There are 4 areas a, b, c and d I would like to say that if you touch within one of the areas then something happens. Is there a simple way to do this?"} {"_id": 7, "text": "How does the rectangle bounds (x,y,width,height) in libgdx work? I cant work out how to use the rectangle bounds in libgdx I am currently using the superJumper example and have 2 or 3 examples with that are lt ! this is the pause button in the top right corner gt pause Bounds new Rectangle(320 64, 480 64, 64, 64) lt ! this is a rectangle resume button in the middle of the page in the menu that comes up when the pause button is pressed. gt resume Bounds new Rectangle(160 96, 240, 192, 36) Basically my question is aimed at the 360 64 and 160 96 because I don't know why this is used. I need to create a rectangle that covers the left side of the screen and the same on the right. I want to create some on screen buttons, I have already created the actions for these buttons and I have managed to get them to work but I can't move the rectangles to where I want."} {"_id": 7, "text": "Changing background images frequently within a specific time range with Cocos2D I am working on a game development project for Android. We use the Cocos2d framework. I have to design a page which contains two background images, I need to switch these images repeatedly within 1sec. How can I do this? How can I use CCTransitionScene in my Java code and change these images repeatedly? Thanks in advance."} {"_id": 7, "text": "How to manage screen and input when using libSDL2 for both desktop and Android? I have worked on libSDL1.2. Since, the release of 2.0, SDL also supports android. So, I am trying to develop game that can work both on desktop and android. But there are few things that are confusing me. When we are creating a window, we pass the width and height of screen. But on android game covers whole screen and different devices have different resolutions. So how can we create a screen which appears uniform on both desktop and android. How to handle inputs like back button. Also, how to load graphics based on DPI."} {"_id": 7, "text": "The best option to multi platform 2d mobile development we are in the process of porting a game from iphone(made with cocos2s) to android(using the andEngine), and it has been a pain to do. So for our next project (a 2d game) we are thinking about using some multiplatform engine framework. For now we are thinking about testing both unity, marmaled(former airplay sdk) and cocos2d x. Do you have any opinion about this? Does someon have experience developing 2d games using Unity?"} {"_id": 7, "text": "How do I change my gravity and jumping logic to put the character at a specific height at a specific point in time? I'm making a 2D platformer on Android using libGDX. One thing I've had a problem with recently is gravity and jumping. I found a few tutorials on the internet and was able to come up with this... public static final int JUMP HEIGHT 64 public static final float JUMP GRAVITY 6.0f public static final float MAX GRAVITY 20.0f public static final float GRAVITY 19.0f private void updateGravity(float delta) if(Gdx.input.isTouched() amp amp !jumping) jumping true gravity Config.JUMP GRAVITY if(jumping) change frame to jump sprite.setRegion(walkFrames 0 ) sprite.translate(0, ( 1 gravity)) runner has landed? if(sprite.getY() lt idleY) jumping false sprite.setPosition(Config.RUNNER X, idleY) slowdown fall if (gravity lt Config.MAX GRAVITY) gravity Config.GRAVITY delta The code works and my character will jump and fall smoothly. Although the time it takes for him to jump and comedown is independent from delta the height he jumps is not. If the device lags while jumping he will jump only a portion of how high he should. For the life of me I cannot get it to make sure it jumps a specific height (JUMP HEIGHT) and in a specific time independent of the delta."} {"_id": 7, "text": "Reducing APK File Size by using JPG instead of PNG for game background images I've just finished my (openGL ES 2.0 Android) game and it's almost ready for Alpha testing. When I export the application to an APK File, the file is taking up 16MB and I would like to reduce this as much as I can. Here are some points about what the project contains and what I've tried to reduce the size already 222kb of Ogg Vorbis files used for Sound Effects 1 x MP3 file at 5.59MB (128kbps Bitrate) 4 x sets of PNG files used for textures (XHDPI, HDPI, MDPI amp LDPI I'm not using XXHDPI) Just over 1MB of code What I've tried thus far to get where I am I've optimised the PNG files using Optiping I've applied ProGuard to my code before exporting, this didn't really help by much as 99 of my app is resources. So my question is, is there really much else I can do to reduce the size of the APK? I was thinking about maybe using JPG format source files for my Background OpenGL textures instead of PNG anyone have any experience with this? Does it hurt performance at all? I can see that it would make quite a difference my atlas of backgrounds in PNG format for XHDPI is 1.7MB and a 90 compressed JPG comes in at around 650KB. I'm just not sure if it's a good idea as everyone always advocates PNG JPG. Any pointers from personal experience would be helpful amp also if I've overlooked anything other than using JPG's."} {"_id": 7, "text": "How to decide how much to charge for development? So two other friends and I are a very small game dev studio. So far we haven't released a game but we have 2 games almost ready to launch. A bigger studio saw our work and now they want to work with us they need people to develop mobile games for them (iOS, Android). They want us to set the price for the projects (can't tell the specifics we signed a NDA). They will give us all the assets (graphics sound) so we only have to code. And because they only work with Unity3D we have to learn it. How do we decide how much to charge for the projects?"} {"_id": 7, "text": "How do games such as aa Game have high levels in the structure of their code How do games such as aa Game have high levels in the structure of their code? I mean if we want create a game with high levels, should we create and use a class for each level? I do not want code from you. only I want know for creating a game with high levels in android, What we should do in coding? Is it good if we create and use a class for each level?"} {"_id": 7, "text": "How do I change my gravity and jumping logic to put the character at a specific height at a specific point in time? I'm making a 2D platformer on Android using libGDX. One thing I've had a problem with recently is gravity and jumping. I found a few tutorials on the internet and was able to come up with this... public static final int JUMP HEIGHT 64 public static final float JUMP GRAVITY 6.0f public static final float MAX GRAVITY 20.0f public static final float GRAVITY 19.0f private void updateGravity(float delta) if(Gdx.input.isTouched() amp amp !jumping) jumping true gravity Config.JUMP GRAVITY if(jumping) change frame to jump sprite.setRegion(walkFrames 0 ) sprite.translate(0, ( 1 gravity)) runner has landed? if(sprite.getY() lt idleY) jumping false sprite.setPosition(Config.RUNNER X, idleY) slowdown fall if (gravity lt Config.MAX GRAVITY) gravity Config.GRAVITY delta The code works and my character will jump and fall smoothly. Although the time it takes for him to jump and comedown is independent from delta the height he jumps is not. If the device lags while jumping he will jump only a portion of how high he should. For the life of me I cannot get it to make sure it jumps a specific height (JUMP HEIGHT) and in a specific time independent of the delta."} {"_id": 7, "text": "How remove banner adView from a Screen in libgdx? I have an AdMob banner in the game. But I need this banner not to be shown in Screen 1 and when user enter Screen 2 I need to show the banner. When I call AdView.gone() it dissapears from screen but coordinates becomes wrong and touch position doesn't match with coordinates. How can I properly remove AdView."} {"_id": 7, "text": "Moving sprites using the accelerometer (Android) In my previous game, I was moving my sprite like so float time 10f Number of seconds to pass a pre defined area (using the screen width in this example) float velocity 1f time work out velocity based on above time float realX velocity dt Move the sprite to the left (where dt is previously defined delta) x realX screenWidth convert to screen coordinates so it can be rendered sprite.draw(x, y) Working out the y position in the same way This all works great when using touch controls. In the above example, the sprite will cross the screen in precisely 10 seconds regardless of the device on which it is running. However, the game I'm currently developing uses the accelerometer to move the sprite. (I'm only moving the sprite left right). Currently, what I'm doing is this Override public void onSensorChanged(SensorEvent event) tilt event.values(axis) Once I have the value, I apply it to my sprite movement like this float time 10f Number of seconds to pass a pre defined area (using the screen width in this example) float velocity 1f time work out velocity based on above time float realX (tilt velocity) dt Move the sprite to the left Now using the tilt value x realX screenWidth convert to screen coordinates so it can be rendered Although this does work it gives nice fluid movement of the sprite, when I run it on an old Galaxy Ace, the sprite accelerates way too fast. This changes the feel of the game note I'm talking only about acceleration here, so if I tilt the phone from left to right repeatedly, the sprite is extremely (too) responsive on the Ace, but 'just right' on my 10\" tablet). I've tried a couple of other available games and they seem to run pretty consistently across devices. I'm wondering if my code is correct and if so, what can I do to get all devices running more consistently with regards to the accelerometer? Edit Just to clarify what it is I'm asking. I have a sprite in the middle of the screen sitting on a horizontal platform. When the device is tilted to the left, the sprite moves to the left. The rate of movement should be linked to the angle the device is tilted. So, if the device is vertical there should be no movement. If the device is tilted slowly to the left, further and further the sprite should increase in speed also (up to a limit) ie, accelerate. The other (real world) way to think of it is sitting a ball bearing inside a vertical box (the box representing the device) and then simply tilting the box to the left and right. The ball accelerates towards to lowest corner. The sprite should act like a real ball. If it's accelerating towards to left corner, and the box is tilted in the opposite direction, then the sprite should start to decelerate to a stop, and then srart accelerating in the opposite direction. Just as the real world ball bearing would. My Original code achieves this, however, on some devices it's simply too responsive, it will decelerate and accelerate too quickly. And therefore change the 'feel' of the game making it too easy for one thing. So basically when I say the sprite movement feels 'natural' I'm referring to how the ball bearing would act feel in the real world. This is exactly what I'm looking for hope this helps!"} {"_id": 7, "text": "LibGDX Android Textures reload other textures, and transparent images get black backgrounds Pictures I have very strange problems with my LibGDX Game in Android The problem is that sometimes the textures get black backgrounds when they should be transparent, and sometimes when I remove the texture, or press the back button, the textures get replaced with other textures that I have. To clarify I'm using x texture to show the status of health. I'm using three x textures to show how many lives the player got, and when I lose health, and remove one texture, the x texture get replaced with y or z texture, or the remaining x textures get black backgrounds. Sometimes it works flawlessly, and the x texture gets removed, and the backgrounds are still transparent. I'm loading my textures via an AssetManager, and just load them on create(). In my render I use this Gdx.gl.glClearColor(1, 1, 1, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) Gdx.gl.glBlendFunc(GL20.GL SRC ALPHA, GL20.GL ONE MINUS SRC ALPHA) batch.enableBlending() batch.begin() for (Entity life LifeEntities) life.render(batch) batch.end() I'm also using this in my Launcher Class. AndroidApplicationConfiguration cfg new AndroidApplicationConfiguration() cfg.r cfg.g cfg.b cfg.a 8 MainGame myGame new MainGame(arrayName) initialize(myGame, cfg) I do dispose the textures also. I have looked up on google and on gamedev about this problem, but all the questions are for problems when the transparent always have black background, not when it is something that happens like a bug. Any suggestions on where the problem could be? Thanks a lot, if you need more code, please let me know. Pictures of the problem"} {"_id": 7, "text": "Android emulator with acceleration and gyroscope simulation Is there an Android emulator that is compatible with eclipse that can simulate acceleration and tilting of a mobile device?"} {"_id": 7, "text": "Drawing game app How to use vector graphics instead of bitmap in Android? I have a problem concerning the concept of using vector graphics instead of bitmaps in order to draw on canvas. Usually to draw on canvas we set a bitmap to that canvas and we start drawing pixels on it by simply moving our finger on the screen. However, this method will result very pixelated relatively low quality drawings. It is noteworthy that there are some drawing apps that result in very smooth curves when you want to draw via them. After doing some googling and researching, I knew that there is the new concept of use vector graphics that is being used in order to draw smooth edged drawings on the screen. Look guys, the thing is when I developed my drawing app, I used bitmap (which was already there as an object given by Android) in order to draw cubic Bezier curves. No matter how much I tried to smooth my drawings out, I always get stair like edges. If you are interested in how I developed the curve, please read this. If not, just ignore this bold paragraph In order to draw the cubic bezier curves I simply took the sampled touch points and for every 4 points in these sampled points I calculated the 2 intermediate control points (the ones that the curve never touch) to create a bezier through the sampled points. For the curve to appear, I used bitmap and paint objects given by android. After getting the undesired result (low quality curve), I decided that I want to use vector graphics in order to do the same thing but with a higher quality. The thing is that I am very new to Vector Graphics, that I don't know where to start. My question is simple as is Is there a platform given to me by Android in order to use vector drawable like in the case of bitmap? If not, am I supposed to start this from scratch? I am clueless and any tip or hint from you will be greatly appreciated."} {"_id": 7, "text": "Augmented reality on Mobile platform iOS Is there a way that we can control the iOS device camera to an extent what colors it sees, what shapes it sees ? etc I'm speaking about the ability to read information before the image is captured. Consider my question as Possibility of making an augmented reality game on iOS phones. I dont find relevant help for my query in internet iOS developer site. Hence posting here."} {"_id": 7, "text": "Augmented reality on Mobile platform iOS Is there a way that we can control the iOS device camera to an extent what colors it sees, what shapes it sees ? etc I'm speaking about the ability to read information before the image is captured. Consider my question as Possibility of making an augmented reality game on iOS phones. I dont find relevant help for my query in internet iOS developer site. Hence posting here."} {"_id": 7, "text": "Android AndEngine creating a body behind the sprite exactly I am using AndEngine for Android. I created a body, but it is not behind the sprite as I wanted. Body.setTransform(Sprite.getX() 32, Sprite.getY() 32, 0) This is what I am currently using and this is how it appears. My body is the white circular borders, and my sprite is the red circle. and When I remove 32 from the code the body doesn't even appear. Extra code FIXTURE DEF PhysicsFactory.createFixtureDef( 1, density 0.75f, elasticity 0.5f, friction false) isSensor the Body Body PhysicsFactory.createCircleBody(this.physicsWorld, Sprite, BodyType.KinematicBody, this.FIXTURE DEF) Body.setUserData(\"eSprite\") this.physicsWorld.registerPhysicsConnector(new PhysicsConnector(Sprite, Body, true, true) my sprite is 65px .."} {"_id": 7, "text": "GdxRuntimeException uiskin.atlas I have problem when trying to use the uiskin.atlas from github libgdx. I've downloaded(cloned) it from libgdx.git but it just doesnt work. I get the following error Com.badlogic.gdx.utils.GdxRuntimeException Error reading pack file data uiskin.atlas And further down in the catlog it says Caused by java.lang.IllegalArgumentException 256,128 is not a constant in com.badlogic.gdx.graphics.Pixmap Format What does that mean? Anyone knows how to solve it? Im using the line skin new Skin(Gdx.files.internal(\"data uiskin.json\")) Im at work at the moment so can't give more info than this. The error happens both in Eclipse and in AIDE on my phone."} {"_id": 7, "text": "Z rotation causing skew Android OpenGL ES 2.0 If I rotate about the X, or Y axis there is no skewing however for a pure 2D game that does not help me. When I try to rotate about the Z axis however the quad I am rendering for the sprite starts to skew until it disappears at 90 degrees appearing again shortly after a slowly resuming a quad shape. As far as I can tell I have written the code correctly, it is as I have written it before on 2D projects and it worked there I am either missing something stupid or OpenGL ES 2.0 does something different then what I expect, some excerpts of code follow Projection View Matrix.setLookAtM(ViewMatrix, 0, 0, 0, 3, 0f, 0f, 0f, 0f, 1.0f, 0.0f) Matrix.orthoM(ProjectMatrix, 0, width 2, width 2, height 2, height 2, 0 , 100) Rotation Scale Translation(For in place set to identity first) Matrix.translateM(Translation, 0, x, y, 1.0f) Matrix.setRotateM(Rotation, 0, angle 0.05f, 0.0f, 0.0f, 1.0f) Matrix.scaleM(Scale, 0, 64,64,1.0f) Multiplication of Matrices Matrix.multiplyMM(MVPMatrix, 0, ProjectMatrix, 0, ViewMatrix, 0) Matrix.multiplyMM(MVPMatrix, 0, MVPMatrix, 0, Translation,0) Matrix.multiplyMM(MVPMatrix, 0, MVPMatrix, 0, Rotation, 0) Matrix.multiplyMM(MVPMatrix, 0, MVPMatrix, 0, Scale, 0) Thanks for any help."} {"_id": 7, "text": "How to change from 60FPS to 30FPS while keeping things smooth? Here is my current game loop final int ticksPerSecond 60 final int skipTicks (1000 ticksPerSecond) float dt 1f ticksPerSecond while(System.currentTimeMillis() gt nextGameTick amp amp loops lt maxFrameskip) updateLogic() nextGameTick skipTicks timeCorrection (1000d ticksPerSecond) 1 nextGameTick timeCorrection timeCorrection 1 loops On most devices I've tested my game on (this is an Android game BTW) it runs quite nice. As you can see, I'm using a fixed time step (defined as my ticks per second). If I reduce my Ticks Per Second to 30, everything runs at the same speed but is nowhere near as smooth. I keep hearing people say that 30fps should be OK for mobile games and everything should run great at 30 fps, but that's just not my experience. Would be grateful if someone could give me some pointers on how to achieve this."} {"_id": 7, "text": "Export Blender 3D animation to be played by Android OpenGLES Below code snippet shows the way to export coordinate of bones def export bone matrix(armature, bone, label, file handler) SystemMatrix Matrix.Scale( 1, 4, Vector((0, 0, 1))) Matrix.Rotation(radians(90), 4, 'X') if (bone.parent) Export babylon.write matrix4(file handler, label, (SystemMatrix armature.matrix world bone.parent.matrix).inverted() (SystemMatrix armature.matrix world bone.matrix)) else Export babylon.write matrix4(file handler, label, SystemMatrix armature.matrix world bone.matrix) I have create a 3D character in Blender, and add keyframes in it by transforming in some frames. From the graph editor, you can easily tell the all displacement of transformation translate, rotate, scale are all measured with respect to the original value in frame 0. Is it possible to write OpenGL in Android to animate the same 3D animation in Blender? I'd like to transform the 3D character translate, rotate in each frame according to the displacement value exported from Blender. Below lists the python function to export translate, rotate displacement in each frame def get bone action location(action, bonename, frame 1) loc Vector() if action None return(loc) data path 'pose.bones \" s\" .location' (bonename) for fc in action.fcurves if fc.data path data path loc fc.array index fc.evaluate(frame) return(loc) def get bone action rotation(action, bonename, frame 1) rot Quaternion( (1, 0, 0, 0) ) the default quat is not 0 if action None return(rot) data path 'pose.bones \" s\" .rotation quaternion' (bonename) for fc in action.fcurves if fc.data path data path and frame gt 0 and frame 1 lt len(fc.keyframe points) rot fc.array index fc.evaluate(frame) return(rot) Or I need to transform the meshes with vertex group controlled by root bone by the transform matrix SystemMatrix armature.matrix world bone.matrix? And for those controlled by child bones by the matrix in terms of (SystemMatrix armature.matrix world bone.parent.matrix).inverted() (SystemMatrix armature.matrix world bone.matrix)?"} {"_id": 7, "text": "Android cocos2d removing a sprite after animation I have an object going across the screen with an animation using the following code CCSpriteFrameCache.sharedSpriteFrameCache().addSpriteFrames(\"ninjastar.plist\") CCSpriteSheet projectileSheet CCSpriteSheet.spriteSheet(\"ninjastar.png\") addChild(projectileSheet) ArrayList lt CCSpriteFrame gt projectileSprites new ArrayList lt CCSpriteFrame gt () for (int i 1 i lt 4 i ) projectileSprites.add(CCSpriteFrameCache.spriteFrameByName(\"ninjastar\" i \".png\")) CCAnimation projectileAnimation CCAnimation.animation(\"throw\", 0.1f, projectileSprites) CCSprite projectile CCSprite.sprite(projectileSprites.get(0)) CCAction projectileAction CCRepeatForever.action(CCAnimate.action(projectileAnimation, false)) projectile.setPosition(CGPoint.ccp(winSize.width (projectile.getContentSize().width 2.0f), actualY)) actionMove CCMoveTo.action(actualDuration, CGPoint.ccp( projectile.getContentSize().width 2.0f 320, actualY)) projectileSheet.addChild(projectile) projectile.setTag(1) projectiles.add(projectile) CCCallFuncN actionMoveDone CCCallFuncN.action(this, \"spriteMoveFinished\") CCSequence actions CCSequence.actions(actionMove, actionMoveDone) projectile.runAction(actions) projectile.runAction(projectileAction) I'm using \"spriteMoveFinished\" to remove the sprite once it is done going across the screen public void spriteMoveFinished(Object sender) CCSprite sprite (CCSprite)sender projectiles.remove(sprite) sprite.stopAllActions() removeChild(sprite, true) However, when the sprite gets to the end of the screen it just stays stuck there on the last frame. How do I remove it completely?"} {"_id": 7, "text": "Detecting image curve to move a truck on this surface I have an image background in surface view I want to move something according to black surface.But i can not do this using height of this image as it return same height.and one more thing bitmap.getPixel is also not working.and my background is moving.So what is the way to achieve this feat"} {"_id": 7, "text": "How to implement constant velocity and collisions without gravity I am learning game development and i am trying to implement the AndEngineBox2D Extension such that my character is always moving at a constant velocity, when it collides with a body sprite, the character automatically changes direction (is deflected) and moves in the new direction until another collision has happened and the same is done repeatedly. My Question Is it possible to implement the changes in trajectory with AndEngineBox2D's physics world or i have to to handle it manually is java code."} {"_id": 7, "text": "Move Background in AndEngine for a Racing Game I am new to game development and AndEngine. I have small query about racing game. I am going to develop a bike racing game. For bike racing game we will move the background or the player. I am tried with andengine autoparallax background. But I didn't got the correct answer. I need to do a background like these screenshots in SpeedMoto. Can anyone help me to set the background."} {"_id": 7, "text": "Button change texture after click I need to make a button with texture. After button is pressed I want to change texture of button permanently. For example on of sound button. I tried this but it changes image only while I hold button. Thanks mSoundButton new ButtonSprite(30, 30, ResourceManager.getSoundButtonTR(), tiled texture region with image for sound on and sound off ResourceManager.getEngine().getVertexBufferObjectManager()) Override public boolean onAreaTouched(TouchEvent pTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) if(pTouchEvent.isActionDown()) SFXManager.toggleSoundEnabled() this.setCurrentTileIndex(1) return super.onAreaTouched(pTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY) mScene.registerTouchArea(mSoundButton) mScene.attachChild(mSoundButton)"} {"_id": 7, "text": "How well does Unity 3d work for both Android and iPhone? First off this question might be a bit broad so I apologize if it is. I am really just looking for peoples experiences and personal knowledge on the subject. I am looking to create a game for both Android and iPhone platform. I know Unity is a great game engine and my question is how well does it work for creating one code base to build for both Android and iPhone platforms? Time is a constraint on this project so I am very interested in how smoothly the process usually is when trying to build both applications and how much custom code must be written for each specific application. Any insite that people have on this topic would be much appreciated thanks."} {"_id": 7, "text": "In Unity, on an Android device, CaptureScreenshot writing to Phone, but persistentdatapath linking to the external card I'm using CaptureScreentshot() to get an image. But when I try to access it on an Android device it's giving me Could not find file \" storage emulated 0 Android data appname screenshot.png\" When I go the external storage, it's not there, but rather on the phone storage. So why is persistentdatapath accessing something different? My code is the following byte Bytes File System.IO.File.ReadAllBytes(currentScreenshotPathname) with thepathname obtained using currentScreenshotPathname System.IO.Path.Combine(Application.persistentDataPath, currentScreenshotName) Is there anyway to make the persistenDataPath go to the phone storage rather than emulated to read the file? I've tried changing the WriteAccess perimission to Externalas well as Internal in the player settings, but it's still the same. Edit Here's what's happening PersistentDataPath is storage emulated 0 Android data myapp files , but the screenshot is being saved to mnt sdcard Android data myapp files, despite the documentation saying that it should save to the PersistentDataPath."} {"_id": 7, "text": "Problem converting FBX file into XNB I create a Monogame Content Project to convert assets into XNB. For FBX file without texture there is no problem the file is correctly converted and when I load XNB into my project everything is ok. The problem occours when i have associated to fbx file a texture map in this case both FBX and PNG files are converted to XNB but when i try to load these XNB files into my project the following problem occours \"ContentLoadException Could not load Models maze1 asset as a non content file!\" Note maze1 is the XNB file that was converted from FBX. How can I solve this problem? Thank you in advance"} {"_id": 7, "text": "Touch point on the near plane I have a matrix created with either orthoM or frustumM GL function, where the near plane is logically the surface of the tablet. I would like to translate touch locations to their location on the near plane (that is, from device coordinates to the world coordinates). I assume this is a common enough activity so I'm wondering if a standard API function exists (or simple sequence) which can provide me with this data?"} {"_id": 7, "text": "Saving an interface instance into a Bundle All I've have an interface that allows me to switch between different scenes in my Android game. When the home key is pressed, I am saving all of my states (score, sprite positions etc) into a Bundle. When re launching, I am restoring all my states and all is OK however, I can't figure out how to save my 'Scene', thus when I return, it always starts at the default screen which is the 'Main Menu'. How would I go about saving my 'Scene' (into a Bundle)? Code import android.view.MotionEvent public interface Scene void render() void updateLogic() boolean onTouchEvent(MotionEvent event) I assume the interface is the relevant piece of code which is why I've posted that snippet. I set my scene like so ('options' is an object of my Options class which extends MainMenu (Another custom class) which, in turn implements the interface 'Scene') SceneManager.getInstance().setCurrentScene(options) Current scene is optionscreen"} {"_id": 7, "text": "How do I implement an AutoParallax Background in AndEngine GLES1? I'm using AndEngine GLES1. In my game, I use AnalogOnScreenControl to move a sprite and when it moves vertically, the background image also moves vertically. I want to do something like this that is in this link. I know that AutoParallax Background or BackgroundParallaxScrolling may be used. But how do I use it in my game?"} {"_id": 7, "text": "How do I access device camera in GameMaker Studio 1.4? I've looked everywhere in the documentation for GameMaker and I didn't find anything about how to access the camera."} {"_id": 7, "text": "How to specify colour in a single 32 bit value I'm writing my first game using OpenGL 2 ES (for Android), and I've currently got a particle engine and some player sprites running successfully. I'm using 4 floats for the colour of each particle which seems like total overkill. It makes sense that I should be able to use a single 32 bit int (or perhaps a single float) to hold the colours (perhaps in RGBA format) which would presumably save a lot of unnecessary loading copying processing, but I'm struggling to understand how I could do this. I guess that I would need to change the shaders to take the relevant format, and also i'd need to change the way I load the color shader attribute. My fragment shader has varying vec4 v Color gl FragColor v Color texture2D(u TextureUnit, gl PointCoord) and the attribute (passed into the fragment shader from the vertex shader) is set up with glVertexAttribPointer(aColourLocation, COLOUR COMPONENT COUNT, GL FLOAT, false, BYTES PER VERTEX, floatBuffer) I've searched the documentation for what I should change vec4 and GL FLOAT to, and what how I'd multiply the colour with the texture, and have tried a few things but with no success."} {"_id": 7, "text": "Scene2d Stage Actor setup issues I am creating a game using libgdx. In the same each level has a class. I have stage as a member variable of the class. To this stage, I add actors. Inside the levels class, I have attaced the input processor to the stage like below. stage new Stage() sviewPort new StretchViewport(OSR Constants.VIEWPORT WIDTH, OSR Constants.VIEWPORT HEIGHT) OrthographicCamera camera new OrthographicCamera(OSR Constants.VIEWPORT WIDTH, OSR Constants.VIEWPORT HEIGHT) camera.position.set(0, 0, 0) camera.update() sviewPort.setCamera(camera) stage.setViewport(sviewPort) Gdx.input.setInputProcessor(stage) The level object is instantiated in another class known as GameScreen. GameScreen implements the Screen interface. I am unable to detect touch events on my actors in the stage. Each actor has also been given bounds as per the world coordinates. I have added the following code on each actor to detect touch this.addListener(new InputListener() public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) System.out.println(\"touchdown at \" x \" \" y) return true )"} {"_id": 7, "text": "Android canvas.drawColor throws a null object reference I have two nearly identical methods, the first to draw a splash screen while assets are loading, and the second to draw all of the assets to the screen. The first throws a NullPointerException on this line canvas.drawColor(Color.argb(255, 0, 0, 0)) Here is my error Caused by java.lang.NullPointerException Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int)' on a null object reference 10 19 21 54 56.042 18973 18973 ? E AndroidRuntime at com.xyz.123.GameView.drawSplash(GameView.java 76) Here is my code in full package com.xyz.123 import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.view.MotionEvent import android.view.SurfaceHolder import android.view.SurfaceView public class GameView extends SurfaceView implements Runnable volatile boolean playing Thread gameThread null private Paint paint private Canvas canvas private SurfaceHolder holder private int screenWidth private int screenHeight private Background1ResourceList background1ResourceList private Background background1 private Background background2 private Background background3 private Context context private SplashScreen splashScreen public GameView(Context context, int screenWidth, int screenHeight) super(context) this.context context this.screenWidth screenWidth this.screenHeight screenHeight Initialize our drawing objects holder getHolder() paint new Paint() splashScreen new SplashScreen(context, screenWidth, screenHeight) drawSplash() background1ResourceList new Background1ResourceList() background1 new Background(context, background1ResourceList.getBackgroundResources(), screenWidth, screenHeight, 0.00f, 0.50f) background2 new Background(context, background1ResourceList.getBackgroundResources(), screenWidth, screenHeight, 0.33f, 0.80f) background3 new Background(context, background1ResourceList.getBackgroundResources(), screenWidth, screenHeight, 0.66f, 1.00f) Override public void run() while (playing) update() draw() control() private void update() background1.update() background2.update() background3.update() private synchronized void drawSplash() if (holder.getSurface().isValid()) First we lock the area of memory we will be drawing to holder.getSurface() canvas holder.lockCanvas() rub out the last frame canvas.drawColor(Color.argb(255, 0, 0, 0)) draw the backgrounds splashScreen.draw(canvas, paint) unlock and draw the scene holder.unlockCanvasAndPost(canvas) else System.out.println(\"surface not valid\") private synchronized void draw() if (holder.getSurface().isValid()) First we lock the area of memory we will be drawing to canvas holder.lockCanvas() rub out the last frame canvas.drawColor(Color.argb(255, 0, 0, 0)) draw the backgrounds background1.draw(canvas, paint) background2.draw(canvas, paint) background3.draw(canvas, paint) holder.unlockCanvasAndPost(canvas) public void pause() playing false try gameThread.join() catch (InterruptedException e) public void resume() playing true gameThread new Thread(this) gameThread.start()"} {"_id": 7, "text": "Specific Physics Lessons and Reference for Game Development What \"Physics stuffs\" should I learn in game developments? I'm reading about Verlet Integration, and I'm wondering what other lesson should I learn and if there are available resources can you please provide some link or anything. Thanks."} {"_id": 7, "text": "How can I use ParallaxBackground in AndEngine? I'm new to game development with AndEngine. I want to add ParallaxBackground but I don't know how to change the background when the player moves. I'm using arrows for moving a player. Now my question is where I write the code parallaxBackground.setParallaxValue(5) ? I have written this line in onAreaTouched method of arrow but it does not work. Code private Camera mCamera private static int CAMERA WIDTH 800 private static int CAMERA HEIGHT 480 private BitmapTextureAtlas bgTexture private ITextureRegion bgTextureRegion Override protected void onCreateResources() BitmapTextureAtlasTextureRegionFactory.setAssetBasePath(\"gfx \") bgTexture new BitmapTextureAtlas(getTextureManager(),2160,480,TextureOptions.REPEATING BILINEAR) bgTextureRegion BitmapTextureAtlasTextureRegionFactory.createFromAsset(bgTexture, this, \"background.png\", 0, 0) bgTexture.load() Override protected Scene onCreateScene() this.getEngine().registerUpdateHandler(new FPSLogger()) Scene scene new Scene() scene.setBackground(new Background(Color.BLACK)) final ParallaxBackground parallaxBackground new ParallaxBackground(0, 0, 0) final VertexBufferObjectManager vertexBufferObjectManager this.getVertexBufferObjectManager() parallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA HEIGHT this.bgTextureRegion.getHeight(), this.bgTextureRegion, vertexBufferObjectManager))) scene.setBackground(parallaxBackground) Robot robot new Robot() add Player final AnimatedSprite animatedRobotSprite new AnimatedSprite(robot.centerX, robot.centerY, 122, 126, (ITiledTextureRegion) robotTextureRegion, getVertexBufferObjectManager()) scene.attachChild(animatedRobotSprite) animatedRobotSprite.animate(new long 1250,50,50 ) add right arrow button Sprite rightArrowSprite new Sprite(0, CAMERA HEIGHT 70, rightArrowTextureRegion, getVertexBufferObjectManager()) Override public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY) switch (pSceneTouchEvent.getAction()) case TouchEvent.ACTION DOWN moveRight true parallaxBackground.setParallaxValue(5) break case TouchEvent.ACTION MOVE moveRight true break case TouchEvent.ACTION UP moveRight false break default break return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY) scene.attachChild(rightArrowSprite) scene.registerTouchArea(rightArrowSprite) scene.setTouchAreaBindingOnActionDownEnabled(true) scene.setTouchAreaBindingOnActionMoveEnabled(true) scene.registerUpdateHandler(new IUpdateHandler() Override public void reset() Override public void onUpdate(float pSecondsElapsed) if ( moveRight ) animatedRobotSprite.setPosition(animatedRobotSprite.getX() speedX, animatedRobotSprite.getY()) ) return scene"} {"_id": 7, "text": "Which app markets should I deploy my Android game to? I just launched my Android game today. I'm curious to know where I can deploy it. Of course, Google Play is the veritable king of markets, and my own game site will be next. After that, which marketplaces are mature and are worth deploying to? I looked at SlideMe GetJar Soc.io And some other ones that I didn't use YAAM (kept crashing and erroring out) 1Mobile (couldn't figure out how to upload my app) Insyde Market My question is really, which ones are out there and are worth uploading too? (And 1Mobile seems good, but just can't figure out how to upload.) Each site requires their own size screenshots and logo, so it's a bunch of extra work. I'd rather stick to the 80 20 rule and apply 20 effort to hit 80 of the markets."} {"_id": 7, "text": "GLES2.0 3D Android game performance and multi threading the update? I have profiled my mixed Java C Android game and I got the following result As you can see, the pink think is a C functions that updates the game. It does things like updating the logic but it mostly it generates a \"request list\" for rendering. The thing is, I generate DrawLists on C and then send them to Java to process and draw using GLES2.0. Since then I was able to improve update from 9ms down to about 7ms, but I would like to ask if I would benefit from multi threading the update? As I understand from that diagram is that the function that takes the most time is the one you see it's color on the timeline. So the pink area is taken mostly by update. The other area has MainOpenGL.Handle as it's main contributor(whch is my java function), but since it's not drawn to the top of the diagram I can conclude other things are happening at the same time that use the CPU? Or even GPU stuff that isn't shown in this diagram. I am not sure how the GPU works on this. Does it calculate stuff in parallel to the CPU? Or is it part of the CPU usage as in SoC? I am not sure. Anyway, in case GPU things DO happen in parallel to CPU, then I would guess that if I do this C Update in parallel to the thread that makes the OpenGL calls, I might make use of \"dead CPU time\" due to GPU stalling or maybe have the GPU calls getting processed earlier because it won't have to wait for Update to finish? How do you suggest to improve performance based on that?"} {"_id": 7, "text": "Error compiling irrlicht android using ndk in Mac I'm new to irrlicht and I have started with irrlicht android port. I have made the following changes to android.mk file LOCAL CFLAGS O3 DANDROID NDK DDISABLE IMPORTGL I. .. include I. include I documents karthik android android ndk r9 platforms android 18 arch arm usr include LOCAL LDLIBS L documents karthik android android ndk r9 platforms android 14 arch arm usr lib libGLESv1 CM.so ldl llog L documents karthik android android ndk r9 platforms android 14 arch arm usr lib libGLESv1 CM.so I have tried compiling irrlicht android using ndk build in terminal.It showed the following errors at first In static member function 'static void irr os Printer log(const c8 , irr ELOG LEVEL)' error format not a string literal and no format arguments Werror format security In static member function 'static void irr os Printer log(wchar t const , irr ELOG LEVEL)' error format not a string literal and no format arguments Werror format security In static member function 'static void irr os Printer log(const c8 , const c8 , irr ELOG LEVEL)' error format not a string literal and no format arguments Werror format security In static member function 'static void irr os Printer log(const c8 , const path amp , irr ELOG LEVEL)' error format not a string literal and no format arguments Werror format security make obj local armeabi objs irrlicht os.o Error 1 and then I googled that and made changes in os.cpp file as follows Changed the code, android log print(ANDROID LOG INFO, \"log\", message) to android log print(ANDROID LOG INFO, \"log\",\" s\", message) This change solved that issue, and then I got another error In file included from jni importgl.cpp 55 0 jni importgl.h 37 22 fatal error GLES egl.h No such file or directory Again I changed GLES egl.h to EGL egl.h and solved that issue, got fatal error irrlicht.h No such file or directory I even solved this , atlast I'm here with this error error 'EglDisplay' was not declared in this scope error 'EglSurface' was not declared in this scope error 'EglWindow' was not declared in this scope error 'EglContext' was not declared in this scope"} {"_id": 7, "text": "Ball Physics for Android Game I am starting work on a new Android game and I haven't had any experience implementing physics before. I am trying to steer clear of external libraries such as box2d, not just because I think it is overkill for my project, but I also want to code it myself for the experience. I am more just interested in getting 1 ball to bounce around the screen and bounce off of objects in my world. The game is in 2D and I was just looking for some advice on where to start with ball physics? I know I will need gravity, x y velocities... etc. I know I need to calculate how high the ball needs to bounce based on how fast it hit the object, I also know I will need to calculate the correct angle that the ball needs to bounce at. Just hoping to get some ideas on a good place to start and things I will need to take into account."} {"_id": 7, "text": "how to render small texture on another texture? can anybody help me to render small texture on another texture. i.e I have one background image, when user touches on the screen it should draw small(circle or any object) on it. can anybody suggest me good tutorial to starts with it?"} {"_id": 7, "text": "Android multi screen rendering Is it possible on Android to render specifically only, to the connected Monitor TV on the hdmi port? If so, is it possible to use OpenGL ES to render a different scene on the monitor and on the device's screen? I would like the tablet to become more of an input device when it is connected with a monitor tv and my game to be rendered just to this screen. If nothing is connected, then the device's screen should be used. Ideally I would render a small interface (with buttons and text only) on the android tablet and the game itself on the monitor. Can this be done? How?"} {"_id": 7, "text": "What is Google Play Services Multiplayer? This question might be off topic, i don't know where should i ask it. What's the difference between Google Play Real Time Multiplayer, Google Play Turn Based Multiplayer and sockets?"} {"_id": 7, "text": "Play videos with LibGDX Is there a way to play videos with LibGDX? I want to put a video as my splash screen in Android, but I dont want to use the Android SDK, because I am using LibGDX and I am almost finished"} {"_id": 7, "text": "Sounds make Andengine Scene junky I have a GameScene which has a character (animated sprite), AutoParallaxBackground background with quite large textures and no more than 3 other items attached to the scene at a time, previous 3 items are dispose() ed accordingly, background music and item sounds. Background music is instantiated with MusicFactory, Sounds are played on SoundPool. In between switching these scene we are loading resources asynchronously, reading the streams and instantiation is done in AsyncTask and the loading textures to the hardware is done on UpdateThread GLThread. If I turn off the background music, this starts to happen totally random. I'm experiencing scene junking on at first flow MenuScene 1st Stage (GameScene). After a while lag does not happen, rather than occasionally or random. Junk is happening when aforementioned 3 items are attached on the Scene and a sound is played along, note that background music is playing at the same time. Detaching previous 3 items is \"optimized\" to reduce GC calling almost perfectly. When the lag occurs GC EXPLICIT is showed in the logcat. What I have tried Playing the sounds and music on different thread, IntentService, dedicated Service. Reduced calls to mScene.detachChild(child) and other scene methods to avoid iterations over children of the scene. Detaching IEntitys with matcher to avoid iteration. Inspected sound files' integrity with ffmpeg for possible errors Could .dispose(), unloading the textures from hardware or detachChild() causing this junk? Could be marked object for GC from the async tasks be causing this? What else could be contributing to this issue?"} {"_id": 7, "text": "In OpenGl ES 2, should I allocate multiple transformation matrices? In OpenGl ES 2, should I declare just one transformation matrix, and share it across all objects or should I declare a transformation matrix in each object that needs it? for clarification... something like this public class someclass public static float 16 transMatrix new float 16 ... public static void translate(int x, int y) do translation here public class someotherclass ... void draw(GL10 unused) someclass.translate(10,10) draw verses something like this public class obj1 public static float 16 transMatrix new float 16 ... void draw(GL10 unused) translate draw public class obj2 public static float 16 transMatrix new float 16 ... void draw(GL10 unused) translate draw"} {"_id": 7, "text": "How much memory can i safely use on android? To make my game more fluid, I try to prevent memory allocations during the game I am writing. To that end, I allocate a whopping 16MB of buffers on startup and then use those as I go along. When I check in Eclipse my game now uses 24MB in total, which does not change noticeably during the game. This all works fine on the phone I have now (android 2.3, motorola defy) but I wonder if I'm going to run into problems with this on other phones or tablets that run android 2.2 or higher (which is what I'm aiming for)?"} {"_id": 8, "text": "SDL2 linux fullscreen issue at lower than desktop resolution Having a problem trying to get proper fullscreen in linux. I'm using 1440x900 on desktop. When i set SDL to use 1280x720 as fullscreen, it does change screen resolution. But if i drag the mouse cursor to the bottom or right edge of the game screen, it \"scrolls\" the screen beyond the game surface and makes part of the desktop visible. Here's how I set the window screen gameWindow SDL CreateWindow( \"SDL Tutorial\", SDL WINDOWPOS CENTERED, SDL WINDOWPOS CENTERED, screenWidth, screenHeight, SDL WINDOW FULLSCREEN SDL WINDOW BORDERLESS ) Am i missing some flag(s) perhaps? Is this a common problem? I'm on Linux Mint MATE (Rosa). This problem also occurs when trying to run the same build in an Openbox session. Using nVidia drivers (x64, v340.96) from nvidia.com, on 9600 GT card(s). No twin dual screen or second Workspaces. Any good tips on how to avoid or workaround this issue?"} {"_id": 8, "text": "How to create the \"drunk camera\" effect in GTA 4? If you have played GTA 4, then you have probably been drunk at some stage. This is one of the best intoxicated simulators I have ever seen. It is actually hard or sometimes almost impossible to drive a vehicle while drunk in this game. I know that a lot of the things that make up this drunk experience are changes to the controls or having random changes in direction, but how would the camera be done? The camera seems to wave in and out and side to side. It also has changing blur, and other effects going on. Would this be some kind of shader? What are the effects that are used on top of each other to create the experience?"} {"_id": 8, "text": "rendering a reflection on a texture I want to render reflection on a planar surface but the reflecting surface has a texture mapped onto it.Would the normal technique of using stencil buffer and then blending in the reflected image with the reflecting surface in this case? If not then could some one suggest me how to render reflection on a surface that has a texture mapped onto it? Thanks"} {"_id": 8, "text": "What are these odd distortions on far away textures? I'm currently writing a simple voxel engine just to get some practice in, and I'm coming across some odd issues. In order to generate terrain, I create a mesh and then assign UV coordinates on a texture atlas to each vertex. Whenever I run the game, I get strange distortions, like these I've tried doing a few things so far Generating mip maps for the texture atlas. Play around with the max size of the texture atlas. Play around with the format of the texture atlas. Unfortunately, none of these have worked so far. As of right now, the import settings on the texture atlas itself look like this Is there any way I can get rid of these obnoxious distortions?"} {"_id": 8, "text": "Should I make my games graphics lower quality so everyone can play it? The game I'm working on targets lower end graphics capabilities machine users. Should I make my game's graphics lower quality so that everyone can play it or make its graphics high quality so that people must go and buy a new GPU to play it?"} {"_id": 8, "text": "What's the difference between using hardware accelerated APIs and the OS's drawing API? On Windows, I can do drawing with the OS API without OpenGL or D3D. The code I am writing will make calls to a device driver and tell the GPU what to do regardless, right? How is using OpenGL different exactly? Do these libraries have code that will interact with the GPU differently than just the Windows API does?"} {"_id": 8, "text": "How do you make use of all texture units on today's graphics cards? I saw a review of the GeForce GTX 460 graphics card. It has 56 texture units. I'm not that knowledgeable about graphics effects. But, the ones I know use around 3 or 4 texture units. In this graphics card case, that would leave a lot of texture units idle. How are these graphics cards with so many texture units used?"} {"_id": 8, "text": "How to make proper animations for a html5 game? I am working on a web based MMORPG in html5. Therefore, I think about using Phaser.io to be the main engine of the game on the client side. I want the game to be isometric and I am wondering how to make proper sprites animations gfx for the game. I don't want my graphic team to have too much pain. Would it be possible, for example, to use any kind of \"vectorial spritesheet\" so that I can zoom in and have a better look at the character. On the other hand, I don't want the \"stuff\" (hat, armor, etc) to be too hard to \"plug\" on the character in all the different orientations. I thought about using some kind of flash like system (my game is based on the french MMO Dofus which only uses flash for its client side but no web based techno) But I don't know anything about flash, can I integrate it inside a canvas and does it mux well with raster images like png or jpg? What alternative could I use?"} {"_id": 8, "text": "Cocos2d x setContentSize, setScale give poor graphic quality I want to create sprite with size is relative to the screen size. I.e Sprite size is equal to screen width 0.2. I use setContentSize and setScale but it gives ugly and poor graphic quality. I've read about multiple resolution supports, but it doesn't work on this case because i need sprite size adapt to the any screen size. Testing on iPhone 7, i scale an image from 512x512 to 64x64. This is error of cocos2d x or anyway to archive it?"} {"_id": 8, "text": "Project 2d click touch onto 3d plane I have a 3d scene that contains an infinite plane that is NOT parallel to the camera (so every screen coordinate corresponds to a point on this plane in other words, there are no possible invalid clicks touches). I have all the information you'd expect to work with camera pos, dir, fov, aspect ratio, the 3d points defining the plane (either as a triangle, or as a normal distance), the view projection matrices that project it onto the screen, etc... I haven't found anything online that answers this in a straightforward way. Please no \"use this or that library\". Also, if you're going to say \"invert the matrix\", please give a way to go about doing that (I don't think the matrix is easily possibly invertable, as the \"project to 2d\" process involves the divide by w step, rendering the final translation between 3d to 2d non affine)."} {"_id": 8, "text": "Object Transparency Dithering (as shown in Super Mario Odyssey) A couple games I've been playing recently all have a similar goal of dithering objects when they approach the near clip plane. Super Mario Odyssey applies this dithering near clip plane effect, but along with object intersection dithering for objects like Mario. I have an example of this dithering in Super Mario Odyssey later in this post. How would one go about creating this effect in their graphics solution of choice? The gifs might take a little while to get started. I couldn't get them to each be under 30 mb ( Example in Super Mario Odyssey The balloon of the Odyssey doesn't \"exit dithering\" until the camera is a good distance away from it. This could mean dithering is calculated based on object distance from camera, instead surface distance. Flag starts out with a small dither density, and Mario has no dithering applied to him. Once the flag is fully opaque, Mario becomes dithered, but only in the portions that is covered. Also note Mario's coat tail has the \"transparency dithering\" applied to it. How are the object's shaders structured to allow this compound effect? Below is a blown up image of Mario being dithered. Notice how dithering exists in intersection regions, and when behind objects!"} {"_id": 8, "text": "Can I develop on the Oculus Rift with below the minimum required hardware? I have tried to see if my GTX 960m supports VR and sadly it seems I need minimum GTX 970m, still I have seen videos that if you overclock your 960m you can get a decent 115 frames. My question is, can I still develop games for the Oculus Rift in my 960? I can't afford now to buy assets, oculus and a new laptop."} {"_id": 8, "text": "Minecraft What is the reasonable face vertex limit for custom models? When adding custom models to function as tile entity representations, what is a reasonable ceiling based on performance to maintain for individual models? Assume that the player will have the potential possibility to place as many of these as desired, but functionally it would also be reasonable to assume no more than 20 would have to be rendered at once. If the answer has changed between significant versions of the game, it would be nice if that could be reflected"} {"_id": 8, "text": "Why do games ask for screen resolution instead of automatically fitting the window size? It seems to me that it would be more logical, reusable and user friendly to implement flexible, responsive UI layout over a 3d or 2d screen, which can then be run on any screen resolution. Some modern games auto detect screen resolution and adjust the game to that, but the option to change the resolution still remains in the settings. Why is this option there? My guess is that this is one way to provide older machines with a way to improve performance by rendering less graphics and just stretching them across the screen, but surely there are better ways of improving performance (choosing different texture and model qualities, for example)."} {"_id": 8, "text": "boolean operations on meshes given a set of vertices and triangles for each mesh. Does anyone know of an algorithm, or a place to start looking( I tried google first but haven't found a good place to get started) to perform boolean operations on said meshes and get a set of vertices and triangle for the resulting mesh? Of particular interest are subtraction and union. Example pictures http www.rhino3d.com 4 help Commands Booleans.htm"} {"_id": 8, "text": "What is a good alternative to Unified Shader for Shadows? Most shadow systems I have seen use a unified shader system for shadowing techniques, resulting in an uber shader for the projects. What alternatives do you find work well or is the unified shader the best approach?"} {"_id": 8, "text": "Do I have to keep textures in Android games smaller than 1024 2? I have read tips in books and article that point out, if you are making a game for Android, make sure your textures are lt 1024 2, or you'll not reach all your potential customers. I have never found a concrete statistic that proves this claim. What are we talking about, here, 5 of Android devices only support 1024? 10 ? 80 ?"} {"_id": 8, "text": "How to create the \"drunk camera\" effect in GTA 4? If you have played GTA 4, then you have probably been drunk at some stage. This is one of the best intoxicated simulators I have ever seen. It is actually hard or sometimes almost impossible to drive a vehicle while drunk in this game. I know that a lot of the things that make up this drunk experience are changes to the controls or having random changes in direction, but how would the camera be done? The camera seems to wave in and out and side to side. It also has changing blur, and other effects going on. Would this be some kind of shader? What are the effects that are used on top of each other to create the experience?"} {"_id": 8, "text": "How to simulate a spinning helicopter rotor visual effect programatically? I decided to display an animation that conveys to the viewer that a narrow flat surface is spinning really fast(such as an helicopter's rotor blade). Does anyone have any experience in implementing this effect and could provide an implementation? Please remember a rotor on video looks different than it does in real life. I need to make the rotor look like it does in real life and not on video."} {"_id": 8, "text": "How do mobile mmo's deal with the graphical resources? I'm am creating an MMO(probably won't be so massive), and was wondering how to deal with the graphical resources. Obviously, I can't have what could be possibly a few gigs of images and animations loaded up to the client, so I need another way of doing it. I have tried having a php webserver that updates itself and writes to a file that the client draws, however this seems slow. How can I speed up the process of updating the graphics while not having too much into the client?"} {"_id": 8, "text": "Project 2d click touch onto 3d plane I have a 3d scene that contains an infinite plane that is NOT parallel to the camera (so every screen coordinate corresponds to a point on this plane in other words, there are no possible invalid clicks touches). I have all the information you'd expect to work with camera pos, dir, fov, aspect ratio, the 3d points defining the plane (either as a triangle, or as a normal distance), the view projection matrices that project it onto the screen, etc... I haven't found anything online that answers this in a straightforward way. Please no \"use this or that library\". Also, if you're going to say \"invert the matrix\", please give a way to go about doing that (I don't think the matrix is easily possibly invertable, as the \"project to 2d\" process involves the divide by w step, rendering the final translation between 3d to 2d non affine)."} {"_id": 8, "text": "Opengl in 500 lines barycentric calculation question https github.com ssloy tinyrenderer wiki Lesson 2 Triangle rasterization and back face culling I cannot figure out how we go from uAB vector vAC vector PA vector 0 to the linear system with those subscripts x and y? Is there another way of explaining how we take three vectors, split them into x and y type vectors, and produce a cross product that can be used to find the barycentric coords (u, v, w)? Also, I am not sure why there is a division by the z component of the cross product in last line of the barycentric function. Maybe the answer to my first question will make this more obvious. Below is a picture of the section of the tutorial where I am stuck. Link to full page is above."} {"_id": 8, "text": "Why do people put a gif animation into a single bitmap? Possible Duplicate 2D graphics why use spritesheets? Something like this file from here I haven't write game with animated gif before.... So I wonder why. When I unpack some game, I see them in this kind of format as well. Why they are not divide them into individual bitmap? When they are using it, do they IMPORT them into individual bitmap? or just use display them using offset?"} {"_id": 8, "text": "How do you ensure consistent experience across multiple graphics cards (or even driver versions)? So I was writing a simple 2D game with OpenGL and SDL and had this problem when there was awful tearing when running in windowed mode (even though I explicitly asked SDL SetVideoMode to use double buffering). Didn't worry about it all too much because most of the time the game grabs the entire screen, windowed mode is just for debugging. Anyway, yesterday I updated my nVidia drivers and tearing disappeared, the game runs smooth and looks nice in windowed mode too. I can see how the problem may be in the graphics driver, but this leads to a question. Obviously, professional game developers have to deal with a lot of different hardware software configurations. What are the techniques they use to make sure the game looks the roughly the same on different graphics cards or even the same model of graphics card, but with different driver versions?"} {"_id": 8, "text": "What is the purpose for multiple windows in games? A lot of game development APIs recently got support for multiple windows (such as SDL 2, and GLFW 3). But why did they add that feature? I've never seen a game in my life use multiple windows (with the exceptions of a launcher, or a messagebox). Is there something I'm missing here? Is there an actual game development purpose to it? I'm very confused of why they did that."} {"_id": 8, "text": "Displaying whole screen image on multiple devices without stretching In my(Android) game, all of my sprites are scaled against to a particular ratio (this 'guide' ratio stays the same regardless of the actual ratio of the screen on which they are to be displayed) these sprites are then displayed on screens of different ratios. This way, the game can run full screen on any device, it simply means that more less of the game is visible on some devices than it is on others. However, I can't work out how to diaplay a large (full screen) image on different devices. The only thing I can think of is to simply create the original image for the larger display and the crop it down to fit other ratios. Something like this So here, the image on the right is how the picture will show on the original device (full screen with no cropping), the device on the left has a smaller width. But what if this runs on a device with a larger screen? In this case is it simply a case of (uniformly) stretching the image until it fills the screen? Would be grateful for some guidance."} {"_id": 8, "text": "Rendering 2d sprites into a 3d world? In opengl how do I render 2d sprites in opengl given that I have a png of the sprite? See images as an example of the effect I'd like to achieve. Also I would like to overlay weapons on the screen like the rifle in the bottom image. Does anyone know how I would achieve the two effects? Any help is greatly achieved."} {"_id": 8, "text": "What are these odd distortions on far away textures? I'm currently writing a simple voxel engine just to get some practice in, and I'm coming across some odd issues. In order to generate terrain, I create a mesh and then assign UV coordinates on a texture atlas to each vertex. Whenever I run the game, I get strange distortions, like these I've tried doing a few things so far Generating mip maps for the texture atlas. Play around with the max size of the texture atlas. Play around with the format of the texture atlas. Unfortunately, none of these have worked so far. As of right now, the import settings on the texture atlas itself look like this Is there any way I can get rid of these obnoxious distortions?"} {"_id": 8, "text": "Checking if two lines are crossing How can I check if two lines (created with function love.graphics.line) are crossing themselves? I may use this ability to create procedural maps via graphs."} {"_id": 8, "text": "SDL deleting an image from the screen? Well, I'm sort of a beginner to SDL, and I was wondering how one would go about deleting an image from the screen and replacing it with another? I attempted to do this, but it didn't seem to change it, how would someone with more experience than me go about doing it?"} {"_id": 8, "text": "What does the term \"channel\" mean when used in regards to computer graphics? I was studying terminology for computer graphics, and this statement came up that confused me. The image can have alpha channels for transparency. I tried searching for the meaning of the term \"alpha channel,\" but I got really confused by the definition which used another concept called a \"channel.\" I'm not really sure what this means, so could someone be kind enough to please explain this term to me?"} {"_id": 8, "text": "Correctly bitmasking path tiles based on existing paths Currently, I have a bitmasking implementation that sometimes incorrectly bitmasks the tiles. Conventionally, it is done correctly, and the math etc is sound, but it achieves results such as the following This is similar to what you might expect, and looks fine when doing simple x shaped crossings. However, I would like for the images to remain unchanged in some of these cases. For instance, the parallel paths in the third image would remain parallel paths instead of being bitmasked into many crossings. In the first and second images, only the parts of the path highlighted in the following images would be bitmasked (Different parts of path labelled for clarity.) If I purely update only the tiles that make up the newest path, I again get good results in simple x shaped crossings, however I get results such as those demonstrated in the following image What could I do to achieve results where this would not occur? I have though about adding some sort of flag to the tile to indicate that it is a crossing, but how could I detect that?"} {"_id": 8, "text": "what is order of implementation of matrix transforms? What is the meaning of Tr Sh Ro Sc M ? How is matrix M written to form the graphic transformation 1st Sc Scale, 2nd R Rotate, 3rd Sh Shear 4th T Translate ? Is the matrix M above written properly in a \"post multiplcative\" format\" T Sh R Sc , but executed Scale, Rotate, Shear , finaly Translate ?"} {"_id": 8, "text": "About floating point precision and why do we still use it Floating point has always been troublesome for precision on large worlds. This article explains behind the scenes and offers the obvious alternative fixed point numbers. Some facts are really impressive, like \"Well 64 bits of precision gets you to the furthest distance of Pluto from the Sun (7.4 billion km) with sub micrometer precision. \" Well sub micrometer precision is more than any fps needs (for positions and even velocities), and it would enable you to build really big worlds. My question is, why do we still use floating point if fixed point has such advantages? Most rendering APIs and physics libraries use floating point (and suffer it's disadvantages, so developers need to get around them). Are they so much slower? Additionally, how do you think scalable planetary engines like outerra or infinity handle the large scale? Do they use fixed point for positions or do they have some space dividing algorithm?"} {"_id": 8, "text": "Outsourcing Artwork Hourly or Per Project? I've hired people to produce art and graphics before, but only ever at a per job rate and that has worked out well. This question is for both artists and the people who hire them As a buyer, are there any situations or types of projects you've experienced where it worked out better billed at an hourly rate? For artists, do you have a preference for one over the other and if so, why?"} {"_id": 8, "text": "Basic Collision Detection Math First a bit of background. I have yet to read a book on game development, though I do plan on picking one up sometime. A long time ago I made a simple pong game, followed by a simple Arkanoid type game. In both games I figured the collision detection by comparing the x, y, and z of the ball to the paddle. I did this calculation for each side of the ball and each side of the paddle. It was the only way I could think of to do it at the time. It was something along the lines of if (thing.x gt otherthing.x) if (thing.y gt otherthing.y) And so on. Is this the normal way of figuring collision detection? Did I over complicate it, or is this the basic way that it's done?"} {"_id": 8, "text": "Do SpriteBuilder's Smart Sprite Sheet need to be loaded to memory? When I create an Smart Sprite Sheet Folder using SpriteBuilder and publish it, must I load that SpriteSheet into memory \"FrameCache\" with code or does SpriteBuilder do this automatically (so I just have to access any image inside of SpriteSheet?)"} {"_id": 8, "text": "How do I load graphical resources asynchronously? Let's think platform agnostic I want to load some graphical resources while the rest of the game is running. In principle, I can load the actual files on a separate thread, or using async I O. But with graphical objects, I will have to upload them to the GPU, and that can (usually) only be done on the main thread. I can change my game loop to look something like this while true do update() for each pending resource do load resource to gpu end draw() end while having a separate thread load resources from disk to RAM. However, if there are many big resources to load, this could cause me to miss a frame deadline and eventually get dropped frames. So I can change the loop to this while true do update() if there are pending resources then load one resource to gpu remove that resource from the pending list end draw() end Effectively loading only one resource per frame. However, if there are many small resources to load, loading all of them will take many frames, and there will be a lot of wasted time. Optimally, I would like to time my loading in the following manner while true do time start get time() update() while there are pending resources then current time get time() if (current time time start) time to load(resource) gt 1 60 then break load one resource to gpu remove that resource from the pending list end draw() end This way, I would only load a resource if I can do it within the time I have for that frame. Unfortunately, this requires a way to estimate the amount of time it takes to load a given resource, and as far as I know, there are usually no ways to do this. What am I missing here? How do many games get to load all their stuff completely asynchronous and without dropped frames or extremely long loading times?"} {"_id": 8, "text": "Small 3D Scene Graph I'm looking for a 3D graphics library (not a complete game engine). Preferred a scene graph. Something small (unlike jME, XNA or Unity), that I can easily expand and change. Preferred features Cross Platform Wrriten in Java Scala (JOGL or LWJGL), C (preferred OpenTK), Python or JavaScript WebGL. Support for OpenGL is a must. Direct3D is optional. Some material system Full support for some model format with full animation support (preferred COLLADA) Level of Detail (LOD) support Lighting support Shaders, GUI, Input and Terrain Water support are also preferred, but not required Thanks!"} {"_id": 8, "text": "rendering a reflection on a texture I want to render reflection on a planar surface but the reflecting surface has a texture mapped onto it.Would the normal technique of using stencil buffer and then blending in the reflected image with the reflecting surface in this case? If not then could some one suggest me how to render reflection on a surface that has a texture mapped onto it? Thanks"} {"_id": 8, "text": "Aquaria like graphics look in 3DS Max? I'm making a 2D game and I'm starting to think about graphics. I'm pretty good at 3D modelling, but I'm not very good at drawing or painting. I was wondering if there were settings, or even a renderer that someone could recommend that could achieve the nice painted look found in Aquaria. Thanks."} {"_id": 8, "text": "How to make image bigger than the screen to be slideable in the screen in monogame for windows phone 8? (Idk if my title is correct, because when I google it, there is no related result I guess) I am not sure how to explain it correctly, but I am making a plain 2D, tile based, tactic game in windows phone 8 using monogame. I want to make my map is \"slideable\". With \"slidable\" I mean I can draw larger images (in total) than my screen and then slide it so I can view a certain area of the drawn images Example I have a screen which dimension is 1280x720. I have a 1500x1500px image, which consists of 15 tiles, which is 100x100px each, which each tiles is redrawn each times the \"Draw\" is called. If the image is larger than the screen, the displayed area will be trimmed and of course, making a 220x780px area that is unseenable. The only way to see all of it is through \"sliding\" the screen around, so I can see all the area. My question is How to make that happen? Because in default, the screen is unslideable and the image remains trimmed. Sorry if my question and explanation is not clear enough. Clarify it as much as you like. Thank you."} {"_id": 8, "text": "What is \"ROAM\" related to terrain rendering? I saw it mentioned on this question, but no one explained what it is."} {"_id": 8, "text": "How do I scale down pixel art? There are plenty of algorithms to scale up pixel art. (I prefer hqx, personally.) But are there any notable algorithms to scale it down? My game is designed to run at a resolution of 1280x720, but if it is played at a lower resolution I still want it to look good. Most pixel art discussions center around 320x200 or 640x480 and upscaling for use in console emulators, but I wonder how modern 2D games like the Monkey Island Remake could look good on lower resolutions? Of course ignoring the option of having multiple versions of assets (i.e. mipmapping)."} {"_id": 8, "text": "Precomputing Visibility Having noticed that UDK (Unreal) and Unity 3 include similar pre computed visibility solutions that unlike Quake are not dependent on level geometry, I've been trying to figure out how the calculation is done. The original Quake system is well documented You divide the world into convex volumes that limit both the camera and the geometry. Each volume has a list of all the other volumes that are visible from it. Visibility would be computed by firing rays at some random distribution of points in the target volume and see if any hit. And because the position of the camera in the source volume could have an effect, those thousands of rays would have to be fired from multiple places in the source cell. So what I'm wondering is if there's any been fundamental change to this basic scheme in the intervening 15 or so years? I can see how to adapt it to a UDK Unity scheme that has regular source volumes and deals mostly with arbitrary meshes as the targets, but is there a better way than stochastic ray testing?"} {"_id": 8, "text": "How to combine objects in a rendered scene with and without bloom effect? I'm working on a game and engine as I go under OpenGL. I've had a bloom effect in place for a while that works as a post procesing effect on the entire screen. It's been fine up until now. I have an object that is made up of a few meshes, and one of these meshes is mostly white. The result is it blooms like crazy, but I really don't want it to. The only way around it I can see is that the objects I do want to have bloom would need to be rendered to a bloom framebuffer from which I can bloom (and store the depths) to then mix back in with the rest of my scene. Is this the only way to go about it? It seems like a lot of work to simply isolate something from a screen wide affect."} {"_id": 8, "text": "How to make game appear to run faster? I believe I read somewhere that there is a technique which will make games appear more smooth than they are. I believe it is some visual trick, but I don't remember which one. (It is be something like \"You percieve game to be more fluid if there is good shadows\"). I may be wrong and there is no such thing."} {"_id": 8, "text": "How do I generate a random curve for landscape (like Worms)? Possible Duplicate How do I generate terrain like that of Scorched Earth? How can I generate Worms style terrain? I must build random curve line for the 2D Game on the BitMap (like in Worms, from the side). Teacher said that I should do it using Terrain Generation through recourcy (I work in Delphi 7). I understand the main principle, but I don't know how to introduce it as code. All measurements according to the screen resolution."} {"_id": 8, "text": "Slick2D translate scale translate doesn't return to the old position I am trying to implement zoom using Slick2D library. As I understand, to zoom something on non (0,0) coordinates, we need translate so the target point is in (0,0) apply scale factor translate the target point back from (0,0) Code example aGraphics.translate( width 2, height 2) aGraphics.scale(2,2) aGraphics.translate(width 2, height 2) The issue is, as far I understand, that the scale factor is applied to the translation too. To compensate this, I have use the next code aGraphics.translate( width 2, height 2) aGraphics.scale(2,2) aGraphics.translate(width 4, height 4) Is this expected behaviour for graphics ? Can I workaround the above effect using push pop matrix ?"} {"_id": 8, "text": "Precomputing Visibility Having noticed that UDK (Unreal) and Unity 3 include similar pre computed visibility solutions that unlike Quake are not dependent on level geometry, I've been trying to figure out how the calculation is done. The original Quake system is well documented You divide the world into convex volumes that limit both the camera and the geometry. Each volume has a list of all the other volumes that are visible from it. Visibility would be computed by firing rays at some random distribution of points in the target volume and see if any hit. And because the position of the camera in the source volume could have an effect, those thousands of rays would have to be fired from multiple places in the source cell. So what I'm wondering is if there's any been fundamental change to this basic scheme in the intervening 15 or so years? I can see how to adapt it to a UDK Unity scheme that has regular source volumes and deals mostly with arbitrary meshes as the targets, but is there a better way than stochastic ray testing?"} {"_id": 9, "text": "Cannot find the Cocos2d templates I am about to upgrade to the last version of Cocos2d and would like to uninstall my current Cocos2d templates before installing the new one but cannot find the templates to delete. I have looked at a number of web comments on this such as Uninstall Cocos2D ans another uninstall example but to no avail. However, I still see Cocos2d in my Xcode (4.5) framework. I have been searching my directories but cannot find it. Is there anyone out there who can give me a hint where to find it so i can delete in?"} {"_id": 9, "text": "Cocos2d Check if place is free before moving (all objects) Is there a method in Cocos2d like CGRectIntersectsRect, except instead of limiting it to one sprite, it checks for ALL objects?"} {"_id": 9, "text": "Why does the Texture placement of my CCSprite slightly shift when changing it's location? So I've been seeing this issue for a while now. When using a delta method to change the location of a CCSprite, the placement of texture of my sprite slightly moves into the direction where I'm headed, while the physicsbody stays the same. This is really noticeable, since I'm using CCActionFollow to center this sprite in the view at all times. The code is displayed below. Is this normal behaviour, or am I perhaps overlooking something really obvious? Thanks! (void) move (CCTime)delta toPosition (CGPoint)point OverworldScene parentScene (OverworldScene )self.parent.parent.parent Go over physics node OverworldLayer parentLayer (OverworldLayer )self.parent.parent Go over physics node meewind of tegenwind? float angleWind parentScene.compass.rotation float angleShip self.rotation float difference float windFactor if (angleWind gt angleShip) difference angleWind angleShip else difference angleShip angleWind if (difference gt 180) difference 360 difference Incorporate wind power... if (difference gt 90) Tegenwind windFactor 1 ((((90 (180 difference)) 90)) (parentLayer.windPower 12)) else Meewind windFactor 1 ((((90 difference) 90)) (parentLayer.windPower 12)) if (windFactor lt 0.4) windFactor 0.4 point is the current position of the user's sprite a, b and c are the right triangle sides lengths formed by the caser sprite and the user's sprite positions float a ABS(self.position.y point.y) float b ABS(self.position.x point.x) float c sqrt(pow(a, 2) pow(b, 2)) angle of the hypotenuse float beta rad asin(b c) velocity in pixels per second (used to be 60) c 60 self.velocityFactor windFactor Now accounts for windfactor! parentScene.speedLabel.string NSString stringWithFormat \"Speed .1f knots\", self.velocityFactor (60 windFactor) 8 x axis velocity component float x c sin(beta rad) y axis velocity component float y c cos(beta rad) adjustments based on position of the this (chaser) sprite and the user's sprite, if chaser is on the right or below the user's sprite it is needed to reverse the velocity vector component x and y if (self.position.x gt point.x) x 1 if (self.position.y gt point.y) y 1 final velocity vector CGPoint velocityVector CGPointMake(x, y) CGPoint newPosition ccpAdd(self.position, ccpMult(velocityVector, delta)) NSLog( \"Updating position \", NSStringFromCGPoint(newPosition)) Only update in case new position is in bounds if (newPosition.x lt 0 newPosition.x gt parentLayer.contentSize.width) newPosition CGPointMake(self.position.x, newPosition.y) if (newPosition.y lt 0 newPosition.y gt parentLayer.contentSize.height) newPosition CGPointMake(newPosition.x, self.position.y) self.position newPosition"} {"_id": 9, "text": "How can i get a value from object in tmx file in Cocos2d x 3.x? I want to set my sprite in x coordinate based on an object in TMX map file, this is my code tileMap cocos2d TMXTiledMap create(\"ground.tmx\") ground tileMap gt layerNamed(\"ground\") this gt addChild(tileMap) TMXObjectGroup objects tileMap gt objectGroupNamed(\"objects\") Dictionary sign (Dictionary )objects gt objectNamed(\"sign\") How can i get a value of object in tmx file in Cocos2d x ?"} {"_id": 9, "text": "How to make and correctly use progress bar in cocos2d iphone? I have a game that uses a progress bar to inform player of level of certain stats of the player. For example hunger, when it starts at zero and slowly adds up to maximum bar. When he eats the hunger reduces. I tried implementing as progressBar, but it works wrong, as the bar expands both ways, and I need it to grow one side only. Also I had hard time setting the bar, since it uses actions. Is there an easy way to do it?"} {"_id": 9, "text": "Game over pop up like Flappy Bird How can I make a game over pop up like Flappy Bird in cocos2d iphone 3? I tried to add a new Scene, but it adds a new screen on the game, I just want a rectangle with some buttons inside it. I also search how to add multiple scene, but didn't find an example doing it."} {"_id": 9, "text": "How can I load a large tile map with cocos2d? I am try to design a cocos2d game with a big world. The world's tile map is very big, maybe 20 iPad screen sizes worth of tiles. I want to know how to load this using a CCTMXTiledMap? If I directly add it to screen, will it use too much memory? If so, is there a solution to solve this problem?"} {"_id": 9, "text": "OOP in cocos2d for ios I have been pulling my hair out trying to make an object in cocos 2d that is a CCSprite (with an image) and a CCLabelBMFont. I tried making a CCNode object and I tried making a custom CCSprite object but none of it worked! Can someone show me how to do this? Thanks."} {"_id": 9, "text": "Why does the Texture placement of my CCSprite slightly shift when changing it's location? So I've been seeing this issue for a while now. When using a delta method to change the location of a CCSprite, the placement of texture of my sprite slightly moves into the direction where I'm headed, while the physicsbody stays the same. This is really noticeable, since I'm using CCActionFollow to center this sprite in the view at all times. The code is displayed below. Is this normal behaviour, or am I perhaps overlooking something really obvious? Thanks! (void) move (CCTime)delta toPosition (CGPoint)point OverworldScene parentScene (OverworldScene )self.parent.parent.parent Go over physics node OverworldLayer parentLayer (OverworldLayer )self.parent.parent Go over physics node meewind of tegenwind? float angleWind parentScene.compass.rotation float angleShip self.rotation float difference float windFactor if (angleWind gt angleShip) difference angleWind angleShip else difference angleShip angleWind if (difference gt 180) difference 360 difference Incorporate wind power... if (difference gt 90) Tegenwind windFactor 1 ((((90 (180 difference)) 90)) (parentLayer.windPower 12)) else Meewind windFactor 1 ((((90 difference) 90)) (parentLayer.windPower 12)) if (windFactor lt 0.4) windFactor 0.4 point is the current position of the user's sprite a, b and c are the right triangle sides lengths formed by the caser sprite and the user's sprite positions float a ABS(self.position.y point.y) float b ABS(self.position.x point.x) float c sqrt(pow(a, 2) pow(b, 2)) angle of the hypotenuse float beta rad asin(b c) velocity in pixels per second (used to be 60) c 60 self.velocityFactor windFactor Now accounts for windfactor! parentScene.speedLabel.string NSString stringWithFormat \"Speed .1f knots\", self.velocityFactor (60 windFactor) 8 x axis velocity component float x c sin(beta rad) y axis velocity component float y c cos(beta rad) adjustments based on position of the this (chaser) sprite and the user's sprite, if chaser is on the right or below the user's sprite it is needed to reverse the velocity vector component x and y if (self.position.x gt point.x) x 1 if (self.position.y gt point.y) y 1 final velocity vector CGPoint velocityVector CGPointMake(x, y) CGPoint newPosition ccpAdd(self.position, ccpMult(velocityVector, delta)) NSLog( \"Updating position \", NSStringFromCGPoint(newPosition)) Only update in case new position is in bounds if (newPosition.x lt 0 newPosition.x gt parentLayer.contentSize.width) newPosition CGPointMake(self.position.x, newPosition.y) if (newPosition.y lt 0 newPosition.y gt parentLayer.contentSize.height) newPosition CGPointMake(newPosition.x, self.position.y) self.position newPosition"} {"_id": 9, "text": "How to create array with unique sprites? in cocos2d iphone I write the code like this. This displays only one sprite (red colour bubble) with number of times and moving down, but actually I want to display different sprites (different colour bubble) every time and moving down. I also add no of .png images in resource folder of my project. Here I used only 3.png, but I need to display all .png images (different colour bubbles) in my project but I don't know how to get this. Please help me Thank you. Here is the code (void)addTarget CCSprite target CCSprite spriteWithFile \"3.png\" rect CGRectMake(0, 0, 256, 256) CGSize winSize CCDirector sharedDirector winSize int minY target.contentSize.height 2 int maxY winSize.height target.contentSize.height 2 int rangeY maxY minY int actualY (arc4random() rangeY) minY Create the target slightly off screen along the right edge, and along a random position along the Y axis as calculated above target.position ccp(winSize.width (target.contentSize.width 2), actualY) self addChild target Determine speed of the target int minDuration 4.0 int maxDuration 12.0 int rangeDuration maxDuration minDuration int actualDuration (arc4random() rangeDuration) minDuration Create the actions id actionMove CCMoveTo actionWithDuration actualDuration position ccp( target.contentSize.width 2,actualY) id actionMoveDone CCCallFuncN actionWithTarget self selector selector(spriteMoveFinished ) target runAction CCSequence actions actionMove, actionMoveDone, nil Add to targets array target.tag 2 targets addObject target (void)gameLogic (ccTime)dt self addTarget (id) init if( (self super initWithColor ccc4(255,255,255,255) )) Enable touch events self.isTouchEnabled YES Initialize arrays targets NSMutableArray alloc init projectiles NSMutableArray alloc init Get the dimensions of the window for calculation purposes CGSize winSize CCDirector sharedDirector winSize self schedule selector(gameLogic ) interval 1.0 self schedule selector(update ) return self (void)update (ccTime)dt NSMutableArray projectilesToDelete NSMutableArray alloc init for (CCSprite projectile in projectiles) CGRect projectileRect CGRectMake(projectile.position.x (projectile.contentSize.width 2), projectile.position.y (projectile.contentSize.height 2), projectile.contentSize.width, projectile.contentSize.height) NSMutableArray targetsToDelete NSMutableArray alloc init for (CCSprite target in targets) CGRect targetRect CGRectMake(target.position.x (target.contentSize.width 2), target.position.y (target.contentSize.height 2), target.contentSize.width, target.contentSize.height) if (CGRectIntersectsRect(projectileRect, targetRect)) targetsToDelete addObject target for (CCSprite target in targetsToDelete) targets removeObject target self removeChild target cleanup YES projectilesDestroyed if ( projectilesDestroyed gt 30) GameOverScene gameOverScene GameOverScene node gameOverScene.layer.label setString \"You Win!\" CCDirector sharedDirector replaceScene gameOverScene if (targetsToDelete.count gt 0) projectilesToDelete addObject projectile targetsToDelete release for (CCSprite projectile in projectilesToDelete) projectiles removeObject projectile self removeChild projectile cleanup YES projectilesToDelete release"} {"_id": 9, "text": "How can I load a large tile map with cocos2d? I am try to design a cocos2d game with a big world. The world's tile map is very big, maybe 20 iPad screen sizes worth of tiles. I want to know how to load this using a CCTMXTiledMap? If I directly add it to screen, will it use too much memory? If so, is there a solution to solve this problem?"} {"_id": 9, "text": "how to improve sprite animations to reduce FPS My game has different, and detailed animations throughout the game. For example, the main character has an idle stance, so its not just painted still, giving him some life. Death animation, hurt animation, etc... even the background scenario has animations(which I don't think I went with the best approach here, but, it's working for now, this will be in another thread if not answered here) Anyways, the thing is, while the main character had these animations only that character was in the game at that time, so everything ran smoothly. After adding another character, the enemy, the burden of animations seems to overcharge the FPS and just slows the game down. The most obvious of this problems was that the spritesheet I was using was 1 per character, I figured how to use spritebatchnode efficiently and now 1 spritebatchnode covers the 2 characters animation set. The FPS tried to get back to normal, but its still laggy at times. This worries me because my game design has more enemies to the game, meaning that it will have this issue in a bigger scale. So I believe that its because of my animation approach, its poor, and inefficient making my game run slow. I have been trying to find the answer online with no luck, and I don't my approach is the best. I tried working some solutions by my own, but they end up in the same thing. THE ONLY, the only way I find how to reduce this problem is to make my sprites smaller, its not a big deal, but I wouldn't like this solution."} {"_id": 9, "text": "What is the best way to learn Cocos2D? I've messed around with iPhone development for a couple years now. I've done some contract work. I want to get into Cocos2D to develop a game idea that I have. I was wondering what might be the best quickest way to get up in running in cocos2d? I've thought about a book, but I wondering if that is needed? I'm the type of guy that just wants to know what everything does and is suppose to be used for. Any ideas?"} {"_id": 9, "text": "Best way to prevent UIPanGestureRecognizer from firing when moving sprites in cocos2d Im using UIPanGestureRecognizer in my cocos2d game to do drag and drop of sprites. I have a row of sprites and when I drag a sprite on top of another one, the sprite underneath it and any other sprites between should shift left or right out of the way to allow space to drop the currently selected sprite. This is working ok, however, if I am too quick at dragging the sprite around the screen, this triggers another round of the UIPanGestureRecognizer's callback method, and screws up the logic, as the sprites are in between shifting. I need a way to freeze the callback from firing, whilst the other sprites are shifting, then once they have finished moving, re enable the callback to fire. Whats the best way to do this?"} {"_id": 9, "text": "Alternatives to NSMutableArray for storing 2D grid iOS Cocos2d I'm creating a grid based iOS game using Cocos2d. Currently the grid is stored in an NSMutableArray that contains other NSMutableArrays (the latter are rows in the grid). This works ok and performance so far is pretty good. However the syntax feels bulky and the indexing isn't very elegant (using CGPoints, would prefer integer indices). I'm looking for an alternative. What are some alternatives data structures for 2D arrays in this situation? In my game it's very common to add and remove rows from the bottom of the grid. So the grid might start off 10x10, grow to 17x10, shrink to 8x10 and then finally end with 2x10. Note the column count is constant. I've consider using a vector lt vector lt Object gt gt . Also I'm vaguely aware of some type of \"fast array\" or similar offered by Cocos2d. I'd just like to learn about best practices from other developers!"} {"_id": 9, "text": "Timing use individual timer for every task or global timer? I'm writing a game, where a player controls a spaceship. It regenerates energy over time. So I need to make a little timer that adds certain amount of energy to the pool per second. My enemies also shoot at me, activate different abilities. I figured I can use separate timers for these too. But I see how this can quickly go out of hand, since I have different engines with different energy regeneration rates will I need to replace the timer every time? Or if I have different energy I have to manually track all the timers and set them anew. I thought, maybe I can use some global singleton method that can handle all the timing in my game? It can update everything in the game, and when something new happens (like new enemy spawning) I can just send my singleton information about that object and it will handle all the timing for it? Is this a good approach? Can I read up something about this somewhere? Maybe you have some experience with this?"} {"_id": 9, "text": "Cocosdenshion and Android not working I'm trying to play sounds and music with cocos2d. When I run on iPhone and .caf files the audio is perfect, but on Android it is not playing the background music and is only playing 2 sounds of 10 files. I don't know what I'm doing wrong. include lt SimpleAudioEngine.h gt bool HelloWorld init() const char sound if CC TARGET PLATFORM CC PLATFORM IOS sound \"Fun.caf\" else sound \"Fun.wav\" endif auto audio CocosDenshion SimpleAudioEngine getInstance() audio gt preloadBackgroundMusic(sound) audio gt playBackgroundMusic(sound, true) audio gt setBackgroundMusicVolume(1.0f) void HelloWorld playSound() const char effect if CC TARGET PLATFORM CC PLATFORM IOS effect \"Bomb.caf\" else effect \"Bomb.wav\" endif audio gt preloadEffect(effect) audio gt playEffect(effect)"} {"_id": 9, "text": "Zoom Layer centered on a Sprite I am in process of developing a small game where a space ship travels through a layer (doh!), in some situations the spaceship comes close to an enemy space ship, and the whole layer is zoomed in on the two with the zoom level being dependent on the distance between the ship and the enemy. All of this works fine. The main question, however, is how do I keep the zoom being centered on the center point between the two space ships and make sure that the two are not off screen? Currently I control the zooming in the GameLayer object through the update method, here is the code (there is no layer repositioning here yet) (void) prepareLayerZoomBetweenSpaceship CGPoint mainSpaceShipPosition mainSpaceShip position CGPoint enemySpaceShipPosition enemySpaceShip position float distance powf(mainSpaceShipPosition.x enemySpaceShipPosition.x, 2) powf(mainSpaceShipPosition.y enemySpaceShipPosition.y,2) distance sqrtf(distance) Distance gt 250 gt no zoom Distance lt 100 gt maximum zoom float myZoomLevel 0.5f if(distance lt 100) maximum zoom in myZoomLevel 1.0f else if(distance gt 250) myZoomLevel 0.5f else myZoomLevel 1.0f (distance 100) 0.0033f self zoomTo myZoomLevel (void) zoomTo (float)zoom if(zoom gt 1) zoom 1 Set the scale. if(self.scale ! zoom) self.scale zoom Basically my question is How do I zoom the layer and center it exactly between the two ships? I guess this is like a pinch zoom with two fingers!"} {"_id": 9, "text": "How do I find the rotation point given a touch anchor, new position and new rotation? I've got an Cocos2d layer which anchorPoint, position and rotation (according to http www.qcmat.com understanding anchorpoint in cocos2d ) vary when the pinch zoom gestures. Everything works fine. I've also added smoothness, so the layer will stop gently when it is 'thrown away' by a one finger gesture. The layer will also stop zooming in a gentle way when the 2nd finger is released (if it is released during movement). I've also succeeded with smooth rotation, so the layer continues rotation around touch1 when touch2 is released (if touch2 described an orbit around1). My problem is that the rotation functionality is not generic. For instance, I've problems with the case where touch1 and touch2 is on the opposite side of the center point, and follows a path on a circle circumference. The layer will then rotate around the centre point. That works fine until the fingers are released, but my algorithm is not robust enough to find out that it shall continue the rotation around said center point. Question How do I in a generic way find the point of rotation, and the rotation speed around that point, for a layer using sampled data containing anchorPoint, position and rotation for the last 0.1(?) seconds? The example above is only one use case. You can also think about the case where touch1 follows the arc from (1, 0) to (0, 1) meanwhile touch2 follows the arc from (2, 0) to (0, 2). That will result in a rotation around (0, 0). I want to detect that movement, and continue the rotation around (0, 0) if the touches are released at the same time."} {"_id": 9, "text": "Creating multiple fixtures in one body I want to create this type of fixture in one body. Here square and circle both are different fixtures but attach to one body. How do I do this?"} {"_id": 9, "text": "Manually remove inactive CCParticleSystem from scene? When using particle systems that have a lifetime, with CCParticleSystem and its derived classes, should I manually remove the finished systems from their parent nodes once the particle animations are complete? Or this is done automatically? I don't want to leave dead particle systems in my scene, for obvious reasons."} {"_id": 9, "text": "How to get all child with same tag from CCLayer? Actually i am working with cocos2d Game. I am using CCLayer for particular scene. now there are so many buttons means CCMenuitems are available. I want to disable that all menuitems having same tags."} {"_id": 9, "text": "Keeping the CCSprite on the screen In my cocos2d app I have a CCSprite moving on the screen but it moves off the screen. How can I prevent the CCSprite from moving off the screen? Thanks"} {"_id": 9, "text": "How to pause and unpause the Particular action of a sprite? My game has a sprite representing a character. When the character picks up an item, the sprite should stop moving for a period of time. I use CCbezier to make the sprite move, like this sprite gt runaction(x) Now I want the sprite to stop its current action (moving) and later resume it. I can make the sprite stop by using sprite gt stopaction(x) but if I do that, I can't resume the movement. How can I do that?"} {"_id": 9, "text": "Admob banner not getting remove from superview I am developing one 2d game using cocos2d framework, in this game i am using admob for advertising, in some classes not in all classes but admob banner is visible in every class and after some time game getting crash also. I am not getting how admob banner is comes in every class in fact i have not declare in Rootviewcontroller class. can any one suggest me how to integrate Admob in cocos2d game, i want Admob banner in particular classes not in every class, I am using latest google admob sdk, my code is below Thanks in advance (void)AdMob NSLog( \"ADMOB\") CGSize winSize CCDirector sharedDirector winSize Create a view of the standard size at the bottom of the screen. if (UI USER INTERFACE IDIOM() UIUserInterfaceIdiomPad) bannerView GADBannerView alloc initWithFrame CGRectMake(size.width 2 364, size.height GAD SIZE 728x90.height, GAD SIZE 728x90.width, GAD SIZE 728x90.height) else It's an iPhone bannerView GADBannerView alloc initWithFrame CGRectMake(size.width 2 160, size.height GAD SIZE 320x50.height, GAD SIZE 320x50.width, GAD SIZE 320x50.height) if (UI USER INTERFACE IDIOM() UIUserInterfaceIdiomPad) bannerView .adUnitID \"a15062384653c9e\" else bannerView .adUnitID \"a15062392a0aa0a\" bannerView .rootViewController self CCDirector sharedDirector openGLView addSubview bannerView bannerView loadRequest GADRequest request GADRequest request GADRequest alloc init request.testing NSArray arrayWithObjects GAD SIMULATOR ID, nil Simulator bannerView loadRequest request best practice for removing the barnnerView (void)removeSubviews NSArray subviews CCDirector sharedDirector openGLView .subviews for (id SUB in subviews) (UIView )SUB removeFromSuperview SUB release NSLog( \"remove from view\") this makes the refreshTimer count (void)targetMethod (NSTimer )theTimer INCREASE OF THE TIMER AND SECONDS elapsedTime seconds INCREASE OF THE MINUTOS EACH 60 SECONDS if (seconds gt 60) seconds 0 minutes self removeSubviews self AdMob NSLog( \"TIME 02d 02d\", minutes, seconds)"} {"_id": 9, "text": "Presenting game center leaderboard I have the following code (void)showLeaderboard GKLeaderboardViewController leaderboardController GKLeaderboardViewController alloc init if (leaderboardController ! NULL) leaderboardController.timeScope GKLeaderboardTimeScopeAllTime leaderboardController.leaderboardDelegate self self presentModalViewController leaderboardController animated YES leaderboardController release Which I am trying to use to make my leader board pop up. The issue is cocos2d will not allow me to use the line self presentModalViewController leaderboardController animated YES How do I fix this? Thanks PS I am using cocos2d"} {"_id": 9, "text": "Timing use individual timer for every task or global timer? I'm writing a game, where a player controls a spaceship. It regenerates energy over time. So I need to make a little timer that adds certain amount of energy to the pool per second. My enemies also shoot at me, activate different abilities. I figured I can use separate timers for these too. But I see how this can quickly go out of hand, since I have different engines with different energy regeneration rates will I need to replace the timer every time? Or if I have different energy I have to manually track all the timers and set them anew. I thought, maybe I can use some global singleton method that can handle all the timing in my game? It can update everything in the game, and when something new happens (like new enemy spawning) I can just send my singleton information about that object and it will handle all the timing for it? Is this a good approach? Can I read up something about this somewhere? Maybe you have some experience with this?"} {"_id": 9, "text": "Count number of CCSprite added to a CCLayer Does cocos2d has a method that returns the amount of CCSprites added to a CCLayer? A have SceneControlLayer object, and I added some CCSprites to it. interface SceneControlLayer CCLayer implementation SceneControlLayer (id)init CCSprite spr1 CCSprite spriteWithFile \"spr1.png self addChild spr1 z 1 tag 1 CCSprite spr2 CCSprite spriteWithFile \"spr2.png self addChild spr2 z 2 tag 2 ... end How do I retrieve an array of sprites added to the layer? Could I retrieve all the objects added through addChild and test its type? Since I'm starting with cocos2d objectivec, please, give some examples how to do it... I also thought that I could create an array, and, besides adding it to the layer, add it to the array also. But I'm not so sure if it's a good option. TIA, Bob"} {"_id": 9, "text": "Using pixel art on small high resolution screens I'm making a game and I would like to utilize pixel art as my style. But I faced a problem, modern displays on my target platform (iOS) have extremely high resolution. So if my artist makes me some sprites in 1 to 1 pixel resolution, each character sprite will look like 2x3 millimeters, and that's not what I want. How do I fix this problem? Do i just use 4 pixel blocks as 1 pixel in my art, or there is some other way? Another question, is how do I utilize high crisp display of those devices with pixel art? How do I go with using images on older devices? Do I have to make double assets or downscale upscale some images?"} {"_id": 9, "text": "CCsprite.flipX not working! Here is my function, it makes random point on the ground and makes my sprite go there. If the x position of location is less then position of my sprite, I flip my sprite so it looked left (it looks right by default). But this is not working at all. I tried different flip methods but none work! Please help what is wrong? (void) wander CGPoint rand CGPointMake(CCRANDOM 0 1() 270 , CCRANDOM 0 1() 140 ) float distance ccpDistance( currentSprite position , rand) float speed distance 2 ccTime time distance speed CCAction move CCMoveTo actionWithDuration time position rand if (currentSprite.position.x gt rand.x) currentSprite.flipX YES else currentSprite.flipX NO self runAction move There is no problem with this code. Problem was that I was trying to flip sprite that was a child of my Pet object. When I tried flipping sprite everything worked just fine. If anybody could explain that, would be great."} {"_id": 9, "text": "How to extend Tiled and Cocos2d to create an Isometric map that supports elevation I've been looking and looking and looking, and I cannot seem to find a solution out there for making a game that uses cocos2d and Tiled to make an isometric map that supports elevation. I am not looking for anything super complex... Just maybe 2 or 3 levels of elevation. (Think X Com UFO Defense, or Final Fantasy Tactics) I figure that since I've been unable to find a solution, I'll probably have to extend Tiled or something to support this. For now I'll just stick with level of elevation, but I want to extend the game to support elevation eventually. Will you share with me any good resources that you know? Where should I read to better understand how to accomplish such a thing?"} {"_id": 9, "text": "How can I cause the latest touch event to interrupt a prior event in Cocos2D? In Cocos2D for iPhone, I want the latest touch event to interrupt another and ignore the last touch. Let me know if I need to elaborate more, but basically my game consists of a lot of finger dragging, and if the player ever switched fingers, there may be some overlap, and for the way things are setup, it may detect it as a new touch. I think I have things almost on the right track, but my third touch does not work correctly. For instance Touch A begins and held Touch B begins and held Touch A let go Touch A begins and held lt This should interrupt Touch B In my delegate I put glView setMultipleTouchEnabled YES because I believe I need multiple touches enabled. In my CCLayer class with my added map and sprite I am using targeted touch delegate (i.e. ccTouchBegan NOT ccTouchesBegan, etc) I am accessing a touch object with touch event allTouches allObjects objectAtIndex 0 , however I don't have much understanding what index is considered the latest touch or even a process to always get the latest touch."} {"_id": 9, "text": "Cocos 2D asteroids style movement (iOS) So I have a CCSprite subclass, well call this Spaceship. Spaceship needs to move on a loop, until I say othersise by calling a method. The method should look something like (void)moveForeverAtVelocity method logic The class Spaceship has two relevant iVars, resetPosition and targetPosition, the target is where we are headed, the reset is where we set to when we've hit our target. If they are both off screen this creates a permanent looping effect. So for the logic, I have tried several things, such as CCMoveTo move CCMoveTo actionWithDuration 2 position ccp(100, 100) CCCallBlockN repeat CCCallBlockN actionWithBlock (CCNode node) self moveForeverAtVelocity self runAction CCSequence actions move, repeat, nil self.position self.resetPosition recursively calling the moveForeverAtVelocity method. This is psuedo code, so its not perfect. I have hard coded some of the values for the sake of simplicity. Enough garble The problem I am having, how can I make a method that loops forever, but can be called and reset at will. I'm running into issues with creating multiple instances of this method. If you can offer any assistance with creating this effect, that would be appreciated."} {"_id": 9, "text": "Rotating a sprite to touch I know this has been asked before and Ive looked through peoples questions and answers all over the internet and I just cant get it to work. Im sure its down to my inexperience. Ive got an arrow attached to a sprite, this sprite appears when touched but I want the arrow to point where the sprite will launch. I have had the arrow moving but it was very erratic and not pointing as it should. Its not moving at the moment but this is what I have. (void)update (ccTime)delta arrow.rotation dialRotation (void) ccTouchMoved (UITouch )touch withEvent (UIEvent )event pt1 self convertTouchToNodeSpace touch CGPoint firstVector ccpSub(pt, arrow.position) CGFloat firstRotateAngle ccpToAngle(firstVector) CGFloat previousTouch CC RADIANS TO DEGREES(firstRotateAngle) CGPoint vector ccpSub(pt1, arrow.position) CGFloat rotateAngle ccpToAngle(vector) CGFloat currentTouch CC RADIANS TO DEGREES(rotateAngle) dialRotation currentTouch previousTouch I have got pt from ccTouchBegan the same way as pt1 Thanks"} {"_id": 9, "text": "how to improve sprite animations to reduce FPS My game has different, and detailed animations throughout the game. For example, the main character has an idle stance, so its not just painted still, giving him some life. Death animation, hurt animation, etc... even the background scenario has animations(which I don't think I went with the best approach here, but, it's working for now, this will be in another thread if not answered here) Anyways, the thing is, while the main character had these animations only that character was in the game at that time, so everything ran smoothly. After adding another character, the enemy, the burden of animations seems to overcharge the FPS and just slows the game down. The most obvious of this problems was that the spritesheet I was using was 1 per character, I figured how to use spritebatchnode efficiently and now 1 spritebatchnode covers the 2 characters animation set. The FPS tried to get back to normal, but its still laggy at times. This worries me because my game design has more enemies to the game, meaning that it will have this issue in a bigger scale. So I believe that its because of my animation approach, its poor, and inefficient making my game run slow. I have been trying to find the answer online with no luck, and I don't my approach is the best. I tried working some solutions by my own, but they end up in the same thing. THE ONLY, the only way I find how to reduce this problem is to make my sprites smaller, its not a big deal, but I wouldn't like this solution."} {"_id": 9, "text": "How to make Snake Body in Snake Game? I'm new in cocos2d and game dev. I'm still learning in game dev. My goal is to make one game like Doodle Grub. But problem is snake body. I wrote like following (void)update (ccTime)delta NSLog( \" f\", GameScence sharedGameScence .playerVelocity.y) CGPoint tmp self.position float tmprotation self.position GameScence sharedGameScence .WormHeadPos GameScence sharedGameScence .WormHeadPos tmp tmprotation self.rotation self setRotation GameScence sharedGameScence .Headrotation GameScence sharedGameScence .Headrotation tmprotation snake is moving but problem is all of the body segments are same position when snake stop. And all of the body segments is so close and can't see segments like Doodle Grub. Any idea or Any suggestion ?"} {"_id": 9, "text": "Blending transition in cocos2d In my cocos2d iphone game, I have 2 backgrounds (CCnodes), each containing a quite complex hierarchy of sprites. I would like to make a smooth transition between them Initially, only the first background is visible At the end, only the second one is visible Is there a good way to set the opacity of a full hierarchy of sprites ? I tried to recursively set the opacity of all the contained sprites. It kinda works except that I guess it's not very efficient I would like the opacity of overlapping sprites to be 'merged' (as if the background was one single big sprite)"} {"_id": 9, "text": "Unit Testing with Cocos2D How to implement Unit Testing with Cocos2D framework? What are the good practices? Is there any testing framework like JUnit Framework at Eclipse for Android?"} {"_id": 9, "text": "Moving camera in large view In my cocos2d app I was wondering how to make a CCSprite move on the screen but have the screen focused on the CCSprite, so when the sprite moves the view moves with the CCSprite. Is there a tutorial to do this? Thanks"} {"_id": 9, "text": "Cocos 2D asteroids style movement (iOS) So I have a CCSprite subclass, well call this Spaceship. Spaceship needs to move on a loop, until I say othersise by calling a method. The method should look something like (void)moveForeverAtVelocity method logic The class Spaceship has two relevant iVars, resetPosition and targetPosition, the target is where we are headed, the reset is where we set to when we've hit our target. If they are both off screen this creates a permanent looping effect. So for the logic, I have tried several things, such as CCMoveTo move CCMoveTo actionWithDuration 2 position ccp(100, 100) CCCallBlockN repeat CCCallBlockN actionWithBlock (CCNode node) self moveForeverAtVelocity self runAction CCSequence actions move, repeat, nil self.position self.resetPosition recursively calling the moveForeverAtVelocity method. This is psuedo code, so its not perfect. I have hard coded some of the values for the sake of simplicity. Enough garble The problem I am having, how can I make a method that loops forever, but can be called and reset at will. I'm running into issues with creating multiple instances of this method. If you can offer any assistance with creating this effect, that would be appreciated."} {"_id": 9, "text": "GUI device for throwing a ball The hero has a ball, which shall be thrown with accuracy in a court on iPhone iPad. The player is seen from above, in a 2D view. In game play, the player reach is between 1 15 and 1 6 of the height of the iPhone screen. The player will run, and try to outmaneuver his opponent, and then throw the ball at a specific location, which is guarded by the opponent (which is also shown on the screen). The player is controlled by a joystick, and that works ok, but how shall I control the stick? Maybe someone can propose a third control method? I've tried the following two approaches Joystick Hero has a reach of 1 meter, and this reach is marked with a semi opaque circle around the player. The ball can be moved by a joystick. When the joystick is moved south, the ball is moved south within the reach circle. There is a direct coupling with the joystick and the position of the ball. I.e. when the joystick is moved max south, the ball is max south within the player reach. At each touch update the speed is calculated, and the Box2d ball position and ball speed are updated. NB, the ball will never be moved outside the reach as long as the player push the joystick. The ball is thrown by swiping the joystick to make the ball move, and then releasing the joystick. At release, the ball will get a smoothed speed of the joystick. Joystick Problem The throwing accuracy gets bad, because the joystick can not be that big, and a small movement results in quite a large movement of the ball. If the user does not release before the end of the joystick maximum end point, the ball will stop, and when the user releases the joystick the speed of the ball will be zero. Bad... Touch pad A force is applied to the ball by a sweep on a touchpad. The ball is released when the sweep is ended, or when the ball is moved outside the player reach. As there is no one to one mapping between the swipe and the ball position, the precision can be improved. A large swipe can result in a small ball movement. Touch Pad Problem A touchpad is less intuitive. Users do not seem to know what to do with the touch pad. Some tap the touchpad, and then the ball just falls to the ground. As there is no one to one mapping, the ball can be moved outside the reach, and then it will just fall to the ground. It's a bit hard to control the ball, especially if the player also moves."} {"_id": 9, "text": "Getting different x and y coordinates for touched location on a zoomed view I'm using Cocos2d for developing a game. I need to be able to pan and zoom when necessary, so for this reason I've added CCLayerPanZoom extension to my project. Recently I've noticed a problem with zoomed layers. The thing is if I touch on a zoom panable layer before doing zooming or panning I get correct x,y coordinates. But if I zoom the layer, the touched location coordinates are different than the earlier ones. Here's how I get the touch location (void)ccTouchesBegan (NSSet )touches withEvent (UIEvent )event UITouch touch touches anyObject CGPoint touchedLocation touch locationInView touch.view touchedLocation CCDirector sharedDirector convertToGL startPoint You might ask how I determine whether the two points are different before and after zooming. I have a sprite located on a predetermined point in the view. When I touch the sprite I log the position of both the sprite and the touchedLocation. Before zooming these points are almost the same, only a few units of difference in x and y. But after zooming they're totally different points and I guess this difference is directly proportional with the zoom scale. I don't want to ask how to have the touched location the same before and after zooming, I rather want to ask what I should do in this case."} {"_id": 9, "text": "Why the AnchorPoint doesn't affect the CCLayer Positioning? I think there is a difference between the CCLayer and CCNode behavior when I change their AnchorPoint. I will describe what I mean and please somebody explain it. Scenario I start with CCNode CCNode node ... node.setContentSize(ccp(W,H)) 1. node.setAnchorPoint(ccp(0,0)) node.setPosition(ccp(X,Y) This line will move the node in a way that its (0,0) point will be placed at (X,Y). 2. node.setAnchorPoint(ccp(1,1)) node.setPosition(ccp(X,Y) This line will move the node in a way that its (0,0) point will be placeed at (X W,Y H). In other word, this line will move the (W,H) point of the node to (X,Y) In addition to the Positioning, all actions (like Rotating, Scaling) are based on this anchor point. This policy is fair enough and you won't get confused when moving a scaled node (setScale(X)) to some position because the node's position ( and not node's contents!) will not change in the screen after any actions. ( PS We knew that rotating scaling a node will rotate scale internal node contents) Let's continue with CCLayer CCLayer layer ... layer.setContentSize(ccp(W,H)) 1. layer.setAnchorPoint(ccp(0,0)) layer.setPosition(ccp(X,Y) This line will move the layer in a way that its (0,0) point will be placed at (X,Y) 2. layer.setAnchorPoint(ccp(1,1)) layer.setPosition(ccp(X,Y) Unfortunately, This line will move the layer in a way that its (0,0) point will be placeed at (X,Y). Although CCLayer also use the anchor point for scaling, rotating and ... purposes, It does NOT use its anchor point for positioning!!! Question WHY? and How can I have the same CCNode like setPosition() behaviour for CCLayer? PS I've also tried gt ignoreAnchorPointForPosition(true) but it didn't help. ( cocos2d x version is 2.2.3)"} {"_id": 9, "text": "Sprite Body can not stop Hey i have issue regarding jump sprite body. In my code i am using moveLeft and moveRight Button and when i am press moveRight Button using following code if (moveRight.active YES) b2Vec2 force b2Vec2(4,0) ballBody gt SetLinearVelocity(force) Its move perfectly and When i release this Button than sprite body stop using following code else b2Vec2 force b2Vec2(0,0) ballBody gt SetLinearVelocity(force) But when i put this else part then jump can not done. My jump code is following if (jumpSprite.active YES) NSLog( \"Jump Sprite\") b2Vec2 locationWorld locationWorld b2Vec2(0.0f,4.0f) double force ballBody gt GetMass() ballBody gt ApplyLinearImpulse(force locationWorld, ballBody gt GetWorldCenter()) If i remove else part then jump will perform complete but sprite body can not stop after release button. So what to do?? Thanks in advance"} {"_id": 9, "text": "How can I load a large tile map with cocos2d? I am try to design a cocos2d game with a big world. The world's tile map is very big, maybe 20 iPad screen sizes worth of tiles. I want to know how to load this using a CCTMXTiledMap? If I directly add it to screen, will it use too much memory? If so, is there a solution to solve this problem?"} {"_id": 9, "text": "Blending transition in cocos2d In my cocos2d iphone game, I have 2 backgrounds (CCnodes), each containing a quite complex hierarchy of sprites. I would like to make a smooth transition between them Initially, only the first background is visible At the end, only the second one is visible Is there a good way to set the opacity of a full hierarchy of sprites ? I tried to recursively set the opacity of all the contained sprites. It kinda works except that I guess it's not very efficient I would like the opacity of overlapping sprites to be 'merged' (as if the background was one single big sprite)"} {"_id": 9, "text": "How to create array with unique sprites? in cocos2d iphone I write the code like this. This displays only one sprite (red colour bubble) with number of times and moving down, but actually I want to display different sprites (different colour bubble) every time and moving down. I also add no of .png images in resource folder of my project. Here I used only 3.png, but I need to display all .png images (different colour bubbles) in my project but I don't know how to get this. Please help me Thank you. Here is the code (void)addTarget CCSprite target CCSprite spriteWithFile \"3.png\" rect CGRectMake(0, 0, 256, 256) CGSize winSize CCDirector sharedDirector winSize int minY target.contentSize.height 2 int maxY winSize.height target.contentSize.height 2 int rangeY maxY minY int actualY (arc4random() rangeY) minY Create the target slightly off screen along the right edge, and along a random position along the Y axis as calculated above target.position ccp(winSize.width (target.contentSize.width 2), actualY) self addChild target Determine speed of the target int minDuration 4.0 int maxDuration 12.0 int rangeDuration maxDuration minDuration int actualDuration (arc4random() rangeDuration) minDuration Create the actions id actionMove CCMoveTo actionWithDuration actualDuration position ccp( target.contentSize.width 2,actualY) id actionMoveDone CCCallFuncN actionWithTarget self selector selector(spriteMoveFinished ) target runAction CCSequence actions actionMove, actionMoveDone, nil Add to targets array target.tag 2 targets addObject target (void)gameLogic (ccTime)dt self addTarget (id) init if( (self super initWithColor ccc4(255,255,255,255) )) Enable touch events self.isTouchEnabled YES Initialize arrays targets NSMutableArray alloc init projectiles NSMutableArray alloc init Get the dimensions of the window for calculation purposes CGSize winSize CCDirector sharedDirector winSize self schedule selector(gameLogic ) interval 1.0 self schedule selector(update ) return self (void)update (ccTime)dt NSMutableArray projectilesToDelete NSMutableArray alloc init for (CCSprite projectile in projectiles) CGRect projectileRect CGRectMake(projectile.position.x (projectile.contentSize.width 2), projectile.position.y (projectile.contentSize.height 2), projectile.contentSize.width, projectile.contentSize.height) NSMutableArray targetsToDelete NSMutableArray alloc init for (CCSprite target in targets) CGRect targetRect CGRectMake(target.position.x (target.contentSize.width 2), target.position.y (target.contentSize.height 2), target.contentSize.width, target.contentSize.height) if (CGRectIntersectsRect(projectileRect, targetRect)) targetsToDelete addObject target for (CCSprite target in targetsToDelete) targets removeObject target self removeChild target cleanup YES projectilesDestroyed if ( projectilesDestroyed gt 30) GameOverScene gameOverScene GameOverScene node gameOverScene.layer.label setString \"You Win!\" CCDirector sharedDirector replaceScene gameOverScene if (targetsToDelete.count gt 0) projectilesToDelete addObject projectile targetsToDelete release for (CCSprite projectile in projectilesToDelete) projectiles removeObject projectile self removeChild projectile cleanup YES projectilesToDelete release"} {"_id": 9, "text": "Is it better to preserve scenes in memory or recreate them every time I need them? I am using Cocos Builder to create scenes using sceneWithNodeGraphFromFile owner . Now I have doubts about whether it's better, on iOS, to save some memory or CPU cycles. In other words I have two options First, I could do lazy initialization of scenes without removing them from memory, like this (CCScene ) myScene if(! myScene) myScene CCBReader sceneWithNodeGraphFromFile \"MyFile.ccbi\" return myScene Then I always call self.myScene and I possibly set myScene to nil if the app receives a memory warning. I never remove a scene from the director, I just push without cleaning. Or, I could initialize a new scene every time. I'd call sceneWithNodeGraphFromFile owner every time that I need to push a scene, popping and cleaning it from the director and creating it again if I need it. Which should I prefer and why?"} {"_id": 9, "text": "Using pixel art on small high resolution screens I'm making a game and I would like to utilize pixel art as my style. But I faced a problem, modern displays on my target platform (iOS) have extremely high resolution. So if my artist makes me some sprites in 1 to 1 pixel resolution, each character sprite will look like 2x3 millimeters, and that's not what I want. How do I fix this problem? Do i just use 4 pixel blocks as 1 pixel in my art, or there is some other way? Another question, is how do I utilize high crisp display of those devices with pixel art? How do I go with using images on older devices? Do I have to make double assets or downscale upscale some images?"} {"_id": 9, "text": "Why the AnchorPoint doesn't affect the CCLayer Positioning? I think there is a difference between the CCLayer and CCNode behavior when I change their AnchorPoint. I will describe what I mean and please somebody explain it. Scenario I start with CCNode CCNode node ... node.setContentSize(ccp(W,H)) 1. node.setAnchorPoint(ccp(0,0)) node.setPosition(ccp(X,Y) This line will move the node in a way that its (0,0) point will be placed at (X,Y). 2. node.setAnchorPoint(ccp(1,1)) node.setPosition(ccp(X,Y) This line will move the node in a way that its (0,0) point will be placeed at (X W,Y H). In other word, this line will move the (W,H) point of the node to (X,Y) In addition to the Positioning, all actions (like Rotating, Scaling) are based on this anchor point. This policy is fair enough and you won't get confused when moving a scaled node (setScale(X)) to some position because the node's position ( and not node's contents!) will not change in the screen after any actions. ( PS We knew that rotating scaling a node will rotate scale internal node contents) Let's continue with CCLayer CCLayer layer ... layer.setContentSize(ccp(W,H)) 1. layer.setAnchorPoint(ccp(0,0)) layer.setPosition(ccp(X,Y) This line will move the layer in a way that its (0,0) point will be placed at (X,Y) 2. layer.setAnchorPoint(ccp(1,1)) layer.setPosition(ccp(X,Y) Unfortunately, This line will move the layer in a way that its (0,0) point will be placeed at (X,Y). Although CCLayer also use the anchor point for scaling, rotating and ... purposes, It does NOT use its anchor point for positioning!!! Question WHY? and How can I have the same CCNode like setPosition() behaviour for CCLayer? PS I've also tried gt ignoreAnchorPointForPosition(true) but it didn't help. ( cocos2d x version is 2.2.3)"} {"_id": 10, "text": "Tweaking and Settings Runtime variable modification and persistence Most companies have an editor, or a variable control system for tweaking stuff in games, but are there any middleware solutions to this problem? I've written two such systems in the past myself, and worked with five, maybe six different ones, but none of them were off the shelf. Each of these home grown solutions had problems, ranging from having to keep looking up values, to not being able to save the current state of the variables. Are there any mature Config Runtime variable control libraries apps? I generally code in C , but I would think that a mature settings variables editor would probably be socket based (and therefore language agnostic to some extent) as all current development hardware apart from Nintendo stuff provides a mechanism to talk to servers. The code implementation would also need to be quite simple (I do like the hot var TweakableConstants article shared by Oskar, but it's not a package)"} {"_id": 10, "text": "How is console game development done? I'm curious what the process is for development for a game console such as Wii, Playstation, or Xbox. Do I need to use some game engine and compile for each platform? What IDE is used? Any C IDE? Are all console games built in C ?"} {"_id": 10, "text": "How can I unpack a sprite sheet into multiple images? I need to take a sprite sheet and convert it into multiple images, one for each frame of the sprite sheet. How should I go about this? I would prefer an offline method or a tool to do so I found Alferd SpriteSheet Unpacker, but it is really slow on Windows 7 and does not seem to respond well at all."} {"_id": 10, "text": "Is there a command line ATI texture compression tool? Is there a command line tool that can convert PNG and JPG files to ATITC compressed textures? I have my own export pipeline that converts all textures to PVRTC, ATITC, and DXT, so I have no use for a GUI based tool like the Compressonator. Also, I'm running on Linux (although Wine might be able to handle simple conversion tools)."} {"_id": 10, "text": "What can I use to generate 2d vector graphics as a list of coordinates? I am working on a game that uses simple 2d vector graphics. I want a tool that will let me visually draw things like arbitrary polygons by placing points. A perfect tool would present a grid that I could scale larger or smaller (ie the window is 10 units across or the window is 20 units across). It would let me draw a polygon on this grid, and will tell me, simply, the coordinates of each point. It would be great if this tool could then export a file format that was something like 0, 5 3, 2 0, 0 3, 2 For bonus points, it would be great to be able to assign other attributes to each point. In the end, this will get passed to OpenGL, so things like color and opacity could possibly be used."} {"_id": 10, "text": "How do \"game maker\" tools like Blitz3D create .exe files? There are several applications like Blitz3D or other kinds of game construction tools that compile scripts or other game data to a single executable file. How do they do that?"} {"_id": 10, "text": "Platform for DS Gameboy Dev Managed Memory, Tools, and Unit Testing I'm interested in dabbling in Nintendo DS, 3DS, or GBA development. I would like to know what my (legal) options for development tools and IDEs are. In particular, I would not consider moving in this direction unless I can find A programming language that has managed memory (garbage collection) A unit testing tool akin to JUnit, NUnit, etc. for unit tests I would also prefer if other tools exist, like code coverage, etc. for that platform. But the main thing is managed memory and unit testing. What options are out there?"} {"_id": 10, "text": "Which programming language to use for tools? I use C as my language as choice. However, I generally use Python to write helper utilities and tools. My worry is that as my game engine continues to grow it's getting tedious to reimplement some of its features in Python. There has got to be a better way. Here are the options as I seem them Keep on keeping on. That is often the answer in a cooperate environment. Maybe it has some merit. Build bindings for Python (yuck) and have it use pieces of the engine directly. Start building the tools using C instead. I already use QT in the Python tools to provide a GUI when needed. It doesn't seem like it'd be that much harder to use QT in C instead. However I'm worried my tool productivity will go down. I generally strive to apply much less rigidity in tool code than I would in shipping code. So what is common practice, use the same language for tools, or use a more RAD friendly one? What if you use a language that differs from the language of the game which do you use? How do tools interact with the game engine link to it directly or fake it?"} {"_id": 10, "text": "Tool to create a bitmap font from a true type font What tool do you use to convert ttf fonts to bitmap fonts? Following is a list of features I'm looking for. I'd be happy with any tool really, but one that had these features would be better. outputs power of 2 texture atlas parsible config file (so I don't have to use their rendering library) output kerning information cross platform a rendering library would be great if it lets me make the actual OpenGL calls. So what tool have you used? Were you happy with it?"} {"_id": 10, "text": "Good ways to edit arbitrary collision shapes for 2D physics engine? Assume you have several 1024x1024 textures which contain an arbitrarily shaped and relatively complex cave system whose walls need to have collision polygons defined. The polygons need to be convex to work with the physics engine. What kind of process and tools can you think of that would make editing the vertices of these walls as efficient and painless as possible? Especially considering that the polygons need to be convex, and the designer needs to see when that is not the case."} {"_id": 10, "text": "IDE Debugging of Official SDK for wii and ps3? I remember hearing that wii and the ds uses CodeWarrior as their IDE. I know xbox uses visual studios but i have no idea what ps3 uses. What IDE do ps3 developers use and how do they debug? How do wii programmers debug? I always heard they use GDB but is that built into CodeWarrior or is that a separate application?"} {"_id": 10, "text": "What can I use to generate 2d vector graphics as a list of coordinates? I am working on a game that uses simple 2d vector graphics. I want a tool that will let me visually draw things like arbitrary polygons by placing points. A perfect tool would present a grid that I could scale larger or smaller (ie the window is 10 units across or the window is 20 units across). It would let me draw a polygon on this grid, and will tell me, simply, the coordinates of each point. It would be great if this tool could then export a file format that was something like 0, 5 3, 2 0, 0 3, 2 For bonus points, it would be great to be able to assign other attributes to each point. In the end, this will get passed to OpenGL, so things like color and opacity could possibly be used."} {"_id": 10, "text": "Great realtime shader tool? I often develop 2D games. I would like to know if there's a program like EvalDraw out there, that makes it easy to quickly make (for example) a square, out of a black quad, and then write some shader code, and see how that shader code modifies the square in realtime. That would be really great for my future development processes. Edit The shader tool must work with HLSL."} {"_id": 10, "text": "IDE Debugging of Official SDK for wii and ps3? I remember hearing that wii and the ds uses CodeWarrior as their IDE. I know xbox uses visual studios but i have no idea what ps3 uses. What IDE do ps3 developers use and how do they debug? How do wii programmers debug? I always heard they use GDB but is that built into CodeWarrior or is that a separate application?"} {"_id": 10, "text": "3D Paint tool in Maya Hey everyone, could someone help me out on this question? When I am trying to texture objects in maya (for example a barrel) I want to texture it with a brush. When I try to use the 3D painting tool it al gets black even when I have a image file selected. Also the resolution is very very low of the models and textures in maya, though the texture image is very high quality. Can someone please help me? Thanks so much for helping."} {"_id": 10, "text": "Image drawing tools (that aren't Photoshop) that work in the sRGB colorspace I'm looking for a way to create sRGB raster images. Now, I could use Inkscape and just have it render to a raster format, but are there any image drawing tools other than Photoshop that work in sRGB? Here's what I want to be able to do more specifically. Let's say the image is all one color. I want to be able to pick color 0x808080, which is in the sRGB colorspace. I want the file to write an image where every pixel is 0x808080. And then, when I read it, I can tell OpenGL that it's sRGB color data, so it will treat the 0x808080 color has being from the sRGB colorspace. The important part is that, when I'm selecting colors in the tool, the colors I'm selecting are from the sRGB colorspace."} {"_id": 10, "text": "What language and tools are good to start with for Linux game development? I would like to start learning about game development and I would like to do it using Linux. My main experience has been with Java and a bit of C , but that was for applications and not games. Now that I want to try with gaming, I'm wondering which IDE language should I use in Linux, whether I should go with C and compiling files manually at the beginning, or maybe continue with Java Eclipse, also I think I can use Eclipse with C , I have also started reading about Python... I was thinking in starting with the typical \"Tetris\" just to understand how a game works internally, and I think I can achieve that with all the previous options, but what do you recommend me or how have you started game developming under Linux?"} {"_id": 10, "text": "SFXR Like Tool for Speech Sfxr (and also Bfxr) is a great tool for generating sound effects for games. Is there something like this for speech synthesis? Not every game development tool and platform has a speech synthesis engine, and it would be great to at least get some decent sounding placeholders in place to see how the usability experience plays out. Even better if the results are tweakable, like sfxr. I'm looking for something I can at least run on windows, though preferably (like Bfxr) I would like a web application that I can just run out of my browser."} {"_id": 10, "text": "Sprites saved in INA and AN format? I'm not sure if this is a suitable question but I found a game that had all it is sprites and stuff saved in INA and AN format and I got curious to know which program is it. Or is it some sort of compressing or alike and how it is usually done? Anyone know? Here is the content of one of the files http pastebin.com EzUsFvdG Here is a hex dump of the above file http pastebin.com CTErFBcS The above one is the AN file and the bellow one INA. Hex dump of a INA file which seems to be some sort of map or data file (I believe because of the layers info, etc?) http pastebin.com 2fWn8izR"} {"_id": 10, "text": "Tools for non programmers to add new tasks to games Since graphic designers end users are not programmers, what are the technique to allow them to add new tasks or change application logic in a game? what are the end user tools? I want some popular examples."} {"_id": 10, "text": "What language and tools are good to start with for Linux game development? I would like to start learning about game development and I would like to do it using Linux. My main experience has been with Java and a bit of C , but that was for applications and not games. Now that I want to try with gaming, I'm wondering which IDE language should I use in Linux, whether I should go with C and compiling files manually at the beginning, or maybe continue with Java Eclipse, also I think I can use Eclipse with C , I have also started reading about Python... I was thinking in starting with the typical \"Tetris\" just to understand how a game works internally, and I think I can achieve that with all the previous options, but what do you recommend me or how have you started game developming under Linux?"} {"_id": 10, "text": "Blender For Game Development, Pros And Cons Blender is one of those applications that you either love or hate. I know it is great for 3D modeling and and animations and there is a lot said about the UI and its steep learning curve. I am more interested in how Blender stands out as far as Game Development goes. So my question is, what would be the Pros and Cons of choosing to use Blender to develop a high performance 3D game?"} {"_id": 10, "text": "SFXR Like Tool for Speech Sfxr (and also Bfxr) is a great tool for generating sound effects for games. Is there something like this for speech synthesis? Not every game development tool and platform has a speech synthesis engine, and it would be great to at least get some decent sounding placeholders in place to see how the usability experience plays out. Even better if the results are tweakable, like sfxr. I'm looking for something I can at least run on windows, though preferably (like Bfxr) I would like a web application that I can just run out of my browser."} {"_id": 10, "text": "How do I simulate color blindness for accessibility testing? Is there an application I can download (or some configuration of Windows, or something) that will let me see how my game will appear to users with different color blindnesses? There are already good questions about how to avoid badly designing your game for colour blindness. There's also a Photoshop filter from VisCheck is a nice idea, except their image processing upload service is down. Is there, therefore, a tool I can use to simulate colour blindness and see how things look? Ideally, I would like to try different types (red green, blue yellow, mild severe). If not, how do other game developers test avoid this problem, other than ignoring it, or having access to a color blind person (which I don't)?"} {"_id": 10, "text": "What language and tools are good to start with for Linux game development? I would like to start learning about game development and I would like to do it using Linux. My main experience has been with Java and a bit of C , but that was for applications and not games. Now that I want to try with gaming, I'm wondering which IDE language should I use in Linux, whether I should go with C and compiling files manually at the beginning, or maybe continue with Java Eclipse, also I think I can use Eclipse with C , I have also started reading about Python... I was thinking in starting with the typical \"Tetris\" just to understand how a game works internally, and I think I can achieve that with all the previous options, but what do you recommend me or how have you started game developming under Linux?"} {"_id": 10, "text": "Using model tools as map editor I want to make a game which would require a 3D map editor. Of course, I would like to avoid creating such an editor. My idea is now to use modeling tools (3DS Max, Maya, Blender) to create the map, and to give game specific objects specified names. This way I'd just need to write an COLLADA native map format converter. But I'm not sure if this is possible the way I imagine it, that's why I'd like to hear your thoughts on the matter. Are modeling tools suitable to create big open world maps? Can this \"naming convention\" idea for game specific objects work? Are the modeling tools able to export a scene in chunks in a way that occlusion culling and collision detection can be properly done? If not Is there a way to build a suitable data structure from the exported data?"} {"_id": 10, "text": "Speech synthesis book? When I was a kid, everything had a speech synthesizer in it, more or less. A couple years back I started to wonder where the technology is going after all these years, and after some research found that it's going nowhere. Storage has increased, making concatenative synthesis more life like, but little else has improved. Text to speech seems to be the primary research field. Most books I've found of the subject of speech synthesis skim on the actual voice generation and then spend hundreds of pages on text to speech. I'm not interested in text to speech as such, but more on the voice generation. Yet, I haven't found a single book with good, practical explanation of this. Concatenative synthesis is simple to grasp, but formant is the one I'd like more information about. (The third method, physical modelling, would be a plus, but not all that interesting). What makes this game specific is that I'd love to make a tool that lets low budget downloadable games have speech, without having to go out to get actual voice actors and having to store hundreds of megs of oggs with the game. Since the author is in complete control of the voice editing before release, text to speech is less important what's more important is the voice synthesis. So, anyone know any good books about this?"} {"_id": 10, "text": "What are the tools, programming languages and development processes of AAA games? Only thing I am able to find about \"big\" games like ac, hl, bf, cod is engine used to run the game. But I am interested in what software development methodology, programming and scripting languages were used. As well as tools for creating models, music, animations and other media. Further, were the team team organisations and so on for a certain game (or game series). Is this information even available to the public?"} {"_id": 10, "text": "Tools for non programmers to add new tasks to games Since graphic designers end users are not programmers, what are the technique to allow them to add new tasks or change application logic in a game? what are the end user tools? I want some popular examples."} {"_id": 10, "text": "What are the tools, programming languages and development processes of AAA games? Only thing I am able to find about \"big\" games like ac, hl, bf, cod is engine used to run the game. But I am interested in what software development methodology, programming and scripting languages were used. As well as tools for creating models, music, animations and other media. Further, were the team team organisations and so on for a certain game (or game series). Is this information even available to the public?"} {"_id": 10, "text": "3D Paint tool in Maya Hey everyone, could someone help me out on this question? When I am trying to texture objects in maya (for example a barrel) I want to texture it with a brush. When I try to use the 3D painting tool it al gets black even when I have a image file selected. Also the resolution is very very low of the models and textures in maya, though the texture image is very high quality. Can someone please help me? Thanks so much for helping."} {"_id": 10, "text": "Using model tools as map editor I want to make a game which would require a 3D map editor. Of course, I would like to avoid creating such an editor. My idea is now to use modeling tools (3DS Max, Maya, Blender) to create the map, and to give game specific objects specified names. This way I'd just need to write an COLLADA native map format converter. But I'm not sure if this is possible the way I imagine it, that's why I'd like to hear your thoughts on the matter. Are modeling tools suitable to create big open world maps? Can this \"naming convention\" idea for game specific objects work? Are the modeling tools able to export a scene in chunks in a way that occlusion culling and collision detection can be properly done? If not Is there a way to build a suitable data structure from the exported data?"} {"_id": 10, "text": "What is a good tool for producing animated sprites? Has anyone come across a software package that allows you to build animations in a similar way to how you can in Flash (i.e. using techniques such as tweens amp bones amp easings, etc) and then have the result exported as a sprite sheet?"} {"_id": 10, "text": "Most efficient way to generate 2D portraits I am not sure if this is a fitting question for gamedev, or if it is too art related. I am currently trying, to create 2D character protraits for my game. At first I tried to draw them and even though it helped polishing my drawing skills the end result either required way too much time or it simply looked like it was created by a grade school kid. So I am currently looking into some tools which from which people like me who are not out of the art world might benefit. Especially tools which can create a 3D head hair, so that I can render them. I have tried several 3D generation tools such as makehead and makehuman to create the basic head shape. But I have to admit I am not well versed in what other options are available what has the best quality etc."} {"_id": 10, "text": "Good ways to edit arbitrary collision shapes for 2D physics engine? Assume you have several 1024x1024 textures which contain an arbitrarily shaped and relatively complex cave system whose walls need to have collision polygons defined. The polygons need to be convex to work with the physics engine. What kind of process and tools can you think of that would make editing the vertices of these walls as efficient and painless as possible? Especially considering that the polygons need to be convex, and the designer needs to see when that is not the case."} {"_id": 10, "text": "tile based 2d level editor Possible Duplicate Tools for creating 2d tile based maps I am Indie Game developer and I am looking for a tile based 2d level editor. I also would like to know the free ones as well as paid ones, which you feel as the best."} {"_id": 10, "text": "Very easy game builders? Possible Duplicate What are some good game development programs for kids? I want very easy game builder for a kid somebody who knows nothing about programming games (how they work inside) and just wants to build some (I could teach him but I am not available all the time). She tried Adventure Maker and got confused. It has to be something very straightforward. Do You know about any? Thanks. )"} {"_id": 10, "text": "IDE Debugging of Official SDK for wii and ps3? I remember hearing that wii and the ds uses CodeWarrior as their IDE. I know xbox uses visual studios but i have no idea what ps3 uses. What IDE do ps3 developers use and how do they debug? How do wii programmers debug? I always heard they use GDB but is that built into CodeWarrior or is that a separate application?"} {"_id": 10, "text": "Interesting Innovative Open Source tools for indie games Just out of curiosity, I want to know opensource tools or projects that can add some interesting features to indie games, preferably those that could only be found on big budget games. EDIT As suggested by The Communist Duck and Joe Wreschnig, I'm putting the examples as answers. EDIT 2 Please do not post tools like PyGame, Inkscape, Gimp, Audacity, Slick2D, Phys2D, Blender (except for interesting plugins) and the like. I know they are great tools libraries and some would argue essential to develop good games, but I'm looking for more rare projects. Could be something really specific or niche, like generating realistic trees and plants, or realistic AI for animals."} {"_id": 10, "text": "tile based 2d level editor Possible Duplicate Tools for creating 2d tile based maps I am Indie Game developer and I am looking for a tile based 2d level editor. I also would like to know the free ones as well as paid ones, which you feel as the best."} {"_id": 10, "text": "How to version control game balance data stored in spreadsheets Is there any good workflow tooling for having good version control on spreadsheets for game data? Ideally something that supports branching or merging. Google spreadsheets allow people to edit data live so it makes \"merging\" easy, but it gets really hard to link the data that's live in a spreadsheet with the current version of the game in source control (ie. your git repo or other) Conversely, with a local tool like Excel you at least have actual files that can be stored in the repo, but there doesn't seem to be good tooling for merging different versions of them. With all that in mind, how can we ensure that a specific branch in a game repo can be linked to a specific version of the game data, and how can we allow people to work on different \"branches\" of game data in parallel while still keeping the ability to source control?"} {"_id": 10, "text": "Use of solid brushes and CSG in level building Since Quake 1 (I think it was the first), level design tools for FPS games have used solid brushes and CSG operations to define level geometry instead of more conventional poly modeling tools you see in general purpose 3d applications like 3DS MAX. Why is this? Is it More productive for the level designer? More likely to lead to closed geometry that won't screw up potentially visible set pre calc? Results in lower poly count (more cumbersome tools dissuade designers from adding too much detail)? ..."} {"_id": 10, "text": "Are bounding volumes created by artists? I'm interested in where in the tool chain bounding boxes are created. Are they made by the artists? In the modeling tool? How are they exported? Can Maya 3DS Max Blender ... mark geometry as bounding box? How does that work in Collada FBX?) Or is there a tool which calculates them? Are they calculated at run time? I basically know how bounding volumes work, but I'm a little bit confused on where to get them from."} {"_id": 10, "text": "Game treatment collaboration tools Other than using a wiki, what good (or purpose built) tools allow for collaborative work on a game treatment? I have a couple ideas I'd like to get fleshed out and built, and have a small team who will work me on the project(s). How can we best iterate over and define the game play, graphical styles, etc?"} {"_id": 10, "text": "Image drawing tools (that aren't Photoshop) that work in the sRGB colorspace I'm looking for a way to create sRGB raster images. Now, I could use Inkscape and just have it render to a raster format, but are there any image drawing tools other than Photoshop that work in sRGB? Here's what I want to be able to do more specifically. Let's say the image is all one color. I want to be able to pick color 0x808080, which is in the sRGB colorspace. I want the file to write an image where every pixel is 0x808080. And then, when I read it, I can tell OpenGL that it's sRGB color data, so it will treat the 0x808080 color has being from the sRGB colorspace. The important part is that, when I'm selecting colors in the tool, the colors I'm selecting are from the sRGB colorspace."} {"_id": 10, "text": "Is there a command line ATI texture compression tool? Is there a command line tool that can convert PNG and JPG files to ATITC compressed textures? I have my own export pipeline that converts all textures to PVRTC, ATITC, and DXT, so I have no use for a GUI based tool like the Compressonator. Also, I'm running on Linux (although Wine might be able to handle simple conversion tools)."} {"_id": 10, "text": "'Binary XML' for game data? I'm working on a level editing tool that saves its data as XML. This is ideal during development, as it's painless to make small changes to the data format, and it works nicely with tree like data. The downside, though, is that the XML files are rather bloated, mostly due to duplication of tag and attribute names. Also due to numeric data taking significantly more space than using native datatypes. A small level could easily end up as 1Mb . I want to get these sizes down significantly, especially if the system is to be used for a game on the iPhone or other devices with relatively limited memory. The optimal solution, for memory and performance, would be to convert the XML to a binary level format. But I don't want to do this. I want to keep the format fairly flexible. XML makes it very easy to add new attributes to objects, and give them a default value if an old version of the data is loaded. So I want to keep with the hierarchy of nodes, with attributes as name value pairs. But I need to store this in a more compact format to remove the massive duplication of tag attribute names. Maybe also to give attributes native types, so, for example floating point data is stored as 4 bytes per float, not as a text string. Google Wikipedia reveal that 'binary XML' is hardly a new problem it's been solved a number of times already. Has anyone here got experience with any of the existing systems standards? are any ideal for games use with a free, lightweight and cross platform parser loader library (C C ) available? Or should I reinvent this wheel myself? Or am I better off forgetting the ideal, and just compressing my raw .xml data (it should pack well with zip like compression), and just taking the memory performance hit on load?"} {"_id": 10, "text": "Tools for developing C64 Games Just wondering what people nowadays use for developing Commodore 64 Games? I've got the Programmer's Reference Guide which goes into all the details, but in the modern Age I assume I won't have to do development on an actual C64 itself? Are there tools that run on Windows or Mac OS X that are a bit like an IDE that offers some help and some debugging facilities (e.g., by hooking into an Emulator) or easy packaging into .d64 disk images? Is 6502 Assembler the one chosen language, or is C development feasible? (Ignoring BASIC here)"} {"_id": 10, "text": "What tools are available for creating 3D collision and pathfinding data? What is the process of creating geometry data to assist on NPCs movements and such on a 3D world to avoiding having them from going through the ground, etc? Are there specific modelling programs that can create the world and the collision geometry to be used? The map I made has caves, lakes with deep water, varying terrains heights, mountains, etc."} {"_id": 10, "text": "Use of solid brushes and CSG in level building Since Quake 1 (I think it was the first), level design tools for FPS games have used solid brushes and CSG operations to define level geometry instead of more conventional poly modeling tools you see in general purpose 3d applications like 3DS MAX. Why is this? Is it More productive for the level designer? More likely to lead to closed geometry that won't screw up potentially visible set pre calc? Results in lower poly count (more cumbersome tools dissuade designers from adding too much detail)? ..."} {"_id": 11, "text": "Is there an existing algorithm to find suitable locations to place a town on a heightmap? I've been experimenting with random generation of a \"map\" with the intention of building a basic sort of procedural map generator. Generating a reasonable heightmap using libnoise hasn't been that much of an issue. I am considering using A or similar to plot two main \"roads\" across the terrain from top to bottom and left to right, intersecting in the middle of a town in some relatively flat section of the terrain. I am unsure of the best way to go about locating the optimal point to place the town though. I created a \"steepness\" map as another map which looks at the points surrounding each point on the heightmap to determine the steepness and then sets 1 if steep and 0 if not to create a \"mask\" of steep and flat areas. How then could I determine the largest rectangle area that will fit within those flat areas? Or perhaps I need to re look at this a different way and place the \"town\" first then build the terrain around it rather than trying to place it into an existing terrain."} {"_id": 11, "text": "Use heightmaps or direct vertex manipulation for runtime terrain editing in UE4? I am creating a terrain editor and creator for in our game, in which we should be able to create hills and dales, create different shapes(forms) in the terrain etc. I came up with 2 approaches on achieving what we want, 1. modify 2d heightmaps by darkening lightening colours update terrain vertices based thereon. 2. Create a plane and modify the vertices of the plane to shape what we want. So my question is, which way would be faster better for a ingame terrain editor? And why would you recommend that? Or, if you know of a better way, I would love to hear. Thanks"} {"_id": 11, "text": "Level editing using a 2D map for a 3D game We're trying to make a level editor for a 3D game that involves walking around outdoor environments. In many ways a heightmap satisfies the game's needs, but it also falls short in several ways, so we're considering various enhancements to the heightmap concept, but it's proving difficult to find a simple solution to this problem. For a start, a heightmap has great difficulty with sharp edges. As long as everything is smooth a heightmap looks wonderful, but it becomes jagged around vertical cliffs, along the edges of roads, and anywhere the resolution of the heightmap becomes relevant. The obvious solution to these issues is to add a layer of vector drawing on top of the heightmap, so we can preciously define the curves of vertical cliffs and roads, and use this to insert specialized polygons into the terrain's mesh. A vertical cliff can even be a simple gap in the terrain mesh that can be filled by another mesh which allows us to render the cliff face however we like, bypassing the limitations that heighmaps usually have. Another issue with heightmaps is the difficulty of drawing smooth slopes by hand. For the purposes of the game, terrain should either by a gentle slope or a vertical cliff, so there is no ambiguity over whether the player can traverse through it. We could scan the heightmap to detect overly steep slopes and show an error message, but what we really want to do is give the user drawing tools that will only draw acceptable slopes. But how can this be done? Perhaps the traditional raster heightmap is causing more problems than it is solving, so an entirely different kind of heightmap is called for. Perhaps instead of adding a vector drawing layer, the whole heightmap was done as a vector image and represented as a set of polygons with each polygon having a certain elevation. This way we get smooth curves automatically, and creating meshes for vertical cliffs and flat land is trivial, but representing slopes in the editor and rendering them becomes a challenge. We've considered a blending tool that would draw polygons on a second layer, and wherever these blend polygons appear the underlying terrain polygons would smoothly merge together. Polygons that have shared edges would from a slope perpendicular to those edges at an angle that makes the slope walkable. Unfortunately working out the geometry of the resulting mesh is difficult, and it means that cliffs are the default for every change in elevation. Since it seems more natural for the user to draw lines to block the player's passage rather than drawing the places where the player can traverse, another approach is to have the user draw the cliff lines in another layer just as with the raster heightmap, but now those cliff lines would act to stop the terrain from smoothing itself into pure rolling hills. Imagine each polygon of the heightmap as a pillar of sand with vertical sides, and when a mesh is formed from the map the sand flows out of its pillars, forming smooth slopes in every direction except where it encounters a cliff line and is forced to flow around. Everywhere except the cliffs need to be a gentle enough slope to walk up, so when there is a gap in a cliff the sand needs to flow through and spread out on the other side. We have some ideas about how this might be done, but it's still a major challenge to implement. Finally, we could just use a grid with sloped blocks to represent slopes. Editing would be easy, generating the mesh would be easy, all the problems would be solved, but being confined to a grid would surely sacrifice the freedom we'd hoped to have. We don't want to be constrained to being axis aligned unless no other solution is practical. Ultimately the question is are there practical ways to implement any of the approaches we're considering, or are we coming at this from entirely the wrong direction?"} {"_id": 11, "text": "Large Scale GIS in a AAA Quality Game Engine? (Unreal, Cryengine, Unity, Etc.) I am working on a new simulation project that requires large scale, real world terrain and imagery (GIS). By large scale, I mean that I would like to support databases that cover something on the order of 10,000 square miles that include at least height data and satellite imagery. Using data of this size also means that the engine must be capable of managing the coordinate systems projections such that some reasonable precision can be maintained. To my knowledge OpenSceneGraph is the only graphics engine out there that makes this easy (via paged terrain support, osgEarth, etc.) However, it would be nice to be able to leverage many of the other great features AAA quality game engines bring to the table. (OSG is just a graphics engine, really. I've been using it for over a decade, but I don't want to be fixed only to what I know.) I've seen many tutorials online for importing small postage stamp sized bits of terrain into Unreal. I haven't seen anything on this scale. Asked here \"Very large terrains in Unreal 4\" there is a link to Unreal's \"World Composition\" feature. This seems to shift coordinates around and also doesn't seem geared towards using real world data. How can I represent real world terrain data on these scales in a mainstream game engine?"} {"_id": 11, "text": "3rd party terrain editor I am looking for a good application for generating 3d terrains (really allowing generation and then some user editing) . After a google search, I found many, but I need one that can export the entire terrain as a mesh. This, I was unable to find. (I need either a .obj .fbx or .3ds output) The size of the file that is written and the price of the program are not major factors in my decision."} {"_id": 11, "text": "Merging tesselated terrain with manually modelled In my flighsim visual system I am rendering large scale terrain using fixed grid mesh which is tesselated and displaced using height map. But for some relative small area (usually airports) we have much more detailed models including terrain, runways and so on. And here is a problem how can I merge tesselated terrain with modelled one? On the picture bellow grey is a tesselated terrain, and blue is modelled with 3dsmax."} {"_id": 11, "text": "Large Scale GIS in a AAA Quality Game Engine? (Unreal, Cryengine, Unity, Etc.) I am working on a new simulation project that requires large scale, real world terrain and imagery (GIS). By large scale, I mean that I would like to support databases that cover something on the order of 10,000 square miles that include at least height data and satellite imagery. Using data of this size also means that the engine must be capable of managing the coordinate systems projections such that some reasonable precision can be maintained. To my knowledge OpenSceneGraph is the only graphics engine out there that makes this easy (via paged terrain support, osgEarth, etc.) However, it would be nice to be able to leverage many of the other great features AAA quality game engines bring to the table. (OSG is just a graphics engine, really. I've been using it for over a decade, but I don't want to be fixed only to what I know.) I've seen many tutorials online for importing small postage stamp sized bits of terrain into Unreal. I haven't seen anything on this scale. Asked here \"Very large terrains in Unreal 4\" there is a link to Unreal's \"World Composition\" feature. This seems to shift coordinates around and also doesn't seem geared towards using real world data. How can I represent real world terrain data on these scales in a mainstream game engine?"} {"_id": 11, "text": "Level editing using a 2D map for a 3D game We're trying to make a level editor for a 3D game that involves walking around outdoor environments. In many ways a heightmap satisfies the game's needs, but it also falls short in several ways, so we're considering various enhancements to the heightmap concept, but it's proving difficult to find a simple solution to this problem. For a start, a heightmap has great difficulty with sharp edges. As long as everything is smooth a heightmap looks wonderful, but it becomes jagged around vertical cliffs, along the edges of roads, and anywhere the resolution of the heightmap becomes relevant. The obvious solution to these issues is to add a layer of vector drawing on top of the heightmap, so we can preciously define the curves of vertical cliffs and roads, and use this to insert specialized polygons into the terrain's mesh. A vertical cliff can even be a simple gap in the terrain mesh that can be filled by another mesh which allows us to render the cliff face however we like, bypassing the limitations that heighmaps usually have. Another issue with heightmaps is the difficulty of drawing smooth slopes by hand. For the purposes of the game, terrain should either by a gentle slope or a vertical cliff, so there is no ambiguity over whether the player can traverse through it. We could scan the heightmap to detect overly steep slopes and show an error message, but what we really want to do is give the user drawing tools that will only draw acceptable slopes. But how can this be done? Perhaps the traditional raster heightmap is causing more problems than it is solving, so an entirely different kind of heightmap is called for. Perhaps instead of adding a vector drawing layer, the whole heightmap was done as a vector image and represented as a set of polygons with each polygon having a certain elevation. This way we get smooth curves automatically, and creating meshes for vertical cliffs and flat land is trivial, but representing slopes in the editor and rendering them becomes a challenge. We've considered a blending tool that would draw polygons on a second layer, and wherever these blend polygons appear the underlying terrain polygons would smoothly merge together. Polygons that have shared edges would from a slope perpendicular to those edges at an angle that makes the slope walkable. Unfortunately working out the geometry of the resulting mesh is difficult, and it means that cliffs are the default for every change in elevation. Since it seems more natural for the user to draw lines to block the player's passage rather than drawing the places where the player can traverse, another approach is to have the user draw the cliff lines in another layer just as with the raster heightmap, but now those cliff lines would act to stop the terrain from smoothing itself into pure rolling hills. Imagine each polygon of the heightmap as a pillar of sand with vertical sides, and when a mesh is formed from the map the sand flows out of its pillars, forming smooth slopes in every direction except where it encounters a cliff line and is forced to flow around. Everywhere except the cliffs need to be a gentle enough slope to walk up, so when there is a gap in a cliff the sand needs to flow through and spread out on the other side. We have some ideas about how this might be done, but it's still a major challenge to implement. Finally, we could just use a grid with sloped blocks to represent slopes. Editing would be easy, generating the mesh would be easy, all the problems would be solved, but being confined to a grid would surely sacrifice the freedom we'd hoped to have. We don't want to be constrained to being axis aligned unless no other solution is practical. Ultimately the question is are there practical ways to implement any of the approaches we're considering, or are we coming at this from entirely the wrong direction?"} {"_id": 11, "text": "anisotropic fog of war Here I am not talking about how to render fog of war, but how to model exploring of terrain in a more sophisticated way. In a straight forward approach, terrain explored by a game unit is simply represented by a circle whose radius is how far this unit can see. And visible area is just union of isometric circles. But I can tell that it is not the case in popular games. Please take a look at the following screenshot from League of Legends, for example. The sight of view is anisotropic. The shape of surrounding terrain is also taken in to account. Any idea how this can be done?"} {"_id": 11, "text": "Dealing with edges on spherical heightmapped terrain This is the problem I'm having where the height has been applied to the vertex, the edge of each face has been pushed apart. I was wondering how I can best deal with this issue? I read elsewhere that calculating the mean between the two adjacent edge vertices and applying to both will seal the gap, but wouldn't that cause some UV stretching? Any advice would be great, Caius."} {"_id": 11, "text": "How do I simplify terrain with tunnels or overhangs? I'm attempting to store vertex data in a quadtree with C , such that far away vertices can be combined to simplify the object and speed up rendering. This works well with a reasonably flat mesh, but what about terrain with overhangs or tunnels? How should I represent such a mesh in a quadtree? After the initial generation, each mesh is roughly 130,000 polygons and about 300 of these meshes are lined up to create the surface of a planetary body. A fully generated planet is upwards of 10,000,000 polygons before applying any culling to the individual meshes. Therefore, this second optimization is vital for the project. The rest of my confusion focuses around my inexperience with vertex data How do I properly loop through the vertex data to group them into specific quads? How do I conclude from vertex data what a quad's maximum size should be? How many quads should the quadtree include?"} {"_id": 11, "text": "Dirt compression from vehicle tires So I kinda have this working but its not correct because it just averages, so I wanted to know if anyone here has any ideas. I'm trying to simulate loose dirt compression under the tires of a vehicle to reduce the potential bumpiness of 'chunky' terrain. Currently how I do this is that I have a bounding box shape around my tires, set a little lower so they intersect with the terrain. Each frame, I (currently) average all of the heights of each point in the terrain that are within the box bounds of that tire, and then set them all to that average. Clearly this won't work in most cases because, for example, if i'm on a hill, the terrain will deform way too much. One way I thought was to have a max and min amount the points could raise and lower but that still doesn't seem to work properly and sometimes looks more like steps than smooth dirt. I wanna say that there is probably a bit more to this that what i'm currently doing but I am not sure where to look. Could anyone here shed some light on this subject? Would I benefit any by maybe looking up some smoothing algorith or something similar?"} {"_id": 11, "text": "How to determine character's foot contact point on a uniform triangle mesh terrain? For a terrain that is modelled by a heightmap with a uniform triangle mesh, what are some techniques I could use to determine the contact point of the foot of a character standing on the terrain? Since the terrain's Y values are altered by the heightmap, they won't be flat any more. As the character moves on the terrain, it has to know at which values of Y value its foot should be. Conceptually, what are some methods and techniques to determine the contact point of the character's foot standing on the terrain?"} {"_id": 11, "text": "Mapping noise to sphere surface I'm attempting to create a sphere with terrain (aka planet). I managed to procedurally create an icosahedron, and I am able to subdivide it (yay), but now I'm stuck on terrain. My current idea was to create a Perlin like \"3D Noise Field\" and sample density where each of the spheres vertices fall (as a height map value). this way i should be able to tweak the noise (add octaves, etc) to roughen the \"NoiseField\" and thus the spheres surface. pseudo example and result public void Terrain(float Scale) if (Scale lt 0.01) return List lt Vector3 gt terrain new List lt Vector3 gt () for ( int i 0 i lt surface.vertices.Count i ) Vector3 vert sphere.verts i Vector3 direction vert.normalized Vector3 newpoint vert Sample3DNoise(direction, Scale) terrain.Add(newpoint) this line replaces the original shape! surface.vertices terrain Debug.Log(\"terrain Update\") public float Sample3DNoise(Vector3 point, float scale) Vector3 direction point.normalized float u point.normalized.x scale float v point.normalized.y scale float w point.normalized.z scale poor attempt at 3d noise field PerlinNoise(float, float ) float x Mathf.PerlinNoise(u , 0f) float y Mathf.PerlinNoise(0f, v) float z Mathf.PerlinNoise(u , v) the average of the coords, returns \"density at this point\" return (x y z) 3 edit so while it appears i was able to achieve this, it's is clearly not the \"terrain on surface of sphere\" look I was aiming for. Any suggestions on how can I change the \"noise field\" so my surface is more planet like? or how else can i achieve this?"} {"_id": 11, "text": "What is \"terrain mesh generation\" exactly? I'm new to computer graphics and need to know and understand what the \"terrain mesh generation\" is? I read about \"terrain\", \"mesh\", \"terrain generation\" but can't find an article named \"terrain mesh generation\". So is there anyone can explain \"terrain mesh generation\" ?"} {"_id": 11, "text": "How do we generate overhangs with simplex noise 3d? Now I use a simplex noise 2d function with x( voxel's x location ) and y(voxel's y location) to generate heightmap. How do we use simplex noise 3d to generate overhangs? What should the x y z inputs be? Pseudo code would help a lot."} {"_id": 11, "text": "Real world terrain import into UE4 I am trying to create a basic game in Unreal Engine 4.8.1 and I wish to have it set in the Dubai, UAE but i cannot find a way that will successfully use terrain data i have obtained (NASA Shuttle RADAR 90m) to create a 1 1 scale map in unreal without creating huge world spikes. Does anyone know a method that can import the data without creating terrain spikes?"} {"_id": 11, "text": "How can I store and load large 3D environments (terrains or cities)? I am interested in how a large area 3D environment in games like Grand Theft Auto V or Far Cry can be stored (on disk, in what file format) and how that data can be retrieved when it is used in a game. By \"the environment\" I mean only static objects like terrain with vegetation, city areas with buildings, et cetera. I'm not referring to temporary or moving objects like people or cars. I am not interested in scene rendering. I guess it may be convenient to shard (horizontally partition) the data by location creating something like \"tiles\" because it is usually accessed by location and such tiling will help to keep data that is related together (and reads will be faster). Also I guess the data for sure is stored in some (compressed?) 3D format with the respect to tiling. There probably have to be mechanisms that will split one object to two (or more) parts if it does not fit into a single tile. I have found a somewhat related question (How a 3D game map is stored and handled) but it only briefly answers small part of my question."} {"_id": 11, "text": "Level editing using a 2D map for a 3D game We're trying to make a level editor for a 3D game that involves walking around outdoor environments. In many ways a heightmap satisfies the game's needs, but it also falls short in several ways, so we're considering various enhancements to the heightmap concept, but it's proving difficult to find a simple solution to this problem. For a start, a heightmap has great difficulty with sharp edges. As long as everything is smooth a heightmap looks wonderful, but it becomes jagged around vertical cliffs, along the edges of roads, and anywhere the resolution of the heightmap becomes relevant. The obvious solution to these issues is to add a layer of vector drawing on top of the heightmap, so we can preciously define the curves of vertical cliffs and roads, and use this to insert specialized polygons into the terrain's mesh. A vertical cliff can even be a simple gap in the terrain mesh that can be filled by another mesh which allows us to render the cliff face however we like, bypassing the limitations that heighmaps usually have. Another issue with heightmaps is the difficulty of drawing smooth slopes by hand. For the purposes of the game, terrain should either by a gentle slope or a vertical cliff, so there is no ambiguity over whether the player can traverse through it. We could scan the heightmap to detect overly steep slopes and show an error message, but what we really want to do is give the user drawing tools that will only draw acceptable slopes. But how can this be done? Perhaps the traditional raster heightmap is causing more problems than it is solving, so an entirely different kind of heightmap is called for. Perhaps instead of adding a vector drawing layer, the whole heightmap was done as a vector image and represented as a set of polygons with each polygon having a certain elevation. This way we get smooth curves automatically, and creating meshes for vertical cliffs and flat land is trivial, but representing slopes in the editor and rendering them becomes a challenge. We've considered a blending tool that would draw polygons on a second layer, and wherever these blend polygons appear the underlying terrain polygons would smoothly merge together. Polygons that have shared edges would from a slope perpendicular to those edges at an angle that makes the slope walkable. Unfortunately working out the geometry of the resulting mesh is difficult, and it means that cliffs are the default for every change in elevation. Since it seems more natural for the user to draw lines to block the player's passage rather than drawing the places where the player can traverse, another approach is to have the user draw the cliff lines in another layer just as with the raster heightmap, but now those cliff lines would act to stop the terrain from smoothing itself into pure rolling hills. Imagine each polygon of the heightmap as a pillar of sand with vertical sides, and when a mesh is formed from the map the sand flows out of its pillars, forming smooth slopes in every direction except where it encounters a cliff line and is forced to flow around. Everywhere except the cliffs need to be a gentle enough slope to walk up, so when there is a gap in a cliff the sand needs to flow through and spread out on the other side. We have some ideas about how this might be done, but it's still a major challenge to implement. Finally, we could just use a grid with sloped blocks to represent slopes. Editing would be easy, generating the mesh would be easy, all the problems would be solved, but being confined to a grid would surely sacrifice the freedom we'd hoped to have. We don't want to be constrained to being axis aligned unless no other solution is practical. Ultimately the question is are there practical ways to implement any of the approaches we're considering, or are we coming at this from entirely the wrong direction?"} {"_id": 11, "text": "What is \"terrain mesh generation\" exactly? I'm new to computer graphics and need to know and understand what the \"terrain mesh generation\" is? I read about \"terrain\", \"mesh\", \"terrain generation\" but can't find an article named \"terrain mesh generation\". So is there anyone can explain \"terrain mesh generation\" ?"} {"_id": 11, "text": "How can I store and load large 3D environments (terrains or cities)? I am interested in how a large area 3D environment in games like Grand Theft Auto V or Far Cry can be stored (on disk, in what file format) and how that data can be retrieved when it is used in a game. By \"the environment\" I mean only static objects like terrain with vegetation, city areas with buildings, et cetera. I'm not referring to temporary or moving objects like people or cars. I am not interested in scene rendering. I guess it may be convenient to shard (horizontally partition) the data by location creating something like \"tiles\" because it is usually accessed by location and such tiling will help to keep data that is related together (and reads will be faster). Also I guess the data for sure is stored in some (compressed?) 3D format with the respect to tiling. There probably have to be mechanisms that will split one object to two (or more) parts if it does not fit into a single tile. I have found a somewhat related question (How a 3D game map is stored and handled) but it only briefly answers small part of my question."} {"_id": 11, "text": "Mining cubes out of marching cubes I originally built the start of my game world with a fully minecraft style structure chunks, only visible faces rendered, noise, etc. Too blocky. I implement marching cubes. Looks great, horrible to work with The problem is when you try to add or remove blocks to the marching cubes as... exactly as they are supposed to... everything gets smoothed. It becomes difficult to raycast on a neighbor and if you do all the blocks around him get changed. Obviously. I see a lot of marching cubes metaball looking games that implement area based organic molding. You don't place \"blocks\" you shape an area or deshape it like Landmark mining etc. On the otherhand Blockscape and Landmark seem to be a blend of the two? The land starts out marching but you can cut clear square chunks out of it and place square cubes onto it. How can you make straight corners with marching cubes? Or is it a combination of two entirely different systems? (UPDATE) There is probably more than one answer to this, does anyone have any experience trying to do this though? I can think of a couple of possible approaches Separate player built objects into a separate mesh object per chunk keeping terrain as terrain. Run smoothing (marching cubes or others) algorithms and normal calculations only on terrain. Would probably need some sort of a half transparent cube highlighter showing what the cursor is currently selecting. I can see a number of benefits to this system, though feel as if there are some downsides I'm just not thinking of immediately that would crop up if I started coding it...? Define a \"smooth\" bool per cube, only assigned at initial calculation of the mesh on any surfaces (floor ceiling etc). Any built added removed blocks are not re labelled as \"smooth\" when generating the mesh use different math for smooth cubes than for blocky cubes. This is what I'm currently working with and it works, but it's still only about a third as smooth as a full marching cube approach would be. Basically I'm average each vertices y value with its surrounding four cubes height(noise) values while never letting it go beneath 0 or above 1 (to stay within the cube). I also had to re write the raycast click detection to use the surface normals. Re code the marching cubes algorithms to work only on the cells I want them to do what I want them to. This seems like the most difficult but possibly most visually rewarding approach. or ??"} {"_id": 11, "text": "What do sandbox games usually do when generating new terrains? I am trying to make a minecraft. In my game, when the player moves to the boundary, new chunks will be generated. What I do is creating new chunks in my main thread and generating a new VBO to store them. But I find that it's quite inefficient and you can obviously feel the FPS is decreasing. What do these kinds of games usually do when generating new terrains? Do they use multi threads or some specific efficient algorithms or compute shaders (I still don't know much about OpenGL)? I once tried to generate my new terrains in another thread. But I found I can't use GL operation to generate VBO in another thread. I am thinking about pre generated some VBOs in my main thread. Is that the right way? I want to know what most people do in this situation."} {"_id": 11, "text": "Is 1 pixel of a height map representative of 1 vertex on the mesh? I'm trying to get my head around heightmap terrain generation. If I have a plane say 64 x 64 verts will I need to create a 64px by 64px greyscale heightmap in order to displace the geometry of the plane correctly?"} {"_id": 11, "text": "Demystifying \"chunked level of detail\" Just recently trying to make sense of implementing a chunked level of detail system in Unity. I'm going to be generating four mesh planes, each with a height map but I guess that isn't too important at the moment. I have a lot of questions after reading up about this technique, I hope this isn't too much to ask all in one go, but I would be extremely grateful for someone to help me make sense of this technique. 1 I can't understand at which point down the Chunked LOD pipeline that the mesh gets split into chunks. Is this during the initial mesh generation, or is there a separate algorithm which does this. 2 I understand that a Quadtree data structure is used to store the Chunked LOD data, I think i'm missing the point a bit, but Is the quadtree storing vertex and triangles data for each subdivision level? 3a How is the camera distance usually calculated. When reading up about quadtree's, Axis aligned bounding box's are mentioned a lot. In this case would each chunk have a collision bounding box to detect the camera or player is nearby? or is there a better way of doing this? (raycast maybe?) 3b Do the chunks calculate the camera distance themselves? 4 Does each chunk have the same quot resolution quot . for example at top level the mesh will be 32x32, will each subdivided node also be 32x32. Example below"} {"_id": 11, "text": "What is the role of tessellation in terrain? I'm relatively new to graphically programming and I've been looking into ways to render larger heightened terrain. I keep seeing comments directing me to disregard things such as geometry clipmaps, in favor of tessellation. From what I've read however, tessellation adds inner and outer triangles between a set of vertices. So from what I understand, you would lose the 1 to 1 relationship between height points and vertices. Additionally, the new vertices would be interpolated and therefore somewhat similar looking between points of similar height. Is this the case or is there something I'm missing. Is tessellation exclusively the way to go or can it ( should it) be combined with other techniques?"} {"_id": 11, "text": "Very large terrains in Unreal 4 I was watching some YouTube tutorials on making terrains in UE4 and in each one they mention that the larger the terrain the worse the performance gets. I was wondering what you would do if you wanted to create a map like in skyrim or WOW. Is the terrain made of one massive terrain or is it made up out of a series of terrains in a grid? And is there any optimisation that you can do or is it all handled by UE4?"} {"_id": 11, "text": "Rendering smooth ground I'm attempting to render terrain made out of a triangle mesh. The problem is that whenever I have a northwest gt southeast ramp in the terrain, I get this diamond pattern The issue is that at the top and bottom of the ramp, the terrain is more flat than at the middle, so if the ramp is aligned with the triangles, each triangle will have two light vertices (at the top and bottom), and one dark vertex (at the middle). How can I fix this effect? Subdividing the mesh helps, but doesn't fix it completely. Vertex shader uniform mat4 projection attribute vec3 position attribute vec3 normal attribute vec4 color varying vec3 f position varying vec3 f normal varying vec4 f color void main(void) gl Position projection position f color color f normal normal f position position Fragment shader varying vec3 f position varying vec3 f normal varying vec4 f color uniform vec3 light position void main(void) float light 0.5 0.5 abs(dot(normalize(f normal), normalize(light position f position))) gl FragColor vec4(light, light, light, 1) f color"} {"_id": 11, "text": "How to smooth low res sampling of noise for voxel terrain I am attempting to create a new terrain generator as part of a minecraft mod, which works very well if it samples at the full terrain resolution (16x256x16 voxels per terrain chunk). This is extremely laggy, so i attempted using a lower resolution sample, x4x64x4, with an extra one sample on each positive axis to interpolate with (5x65x5, representing 20x260x20 space). It all works fine until i try to smooth out the resulting 4x4x4 cubes of terrain. I have tried interpolating the noise value (0.0 to 2.0) of each block with the value next to it along each positive axis, each value weighted by how close the block is to it. The result has some smoothing, but some of it seems to be rotated 90 degrees, and some areas are unsmoothed. I know this is possible, minecraft does it internally (the code is illegibly obfuscated and messy, about half a page, 20 variables and 6 loops). Does anyone have any ideas about a reliable method for smoothing, only knowing the contents of the chunk and one sample to the north east top? my current noise array generator protected double getNoise(float x, float z) get a rough noisemap every 4 blocks, 1 more past the edge to round with double n new double 1625 x65x5x5 3D space in order y,x,z represents one chunk at 1 4 precision (1024 blocks plus 601 blocks padding along the positive axis sides for rounding. Minecraft uses 825 doubles internally, 5x33x5) for(int lx 0 lx lt 5 lx) for(int lz 0 lz lt 5 lz) some extra noise that controls terrain thickness along Y double m 32 (1f SimplexNoiseGenerator.getNoise( (x (lx 4)) 256, (z (lz 4)) 256) ) 32 for(int ly 0 ly lt 65 ly) n (ly 25) (lx 5) lz ( 1f SimplexNoiseGenerator.getNoise( (float)(x (lx 4)) 512f, ((float)ly 4) m, (float)(z (lz 4)) 512f ) ) (1.5f (Math.abs(32f ly) 32f) ) return n Someone posted this on stack overflow, it is exactly the same problem and seems to be unresolved. https stackoverflow.com questions 35852194 smooth lower resolution voxel noise"} {"_id": 11, "text": "Query regarding a quad tree implementation for spherical terrain I am having some difficulty conceptualising how a quadtree would be used to implement a spherical terrain system. I currently have a spherical terrain system working, without any form of optimisation, I just have a vertex buffer full of every vertex in the terrain. Obviously, this can only be rendered at very low resolutions without lagging. I intend to use a Chunked Level of Detail system to speed things up, however, despite my research, I am still somewhat unsure as to how to proceed. From what I understand I need to generate several levels of detail (by essentially creating several distinct terrain files, each with a lower resolution than the last). I then load the quad tree with the data by setting each level of the quad tree to be a \"level of detail\", so level 1 would be the root node, encompassing everything, level 2 would contain very low resolution terrain data (in the form of a low resolution list of terrain vertices), and so on until level n, where the highest resolution data would be stored (in the form of a high resolution list of terrain vertices). This is the part I have the most trouble with, is this correct? Generating several terrain files at different resolutions, and loading each one to a separate level of the quad tree? Or should the tree be populated with vertices in a different way? I then populate the main vertex buffer by searching the quadtree's nodes, and I use the players position to decide which nodes to return. So, the nodes far away from the player will be all high level (level 1) nodes with low detail, and as the distance to the player gets closer, the search will drill deeper and deeper into the quad tree, so eventually the nodes returned will be the highest detail level possible. Is this in any way correct? My thinking on this is still quite hazy, even though I have done extensive research. Thanks for any help or advice!"} {"_id": 11, "text": "Mapping noise to sphere surface I'm attempting to create a sphere with terrain (aka planet). I managed to procedurally create an icosahedron, and I am able to subdivide it (yay), but now I'm stuck on terrain. My current idea was to create a Perlin like \"3D Noise Field\" and sample density where each of the spheres vertices fall (as a height map value). this way i should be able to tweak the noise (add octaves, etc) to roughen the \"NoiseField\" and thus the spheres surface. pseudo example and result public void Terrain(float Scale) if (Scale lt 0.01) return List lt Vector3 gt terrain new List lt Vector3 gt () for ( int i 0 i lt surface.vertices.Count i ) Vector3 vert sphere.verts i Vector3 direction vert.normalized Vector3 newpoint vert Sample3DNoise(direction, Scale) terrain.Add(newpoint) this line replaces the original shape! surface.vertices terrain Debug.Log(\"terrain Update\") public float Sample3DNoise(Vector3 point, float scale) Vector3 direction point.normalized float u point.normalized.x scale float v point.normalized.y scale float w point.normalized.z scale poor attempt at 3d noise field PerlinNoise(float, float ) float x Mathf.PerlinNoise(u , 0f) float y Mathf.PerlinNoise(0f, v) float z Mathf.PerlinNoise(u , v) the average of the coords, returns \"density at this point\" return (x y z) 3 edit so while it appears i was able to achieve this, it's is clearly not the \"terrain on surface of sphere\" look I was aiming for. Any suggestions on how can I change the \"noise field\" so my surface is more planet like? or how else can i achieve this?"} {"_id": 11, "text": "Merging tesselated terrain with manually modelled In my flighsim visual system I am rendering large scale terrain using fixed grid mesh which is tesselated and displaced using height map. But for some relative small area (usually airports) we have much more detailed models including terrain, runways and so on. And here is a problem how can I merge tesselated terrain with modelled one? On the picture bellow grey is a tesselated terrain, and blue is modelled with 3dsmax."} {"_id": 11, "text": "How do we generate overhangs with simplex noise 3d? Now I use a simplex noise 2d function with x( voxel's x location ) and y(voxel's y location) to generate heightmap. How do we use simplex noise 3d to generate overhangs? What should the x y z inputs be? Pseudo code would help a lot."} {"_id": 11, "text": "How can I write a terrain into a .raw file? I want to generate a terrain through Perlin noise and store it into a .raw file. From Nehe's HeightMap tutorial I know the .raw file is read like this define MAP SIZE 1024 void LoadRawFile(LPSTR strName, int nSize, BYTE pHeightMap) FILE pFile NULL Let's open the file in Read Binary mode. pFile fopen( strName, \"rb\" ) Check to see if we found the file and could open it if ( pFile NULL ) Display our error message and stop the function MessageBox(NULL, \"Can't find the height map!\", \"Error\", MB OK) return Here we load the .raw file into our pHeightMap data array. We are only reading in '1', and the size is the (width height) fread( pHeightMap, 1, nSize, pFile ) After we read the data, it's a good idea to check if everything read fine. int result ferror( pFile ) Check if we received an error. if (result) MessageBox(NULL, \"Can't get data!\", \"Error\", MB OK) Close the file. fclose(pFile) pHeightMap is one dimensional, so I don't understand how I would write the x,y correspondence to a height value. I was planning to use either libnoise or the noise2 function on Ken Perlin's page, to make each value in a 1024x1024 matrix correspond to the height for the point, but the .raw file is stored in a single dimension, how can I make x,y correspondence work there?"} {"_id": 11, "text": "Is Quadtree Terrain Decimation applicable today? It all started from that page. https www.gamasutra.com view feature 131841 continuous lod terrain meshing .php?print 1 I didn't quite got what it was all about, so I've looked at this. https www.researchgate.net publication 3410916 Terrain decimation through Quadtree Morphing Then I've got some understanding. It was about decimating the more distant patches of the terrain. And then I've just wondered about one thing. At every frame, the mesh is re generated and re uploaded. Wouldn't it be kinda of slow? Ran the demo provided in the first link and got just 3 fps. What's the big idea of this \"optimization\"? My current code has 1048576 vertices for 1024x1024 heightmap, undecimated, and it runs way faster. His code makes my laptop hot. Another link. Quadtree vs multiple resolution grids for terrain rendering That is more useful. It turns out that there might be some mipmapped meshes on the GPU, and the quadtree decides which of them are turned on. The first question. Is my last guess correct? Second am I right the first link isn't useful anymore? Third how this applies to modern Android development (I mean at least GLESv2)."} {"_id": 11, "text": "What is the role of tessellation in terrain? I'm relatively new to graphically programming and I've been looking into ways to render larger heightened terrain. I keep seeing comments directing me to disregard things such as geometry clipmaps, in favor of tessellation. From what I've read however, tessellation adds inner and outer triangles between a set of vertices. So from what I understand, you would lose the 1 to 1 relationship between height points and vertices. Additionally, the new vertices would be interpolated and therefore somewhat similar looking between points of similar height. Is this the case or is there something I'm missing. Is tessellation exclusively the way to go or can it ( should it) be combined with other techniques?"} {"_id": 11, "text": "How is the terrain generated in Commandos and Commandos game clones look alikes? The Commandos series of games and its similar western counterpart, Desperados, use a mix of 2D and 3D elements to achieve a very pleasing and immersive atmosphere. Apart from the concept that alone made the series a best seller, the graphics eye candy was also a much appreciated asset of that game. I was very curious on what was the technique used to model and adorn the realistic terrains in those titles? Below are some screenshots that could be relevant as a reference for whomever has a candidate answer The tiny details and patternless distribution of ornamental textures make me think that these terrains were not generated using a standard heightmap blendmap method."} {"_id": 11, "text": "How do I serialise a mesh to a text file? I'm building a game engine in OpenTK (OpenGL for C ). Is it ossible to take a terrain mesh (in any format) and convert it into a text file (or a really small character filled file, no more than a few bytes). Then, afterwards, I'd take that file and generate the terrain from it. The only reason I'm doing this is to save some memory on the computer. I think it would be more efficient if we had to quickly generate a crude terrain, and then smooth it instead of loading in a large mesh file. Is this possible, and if so, how could I do it?"} {"_id": 11, "text": "How can I store and load large 3D environments (terrains or cities)? I am interested in how a large area 3D environment in games like Grand Theft Auto V or Far Cry can be stored (on disk, in what file format) and how that data can be retrieved when it is used in a game. By \"the environment\" I mean only static objects like terrain with vegetation, city areas with buildings, et cetera. I'm not referring to temporary or moving objects like people or cars. I am not interested in scene rendering. I guess it may be convenient to shard (horizontally partition) the data by location creating something like \"tiles\" because it is usually accessed by location and such tiling will help to keep data that is related together (and reads will be faster). Also I guess the data for sure is stored in some (compressed?) 3D format with the respect to tiling. There probably have to be mechanisms that will split one object to two (or more) parts if it does not fit into a single tile. I have found a somewhat related question (How a 3D game map is stored and handled) but it only briefly answers small part of my question."} {"_id": 11, "text": "Is Quadtree Terrain Decimation applicable today? It all started from that page. https www.gamasutra.com view feature 131841 continuous lod terrain meshing .php?print 1 I didn't quite got what it was all about, so I've looked at this. https www.researchgate.net publication 3410916 Terrain decimation through Quadtree Morphing Then I've got some understanding. It was about decimating the more distant patches of the terrain. And then I've just wondered about one thing. At every frame, the mesh is re generated and re uploaded. Wouldn't it be kinda of slow? Ran the demo provided in the first link and got just 3 fps. What's the big idea of this \"optimization\"? My current code has 1048576 vertices for 1024x1024 heightmap, undecimated, and it runs way faster. His code makes my laptop hot. Another link. Quadtree vs multiple resolution grids for terrain rendering That is more useful. It turns out that there might be some mipmapped meshes on the GPU, and the quadtree decides which of them are turned on. The first question. Is my last guess correct? Second am I right the first link isn't useful anymore? Third how this applies to modern Android development (I mean at least GLESv2)."} {"_id": 11, "text": "Quadtree vs multiple resolution grids for terrain rendering I have been thinking about quad trees with regards to terrain rendering. From my understanding the basic functionality of quadtree terrain rendering is to frustum cull the terrain in such a manner function render() lod threshold if(lod threshold reached !has children()) draw terrain mesh() return for(child in children) if(child.bounds.intersect(viewing frustum)) child.render() where node.bounds is a 3d bounds calculated as containing the maximum heightmap value of the contained terrain My questions are the following If we are in fact testing a 2d portion of terrain with it's bounds calculated to include the maximum heightmap value against the 3d frustum, what is the preferred bounds calculation for generating the node.bounds in the quadtree? That a tree is necessary because that one has to iterate every portion of a 3d scene to calculate frustum occlusion in a general way. Eg, there is no shortcut algorithm to calculate the set of 3d cells generated from a 2d grid that intersect the viewing frustum. As a more general question and to question the obvious, is there a way to calculate cells in a viewing frustum without having to iterate every cell in a scene? Presumably not otherwise you wouldn't need trees for culling With regards to an alternative grid implementation Has this implementation been contemplated for general purpose terrain culling? I am presuming that some form of grid base terrain culling is certainly preferred in certain games, namely top down games where the possibility of terrain in the distance of being on camera is non existent. function calc cells in quadrilateral(frustum projection onto 2d terrain grid) calculate cells in the resulting quadrilateral projection of the frustum onto the grid without having to bounds test every cell at some point based on distance from camera, assign lod retrieve lod for each cell in the calculated set from lod grids have multiple (array2 or intmap) containing the terrain data at every lod for O(1) retrieval Is there is a way to calculate cells in a quadrilateral without having iterate every cell in a grid? eg, from shaving off cells from slopes or something? If there is, in what fashion should one assign the lod cell based on distance? I haven't contemplated this in detail because 1 may be impossible The terrain would not be optimally culled in this 2d culling algorithm against the quadrilateral frustum projection onto the heightmap, because the height value at the edges may be outside the screen, correct? http www.olhovsky.com 2011 03 terrain started In this post, he describes assigning lod from a grid and from a quad tree. The illustrations are confusing with regards to whether question 1 is correct and terrain rendering with quad trees serves to draw the terrain mesh against the frustum as opposed to just as a function of distance 360 around the camera as at appears to do with his grid implementation. Please specify whether it appears that he is infact not frustum culling in the grid implementation but is frustum culling the quadtree."} {"_id": 11, "text": "Proper updating of GeoClipMaps I have been working on an implementation of gpu based geo clip maps, but there is a section of the GPU Gems 2 article that I just can't seem to understand, specifically this paragraph, and more precisely the bolded part The choice of grid size n 2k 1 has the further advantage that the finer level is never exactly centered with respect to its parent next coarser level. In other words, it is always offset by 1 grid unit either left or right, as well as either top or bottom (see Figure 2 4), depending on the position of the viewpoint. In fact, it is necessary to allow a finer level to shift while its next coarser level stays fixed, and therefore the finer level must sometimes be off center with respect to the next coarser level. An alternative choice of grid size, such as n 2k 3, would provide the possibility for exact centering Let's take an example image from the article My \"understanding\" of the way the clip maps were updated was that you floor the position of the viewpoint to an int, and as such get the center vertex point. If this is not the same as the previous center point, you update the entire map. Now, this obviously is not the case. What I am failing to understand is this If you look at the image above, if the viewpoint was to move one unit to the right, then the inner ring (the one just around the view point white center square) would end up getting a 1 unit space on both the left and right side of itself. But there is nothing in the paper that deals with this. What I mean is that it would end up looking like this (excuse my crummy cut and paste editing of the above image) This is obviously not a valid state. So, would the solution be that a clip ring (layer) can only move in increments of the ring layer it's contained within? Wouldn't this end up being very restrictive? I feel like I am missing some crucial understanding of parts of the algorithm, but I have been over both this paper and the original paper from 2004 and I just can't see what I am not getting."} {"_id": 11, "text": "What algorithm to use for random terrain? (Please note, I am aware that the generation is not truly random and relies on mathematical equations, and that my language of choice is C ) So I've been learning programming for a while now and I'm looking to make a top down 2D game. I want this game to generate random terrain pretty much like Dwarf Fortress but with sprites, however for this question let's just say that there just ASCII characters. I want it to generate mountains, rivers, inland lakes etc. I know of algorithms but have not been able to find a list of them all. The ones i know of are Perlin Noise, Diamond Square, Midpoint Displacement and some other minor ones. However I don't know which one to use and struggle to find a good article on any of them. Is there one right for the job, or does it just come down to personal opinion? And if you can find a list of all the algorithms and maybe a good article on one it would really help. Thanks!"} {"_id": 11, "text": "How to use ROAM algorithm to adapt terrain's mesh? I have a hard time understanding the idea behind ROAM algorithm \"Real time, continuous level of detail rendering of height fields\" Peter Lindstrom, David Koller, William Ribarsky, Larry F. Hodges, Nick Faust, Gregory A. Turner SAIC http dl.acm.org citation.cfm?id 237217 \"ROAMing terrain real time optimally adapting meshes\" Mark Duchaineau, Murray Wolinsky, David E. Sigeti, Mark C. Miller, Charles Aldrich, Mark B. Mineev Weinstein http dl.acm.org citation.cfm?id 267028 The problem that I cannot grasp is that the whole idea behind the algorithm is that the terrain mesh is at all times divided to isosceles right angled triangles but when we arrange the terrain in a non flat mesh then the triangles that we divided the mesh into are supposed to be extended(?) to meet the height field requirements? From what perspective is the terrain divided into those triangles and should they be isosceles right angled triangles generally or only when looked upon in up down projection?"} {"_id": 11, "text": "Level of Detail and loading map tiles I'm making some visualization of the Earth. It just should display tiles from services like Google Map (OpenMap for example) on the Earth surface. This services provide Earth satellite image textures of different parts of Earth at different zoom levels (resolution). The goal is make something similar with Google Earth. Of course I want to load only visible tiles at appropriate zoom level depending on distance to the camera center. So I'm interesting in how to decide which tiles on which levels should I load depending on current camera position. I know how to find region on the Earth surface that currently visible depending on camera view and projection matrix. And I can calculate the desired resolution (zoom level) of tiles for each point inside this region. Now, how to find out tile coordinates and zooms that I need to download form OpenMap or similar services? Is there some algorithm to do it?"} {"_id": 11, "text": "Where can I find an accurate map of Earth for a real time third person game? I want to create a game that will allow the player to move to any place on Earth. The game will not be first person, but it will be possible to zoom in quite close nonetheless. What I am lacking is an accurate height map of the planet. Textures such as albedo, specular or normal would also be very helpful. I don't know if such textures exist, but an \"accurate\" height map should have a resolution of at most a few meters. The textures do not have to be 100 real. Some parts can be procedurally generated, as long as they look \"realistic\"."} {"_id": 11, "text": "How do I simplify terrain with tunnels or overhangs? I'm attempting to store vertex data in a quadtree with C , such that far away vertices can be combined to simplify the object and speed up rendering. This works well with a reasonably flat mesh, but what about terrain with overhangs or tunnels? How should I represent such a mesh in a quadtree? After the initial generation, each mesh is roughly 130,000 polygons and about 300 of these meshes are lined up to create the surface of a planetary body. A fully generated planet is upwards of 10,000,000 polygons before applying any culling to the individual meshes. Therefore, this second optimization is vital for the project. The rest of my confusion focuses around my inexperience with vertex data How do I properly loop through the vertex data to group them into specific quads? How do I conclude from vertex data what a quad's maximum size should be? How many quads should the quadtree include?"} {"_id": 11, "text": "Is 1 pixel of a height map representative of 1 vertex on the mesh? I'm trying to get my head around heightmap terrain generation. If I have a plane say 64 x 64 verts will I need to create a 64px by 64px greyscale heightmap in order to displace the geometry of the plane correctly?"} {"_id": 11, "text": "Large Scale GIS in a AAA Quality Game Engine? (Unreal, Cryengine, Unity, Etc.) I am working on a new simulation project that requires large scale, real world terrain and imagery (GIS). By large scale, I mean that I would like to support databases that cover something on the order of 10,000 square miles that include at least height data and satellite imagery. Using data of this size also means that the engine must be capable of managing the coordinate systems projections such that some reasonable precision can be maintained. To my knowledge OpenSceneGraph is the only graphics engine out there that makes this easy (via paged terrain support, osgEarth, etc.) However, it would be nice to be able to leverage many of the other great features AAA quality game engines bring to the table. (OSG is just a graphics engine, really. I've been using it for over a decade, but I don't want to be fixed only to what I know.) I've seen many tutorials online for importing small postage stamp sized bits of terrain into Unreal. I haven't seen anything on this scale. Asked here \"Very large terrains in Unreal 4\" there is a link to Unreal's \"World Composition\" feature. This seems to shift coordinates around and also doesn't seem geared towards using real world data. How can I represent real world terrain data on these scales in a mainstream game engine?"} {"_id": 11, "text": "Is 1 pixel of a height map representative of 1 vertex on the mesh? I'm trying to get my head around heightmap terrain generation. If I have a plane say 64 x 64 verts will I need to create a 64px by 64px greyscale heightmap in order to displace the geometry of the plane correctly?"} {"_id": 12, "text": "(XNA) Stretching Images (Sprites) without Blur (Rasterizing?) thanks for clicking on this question although it has likely one of the most un specific and confusing titles on this site. I am somewhat new to XNA and I have only posted 1 question on this site before which I didn't understand the answer to fully, but I'll give it another go. I am looking to create a game which allows the user to either go full screen or re size the window to a few preset values, like many mainstream games nowadays allow you to do. I believe I know how to do this in XNA, the problem is, when I toggle full screen, and it stretches the sprites, they appear blurry. I know this is a very obvious problem, as stretching blur (logically). The thing is, I was wondering if there was a way to make it so regardless of the zoom, your sprites look crisp and not blurry? I asked a friend of mine in real life and he said something about rasterizing (which i don't know anything about). The only other thing I can think of I've seen this done a few times in Flash. For examples of what I mean the only game I can think of is Super Smash Flash 2. It seems regardless of the screen size, most of the sprites and images appear crisp, even on the largest of screens. If anybody knows anything about this, please share! Thanks."} {"_id": 12, "text": "Is there a way to scale a texture via GPU rather than by CPU? For my game that I'm developing I want to have my cards dynamically drawn so if there is any changes done to them it could be drawn on the card itself. What I have currently is that the cards are drawn to a RenderTarget at their originally designed size of 2100x1480 px. (I'll probably for game purposes have to scale that down to 1050x740 for its native size, but was designed that way to have 600 dpi for physical versions). Anyway the way I want to do it is that after drawing everything to the RenderTarget I scale it down and store that scaled down texture to the card's texture (which will be 164 x 115 for the playing size, the 1050 x 740 is the zoomed in size that I want so players can view what the card does and stats). The issue that I'm facing is that the way I currently tried to do it was far too slow taking over 9 seconds to scale it down after drawing the original size to the RenderTarget. Is there a way to scale a texture via GPU rather than by CPU? I'm currently using a CPU method as I'm new to working with textures and drawing."} {"_id": 12, "text": "Can someone explain this occurrence with a fbx model in xna? Because this is kind of weird to explain, let's show you what I mean. This is in my game. When I import this base ship model, it should be at (1000,1000,1000), but the model acts like it's at (1000,1000, 0). Note it is positioned correctly when I use a .x model. So it has to be the model. I need to know what's wrong with it. Here is the model file, tell me if anything is wrong with it https dl.dropbox.com u 92848165 station2.FBX http i.imgur.com VsjH8.jpg EDIT The model works if you import it into Google Sketchup...but you lose the textures, not very nice."} {"_id": 12, "text": "Units issue when exporting from 3DS Max to XNA I am working on a XNA game where we have defined that 1 XNA unit equals to 1 meter. Then, I set meters as system unit in 3DS Max and set to meters the units in the FBX exporter. However, when I export my models, they are much bigger in the game. Am I missing something? What should I do to avoid problems with my units? Investigating the FBX file, I noticed that I it has two values called UnitScaleFactor and OriginalUnitScaleFactor. They both are 100 when I export the files... And if I manually change UnitScaleFactor to 1, it works fine S"} {"_id": 12, "text": "Orthographic Camera Zooming In XNA I am using a spritebatch to render a board. I have created a camera class which can provide me a view and projection matrix. Currently I am supplying the view matrix to my sprite batch when I call begin. I can get the view matrix to correctly move everything around and do some zooming in and out. My problem is that I want to zoom in on a specific point (for now the center of the screen) but currently zooming just zooms in on the coordinate 0,0. Here is how I am constructing the view matrix ViewMatrix Matrix.CreateTranslation( new Vector3( ( Position.X Width Zoom 2), ( Position.Y Height Zoom 2), 0) ) Matrix.CreateScale(new Vector3( Zoom, Zoom, 1)) How could this be altered to make it scale correctly relative to the given point. Later I will probably want to zoom to the mouse position, but if someone has a simple example I'm sure I can work out how to adapt it."} {"_id": 12, "text": "How to fill a rectangle with tilable texture in XNA? So, question in the title. I don't know how to create infinite seamless background."} {"_id": 12, "text": "How do you create a .XNB Font file for use with CocosSharp? I know the .XNB file format is an XNA thing and that CocosSharp inherits this from its MonoGame roots. However there doesn't seem to be any information on how to create your own .XNB fonts to use with CocosSharp. I've tried searching but can find any information. Could someone explain it here or point me to a tutorial on how to create .XNB font file for use with CocosSharp? A site to download already compiled .XNB Fonts would also be acceptable. Update Another thing that makes this tricky is that I guess XNA Game Studio could be used, but it's not compatible with Windows 8.1 which is what I currently use for my dev machine..."} {"_id": 12, "text": "Using an object as a model to avoid too many parameters XNA C I have 3 classes(Skill,Projectile and Status),Skill has Projectile and Projectile has Status, all of them need to read information from a txt and to avoid open it everytime I want to create an object I want to read all the txt on Skill and pass the information Projectile need as arguments and then on Projectile create Status passing the information needed as arguments too As Projectile going to create a lot of Status objects it need to receive Projectile's informations and Status's informations from Skill, to avoid too many parameters can I create a Status object on Skill and pass it to Projectile and everytime I need to create another status I use the first one as a model? As example public class Skill String skillName,projectileName,statusName int skillNumber,projectileNumber,statusNumber public Skill() Code to read txt and fill variables What is happening Projectile projec new Projectile(projectileName,statusName,projectileNumber,statusNumber) To avoid above Status status new Status(statusName,statusNumber) Projectile projec new Projectile(projectileName,projectileNumber,status) And then at Projectile public class Projectile Constructor,variables and methods Method that create Status public void Update() if(hitEntity) this status was received from Skills Status tempStatus new Status(status.statusName,status.statusNumber)"} {"_id": 12, "text": "WP 8.1 XNA custom game loop (render when dirty?) I need to know whether it's possible to create a XNA game for Windows Phone 8.1 (which I've already) using monogame with a custom game loop. OpenGL ES has this possibility (GL RENDERMODE WHENDIRTY or sth. like that). Is there anything like that RenderMode for XNA MonoGame on WP 8.1 Note I'm new to Windows phone game programming."} {"_id": 12, "text": "XNA advanced rotation 3D I'm able to rotate any model with any angle I want, where I can not rotate my model around a given point. e.g My model rotates from the origin assigned in its .fpx file. I want it to rotate related to a point of its bottom plane, so that it is animated as falling"} {"_id": 12, "text": "Tons of stuttering in XNA? As stated in the title, my program stutters like crazy, even though my program for the most part runs for 60 fps. During the moments it stutters, FPS momentarily drops down to 59(stats from FRAPS). Here is an video capture of the stuttering in action. If you look closely, you can see the game stutter around 3 4 times. It is much more noticeable in real life. http gfycat.com SevereCanineBabirusa CLR Profiler shows that garbage collection doesn't run at all during that time, never mind 4 times, so it's not that. Here's the code for movement Movement logic Increase the speed speed Math.Min(speed (speedIncrement (gameTime.ElapsedGameTime.Milliseconds 200.0f)), maxSpeed) for (int i fruits.Count 1 i gt 0 i ) Move the fruits fruits i .pos.Y speed gameTime.ElapsedGameTime.Milliseconds fruits i .rect.Y (int)fruits i .pos.Y Check if the fruit is past the screen. If it is, remove it from fruits if (fruits i .rect.Y gt screenHeight) fruits.Remove(fruits i ) IsFixedTimeStep is set to false, but SyncronizeWithVerticalTrace is on. Any idea what could be the cause of the stuttering? EDIT Apparently it was a combination of this http answers.microsoft.com en us windows forum windows 7 performance presentationfontcacheexe uses 50 of my cpu 4200fe85 458f 4f19 b791 1fe5395304da and f.lux eating up my CPU GPU cycles."} {"_id": 12, "text": "How do I make a more or less realistic water surface? I want to make a similar water surface like in this picture I need the water surface in the same view than in the picture. Is it possible to work without shaders? I want to develop a little game for Xbox Live Indie Marketplace, Windows Phone and maybe later iPhone iPad. How should I make the water surface, so that it works on multiple platforms?"} {"_id": 12, "text": "Is there any quick and easy way to make all bodies visible with Farseer physics engine for XNA? I just want to be able to see all my bodies on the screen for debugging purposes and i cant think of an easy way, for example i have make some edge fixtures with curved arcs attached and i just want to see what they look like!"} {"_id": 12, "text": "Creating mesh at run time I've a set of voxel data and I want to create a mesh out of it at run time. I've looked into MeshBuilder and MeshHelper but I haven't found anything useful or a good tutorial how to use them. Can anyone tell me how to create a mesh at run time?"} {"_id": 12, "text": "Different ways to store a 2D map landscape in XNA I was looking around at this site about eight months ago and wish I saved the location of this topic but I was wondering the different map rendering styles that you can do in XNA. The one style I looked at was using a text file to pull characters like \"X\" would be a monster and \"O\" would be the player. Is there another way with out an external file that I can put tiles from a sprite sheet to randomly create a map. Of course when dealing with random buildings I would have certain building designs so that if some one was playing they wouldn't see a building with half a wall missing. This is for a top down 2D game."} {"_id": 12, "text": "How to correctly handle multiple Songs in XNA? I'm working on a (Windows only) game in XNA, and I have multiple music tracks. I don't want to load them all into memory, but play them on demand. To properly dispose them, I have a separate ContentManager just for music and a method that looks like this public void PlayMusic(MusicTracks trackToPlay) if (trackToPlay currentlyPlayingTrack) return MediaPlayer.Stop() musicContentManager.Unload() Song song null switch (trackToPlay) case MusicTracks.TitleMusic song musicContentManager.Load lt Song gt (\"TitleMusic\") break case MusicTracks.CreditsMusic song musicContentManager.Load lt Song gt (\"CreditsMusic\") break if(song ! null) MediaPlayer.Play(song) MediaPlayer.IsRepeating true currentlyPlayingTrack trackToPlay (MusicTracks is an enum). Is this the correct way to make sure I'm not using more RAM Resources than required? Or should I be looking into XACT? To be clear, I don't need to play multiple Songs at the same time (I do need to play 1 Song and a few SoundEffects though) and I don't need any crazy effects apart from setting the Volume of the music independently from the soundeffects, which should be straight forward with MediaPlayer.Volume."} {"_id": 12, "text": "How can I export a model using the CAT bone system into XNA? Has anyone successfully used the CAT bone system in 3ds Max and exported the file into XNA? If so, what was your method of doing so? There are a number of methods of doing this, apparently, but the ones I've tried have not worked. I used the Panda Exporter which creates an .X file. This seems to be the latest way of going about this, but when it's loaded in XNA, there is an error saying something about the bone weights. This happens when I export with and without CAT bones."} {"_id": 12, "text": "XNA GameTime before first Update Using XNA, is it possible to access the GameTime object before Update is called for the first time? Can it be used in the game constructor, Initialize or LoadContent methods?"} {"_id": 12, "text": "Min Max of two vectors? This seems like a simple question, but i'm having trouble searching the internet for it. In XNA, during a collision detecting method, I would determin the minimum of some vectors. Get the minimum top point Vector2 minTopPoint1 Vector2.Min(topLeft1, topRight1) Get the minimum bottom point Vector2 minBottomPoint1 Vector2.Min(bottomLeft1, bottomRight1) Get the minimum of both the top and bottom points. Vector2 minPoint1 Vector2.Min(minTopPoint1, minBottomPoint1) I switched over to making a C engine, and am trying to replicate the collision formula (Honestly, it's confusing enough, I just need to replicate it from XNA) I made my own Vector2, and now I need to make this Min function. So, what is the minimum or maximum of two vectors? Is it just the magnitude of the two vectors measured against eatchother? Is it the x and y values min maxed somehow?"} {"_id": 12, "text": "How can I track how \"well lit\" a player is so that I can determine if my AI can see him or her? I want to see how well lit the player character is in an environment so that my AI can react (or not) to the player when he or she is visible. Currently I am doing this by reading back the color data of the final render target and computing the brightness of the player's region. It seems expensive and taxing, so I was wondering if there is a better way to approach this?"} {"_id": 12, "text": "How to convert screen space into 3D world space? I am trying to make a 3D model to look at the mouse position. Currently I have this code MouseState mouseState Mouse.GetState() Matrix world Matrix.CreateTranslation(0, 0, 0) Vector3 source new Vector3((float) mouseState.X, 1f, (float) mouseState.Y) Vector3 mousePoint GraphicsDevice.Viewport.Unproject(source, this.game.Camera.Projection, this.game.Camera.View, world) System.Console.Out.WriteLine(\"x \" mousePoint.X \", Y \" mousePoint.Y \", Z \" mousePoint.Z) I get output such as this in the console x 0.1787011, Y 999.7204, Z 299.7723 x 0.08917224, Y 999.8602, Z 299.8862 x 0.05908892, Y 999.9069, Z 299.9241 x 0.04422692, Y 999.9302, Z 299.9431 x 0.03303542, Y 999.9477, Z 299.9573 x 0.03109217, Y 999.9508, Z 299.9598 x 0.02930491, Y 999.9535, Z 299.9621 x 0.02770578, Y 999.9559, Z 299.9641 x 0.0263205, Y 999.9581, Z 299.9659 The player is positioned at Vector3.Zero. The camera is positioned at new Vector3(0.0f, 1000.0f, 300.0f). I would like to get output such as X 300, Y 0, Z 300 when moving the mouse to screen top left and when moving the mouse to screen center where the model is located I want to have X 0, Y 0, Z 0. So I want the world coordinates of the mouse so that I can make the player rotate towards the mouse. Basically I want to map mouse X into world X, mouse Y to world Z and the world Y coordinate can be 0 at all times."} {"_id": 12, "text": "How to retrieve a cube collision by faces I work for a while on a minecraft game (voxel). I am front a problem for a long time about the collision detection. I want recover the cubes collision from my highlighted black's cube like on the picture , but only on the sides. And not on the edges ! Actually i got all cubes in red and green when i check with the boundingBox method. Actually i use the method with the class \"BoundingBox\" to check for collisions. Can anyone help me or direct me on the best way for retrive the right cube ? Code example with the boundingBox methode for check the collision List lt Node gt nodeParent regions modelSelected.regionIndex .Nodes modelSelected.Id .Where(m gt modelSelected.BoundingBox.Intersects(m.boundingBox)).ToList() i want to get only the green cube and not the red .. From the black cube in the middle Thank's a lot guy"} {"_id": 12, "text": "2D Collision Check before or check after? I'm using velocity to move my character, I just add subtract 0.4f and then update the players position in the update loop. I was wondering, when would be the best place to check for collision? Do I go ahead move the player, and then if I colliding push him out of the wall until there's no collision? Or do I check collision as soon as the key is pressed, and if there is somehow find the distance and move the player? My problem is that my game is tile based, but the world is constantly rotating around the player I have a function that returns a list of objects of each block that the player is colliding with, and I'm having trouble separating wall collisions with floor collisions"} {"_id": 12, "text": "Facilitating XNA game deployments for non programmers I'm currently working on an RPG, using the RPG starter kit from XNA as a base. (http xbox.create.msdn.com en US education catalog sample roleplaying game) I'm working with a small team (two designers and one music sound artist), but I'm the only programmer. Currently, we're working with the following (unsustainable) system the team creates new pics sounds to add to the game, or they modify existing sounds pics, then they commit their work to a repository, where we keep a current build of everything. (Code, images, sound, etc.) Every day or so, I create a new installer, reflecting the new images, code changes, and sound, and everyone installs it. My issue is this I want to create a system where the rest of the team can replace the combat sounds, for instance, and they can immediately see the changes, without having to wait for me to build. The way XNA's setup, if I publish, it encodes all of the image and sound files, so the team can't \"hot swap.\" I can set up Microsoft VS on everyone's machine and show them how to quickly publish, but I wanted to know if there was a simpler way of doing this. Has anyone come up against this when working with teams using XNA?"} {"_id": 12, "text": "Xna Texture2D from a png file I'm making a tile based game, and I'm working for support of tilesets. I'm trying to make it so that a Texture2D is set as a chosen PNG file. I can do this with no problem f I load the image into the content pipeline, but the level editor will be used by people without access to the content pipeline. How do I go about doing this?"} {"_id": 12, "text": "Viewport.Unproject Checking if a model intersects a large sprite Let's say I have a sprite, drawn like this spriteBatch.Draw(levelCannons i .texture, levelCannons i .position, null, alpha, levelCannons i .rotation, Vector2.Zero, scale, SpriteEffects.None, 0) Picture levelCannon as being a laser beam that goes across the entire screen. I need to see if my 3d model intersects with the screen space inhabited by the sprite. I managed to dig up Viewport.Unproject, but that seems to only be useful when dealing with a single point in 2d space, rather than an area. What can I do in my case?"} {"_id": 12, "text": "How does having the Debugger change the game execution on an XBOX 360? So I thought my issue was relating to the difference between a Debug and a Release build as per this question What 39 s the difference between a quot Release quot Xbox 360 build and a quot Debug quot one? but I've since found that if I go ahead and build a Creators Club version of the game using a Debug build and deploy to the XBOX, I get the same experience I had with the Release version of my game. However if I run the game from Visual Studio using F5 and having set the XBOX as the default platform, then the game runs as expected. If I change from Debug to Release and run with CTRL F5 then the game also works as expected. How would running the game with the debugger attached change the results I am getting in game? Is there any way that I can use the same approach or change the default compilation of the game so that I can use this approach to release my game?"} {"_id": 12, "text": "Is Spine's XNA runtime missing an importer? I'm writing an XNA 4.0 game and use Spine for animation. Until now, I've been making spritesheets with Spine and using them with a custom animation class. I recently discovered there is an official Spine runtime for XNA. I've been trying to use it but encounter an error. The closest I've come (after adding the runtime's classes to my project) is this error Cannot autodetect which importer to use for \"data goblins.atlas\". There are no importers which handle this file type. Specify the importer that handles this file type in your project. Is there such an importer in the runtime and I simply missed it? If so, how can I get XNA to recognize it? If not, is there an alternative?"} {"_id": 12, "text": "Timestep in multiplayer game I'm trying to wrap my brain around the concept of creating a server client multiplayer experience. My problem is mainly related to timestep. Consider the following scenario A client connects to a server. The client sends his inputs to the server to indicate he wants to move. Server simulates the input and determines the position of that client in the game world. Since the client and the server are both running on different timesteps, how do you accurately simulate so that all clients are in sync with the server? My server is currently set at at 30ms timestep. When I process client movements, there are potentially hundreds of requests waiting to be processed, yet no way to indicate how long it took between each one of the requests. I'm really not grasping how to properly simulate on the server based on time, in order to have everything sync up."} {"_id": 12, "text": "Tile based platformer, using larger tiles? So for my tile based platformer, It has a grid of tiles Occupying 1x1 block for each one. However, What if I want larger tiles? Maybe doors, tables, etc. They wouldnt fit in a 1x1 tile, so what I need is a way to let any method trying to access my tile array, know that a tile could be occupying a larger space. I can already render larger objects correctly, But I simply am looking for a method to let evrything else know a larger tile is there, So I can perform collision on it, and so other tiles cant be placed on it."} {"_id": 12, "text": "XNA WP7 accelerometer sample example ball rolling Does anyone know of a good WP7 accelerometer sample of a ball rolling around on a screen?"} {"_id": 12, "text": "2D Magnet like repelling behavior If somebody wanted to develop a system between two intersecting rectangles so that the rectangles would, in a gradual process, push eachother away from one another until no longer intersecting, with the repelling force being stronger depending upon how deep the intersection is... what would the math look like?"} {"_id": 12, "text": "Orienting a model to face a target I have two objects (target and player), both have Position (Vector3) and Rotation (Quaternion). I want the target to rotate and be facing right at the player. The target, when it shoots something should shoot right at the player. I've seen plenty of examples of slerping to the player, but I don't want incremental rotation, well, I suppose that would be ok as long as I can make the slerp be 100 , and as long as it actually worked. FYI Im able to use the position and rotation to do plenty of other things and it all works great except this last piece I cant figure out. Code samples run in the Target's class, Position the targets position, Avatar the player. EDIT Im now using Maik's c code he has provided and it works great!"} {"_id": 12, "text": "Formula throwing a ball to destination I am throwing a ball using this double v, vx, vy, alpha, t2 0 if (Keyboard.GetState().IsKeyDown(Keys.Up)) alpha MathHelper.ToRadians(60f) v 1230d vy v Math.Sin(alpha) vx v Math.Cos(alpha) ball2pos.Y (float)((vy t2) (g t2 t2 2)) graphics.GraphicsDevice.Viewport.Height ball2.Height ball2pos.X (float)( vx t2) t2 t2 gameTime.ElapsedGameTime.TotalSeconds It works without a problem. It calculates the throw including the gravitation (g). vx is how much it moves per second on the X,vY the Y accelerration (running against gravity), v the strength of the throw and t2 the current time. But I want to change the formula to throw the ball to a given destination. Say I want to throw my ball from 60 degrees to a target. How much \"strength\" do I need for it? What would be the formula? I'm not really good at figuring out that and google doesn't give me what I want. To simplify let's assume that the Y of source and target are the same Given Angle, SourceLocation, TargetLocation, Gravitation Looking for Strength"} {"_id": 12, "text": "Game Asset Management I am making my first small mobile game in C XNA. Lets say I have 3 screens, the main menu, options and game screen. A single game session usually lasts for 1 min, so the user will alternate frequently between the main menu and game screen. Therefore, once I load the textures for either screen, I want to keep them in memory to avoid frequent reloading. Both screens share some assets like their background textures, but differ in others. The first solution I came up with is making 2 texture factory classes, MainScreenAssetFactory and GameScreenAssetFactory, each with their own content manager, and ill store them in a globally accessible point so that they persist after either screen is destroyed. There is also a OptionsScreenAssetFactory, but that I dont want to cache it since the options screen is rarely visited. A typical Factory would look something like this public class MainScreenAssetFactory private readonly ContentManager contentManager public MainScreenAssetFactory(IServiceProvider serviceProvider, string rootDirectory) contentManager new ContentManager(serviceProvider) RootDirectory rootDirectory public Texture2D ListElementBackground get return contentManager.Load lt Texture2D gt (\"UserTab\") public Texture2D ListElementBulletPoint get return contentManager.Load lt Texture2D gt (\"TabIcon\") public Texture2D LoggedOutUser get return contentManager.Load lt Texture2D gt (\"LoggedOutUser\") Since both Main, Options and Game Screen share some common resources, instead of loading them more than once, I created another class CommonAssetTexFactory which holds the common stuff and stays in memory during the app lifetime. For example, this class gets passed to the options screen when it is created. However, given my small game with its few assets, I am already finding this solution cumbersome and inflexible. Changing anything would require looking to see if its already in the common factory, and if not, modifying existing factories and so on. And this is just considering textures currently, i didnt add sound files yet. I cant imagine bigger games with thousands of resources using this approach. A better idea must exist. Would someone please enlighten me?"} {"_id": 12, "text": "XNA move from start position to target position exactly in 3D If I have a list of positions that map out a path a character should follow. What would be the best way to move at a constant speed to each position making sure the character lands exactly at each position before moving onto the next? For example the character is at position A, we then queue up position B and position C. The character cannot move towards position C until it reaches position B exactly. It would be great if the solution worked at slower frame rates update speeds as well."} {"_id": 12, "text": "Absorbtion 2d image effect I want to create a specyfic 2d image effect. It consists in modifying a sprite so it looks like it is being zoomed to a point or \"absorbed\" by that point. I'm not really sure what is the technical name of this effect so I cannot explain it correctly. Here you can see a video of what I'm talking about, it is the effect when the character absorbs the three glyphs. http www.youtube.com watch?v PIo GddsMcU amp t 4m45s What is the name of this effect? How can I implement it with XNA for 2D textures sprites?"} {"_id": 12, "text": "How do I create a 3rd person camera? I currently have a camera class set up and have my model player loaded but I can't get my camera in the correct position by changing the x,y,z coordinates. I have set up my \"game\" with a separate class for the model player and a class for the camera. I am fairly new to XNA and most of what I have already got is from a tutorial from my lecturer. Here is my player model class public class Player public Model model public Matrix world Matrix.Identity public Vector3 position public Vector3 direction public Quaternion rotation Quaternion.Identity public BoundingSphere collision public float speed 2f public float moveForwards public float moveLeft public float forward Matrix transform public Player(Model m, Vector3 iPos) model m position iPos direction new Vector3(0, 0, 1) transform new Matrix m.Bones.Count m.CopyAbsoluteBoneTransformsTo(transform) foreach (ModelMesh mesh in m.Meshes) collision BoundingSphere.CreateMerged(collision, mesh.BoundingSphere) public Player() public BoundingSphere getSphere() return collision.Transform(world) public void sampleInputMovement(GamePadState player) moveForwards (player.ThumbSticks.Left.Y 5) moveLeft (player.ThumbSticks.Left.X 32) 1 public void update() rotation Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), moveLeft) Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), moveForwards) Vector3 motion Vector3.Transform(direction, rotation) position motion forward world Matrix.CreateFromQuaternion(rotation) Matrix.CreateTranslation(position) public void Draw(Matrix projection, Matrix view) Matrix transforms new Matrix model.Bones.Count model.CopyAbsoluteBoneTransformsTo(transforms) foreach (ModelMesh mesh in model.Meshes) foreach (BasicEffect effect in mesh.Effects) effect.EnableDefaultLighting() effect.Projection projection effect.View view effect.World transforms mesh.ParentBone.Index world mesh.Draw() And here is my camera class public class Camera Vector3 position Vector3 newposition Quaternion cameraRotation Vector3 targetOffset new Vector3(0, 1f, 6f) public Matrix view Matrix.Identity public Matrix projection Matrix.Identity public Camera(Game game, Vector3 xPostion) position xPostion projection Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, game.GraphicsDevice.Viewport.AspectRatio, 1.0f, 1000000f) public void update(Matrix targetWorld) Quaternion rotation Vector3 target Vector3 scale targetWorld.Decompose(out scale, out rotation, out target) cameraRotation Quaternion.Lerp(cameraRotation, rotation, 0.15f) newposition Vector3.Transform(targetOffset, targetWorld) position Vector3.SmoothStep(position, newposition, 0.8f) Vector3 cameraup Vector3.Transform(new Vector3(0, 1, 0), Matrix.CreateFromQuaternion(cameraRotation)) view Matrix.CreateLookAt(position, target, cameraup) Could someone help me get my camera in the correct position?"} {"_id": 12, "text": "Zune same features as WP7? (gesture, accelerometer) We don't have zune HD in Canada (yet) just wondering if it has the same programmable features as WP7? Like gestures and accelerometer. Basically if I am just making a game, with screen controls (thumbsticks on the screen) is this an easy port to zune? Thanks!"} {"_id": 12, "text": "how to move the camera behind a model with the same angle? in XNA I'm having difficulty moving my camera behind an object in a 3D world. I'd like to have two view modes for fps (first person). external view behind the character (third person). I've searched the net for examples but they don't work in my project. Here is my code used to change the view when F2 is pressed Camera double X1 this.camera.PositionX double X2 this.player.Position.X double Z1 this.camera.PositionZ double Z2 this.player.Position.Z Verify that the user must not let the press F2 if (!this.camera.IsF2TurnedInBoucle) If the view mode is the second person if (this.camera.ViewCamera type CameraSimples.ChangeView.SecondPerson) this.camera.ViewCamera type CameraSimples.ChangeView.firstPerson Calcul position ?? Here my problem double direction Math.Atan2(X2 X1, Z2 Z1) 180.0 3.14159265 Calcul angle ?? Here my problem this.camera.position .. this.camera.rotation .. this.camera.MouseRadian LeftrightRot (float)direction IF mode view is first person else ...."} {"_id": 12, "text": "Keeping the meshes \"thickness\" the same when scaling an object I've been bashing my head for the past couple of weeks trying to find a way to help me accomplish, on first look very easy task. So, I got this one object currently made out of 5 cuboids (2 sides, 1 top, 1 bottom, 1 back), this is just for an example, later on there will be whole range of different set ups. Now, the thing is when the user chooses to scale the whole object this is what should happen X scale top and bottom cuboids should get scaled by a scale factor, sides should get moved so they are positioned just like they were before(in this case at both ends of top and bottom cuboids), back should get scaled so it fits like before(if I simply scale it by a scale factor it will leave gaps on each side). Y scale sides should get scaled by a scale factor, top and bottom cuboid should get moved, and back should also get scaled. Z scale sides, top and bottom cuboids should get scaled, back should get moved. Hope you can help, EDIT I am asking you, if any of you have any idea on how to accomplish this scaling. I have tried whole bunch of things, from scaling all of the object by the same scale factor, to subtracting and adding sizes to get the right size. But nothing I tried worked, if one mesh got scaled correctly then others didn't. Donwload the example object."} {"_id": 12, "text": "How to get max viewable X Value in Viewport How can I calculate or get the farthest X Value of a Viewport during gameplay? Say a model is moving in from the right hand side (beyond Viewport) and starting from a certain X Value it is visible on the viewport. I'd like get that certain X Value. But the more I zoom out (Z Axis) the greater the farthest visible X gets (Max X). How could I approach this?"} {"_id": 12, "text": "How do I make a more or less realistic water surface? I want to make a similar water surface like in this picture I need the water surface in the same view than in the picture. Is it possible to work without shaders? I want to develop a little game for Xbox Live Indie Marketplace, Windows Phone and maybe later iPhone iPad. How should I make the water surface, so that it works on multiple platforms?"} {"_id": 12, "text": "Clarification on RenderTargetUsage in XNA 4.0 I'm trying to understand the exact meaning of RenderTargetUsage.DiscardContents. The documentation says Determines how render target data is used once a new render target is set. DiscardContents Always clears the render target data. Does calling GraphicsDevice.SetRenderTarget(null) to return to the back buffer count as setting a new render target (therefore clearing discarding any previous one)? Are the contents discarded either way at the end of the frame (i.e. when the graphic device presents), or do they persist into future frames even in this mode?"} {"_id": 12, "text": "How to adjust GUI to screen resolution ? I've created a GUI for my XNA game and now I'm stuck with a problem. My GUI element positions are designed for a max resolution of 1920x1080, and if I try changing it to 640x480 they disappear from the screen. What I can change to keep them there?"} {"_id": 12, "text": "Automating XNA Performance Testing? I was wondering what peoples approaches or thoughts were on automating performance testing in XNA. Currently I am looking at only working in 2d, but that poses many areas where performance can be improved with different implementations. An example would be if you had 2 different implementations of spatial partitioning, one may be faster than another but without doing some actual performance testing you wouldn't be able to tell which one for sure (unless you saw the code was blatantly slow in certain parts). You could write a unit test which for a given time frame kept adding updating removing entities for both implementations and see how many were made in each timeframe and the higher one would be the faster one (in this given example). Another higher level example would be if you wanted to see how many entities you can have on the screen roughly without going beneath 60fps. The problem with this is to automate it you would need to use the hidden form trick or some other thing to kick off a mock game and purely test which parts you care about and disable everything else. I know that this isnt a simple affair really as even if you can automate the tests, really it is up to a human to interpret if the results are performant enough, but as part of a build step you could have it run these tests and publish the results somewhere for comparison. This way if you go from version 1.1 to 1.2 but have changed a few underlying algorithms you may notice that generally the performance score would have gone up, meaning you have improved your overall performance of the application, and then from 1.2 to 1.3 you may notice that you have then dropped overall performance a bit. So has anyone automated this sort of thing in their projects, and if so how do you measure your performance comparisons at a high level and what frameworks do you use to test? As providing you have written your code so its testable mockable for most parts you can just use your tests as a mechanism for getting some performance results... Edit Just for clarity, I am more interested in the best way to make use of automated tests within XNA to track your performance, not play testing or guessing by manually running your game on a machine. This is completely different to seeing if your game is playable on X hardware, it is more about tracking the change in performance as your game engine framework changes. As mentioned in one of the comments you could easily test \"how many nodes can I insert remove update within QuadTreeA within 2 seconds\", but you have to physically look at these results every time to see if it has changed, which may be fine and is still better than just relying on playing it to see if you notice any difference between version. However if you were to put an Assert in to notify you of a fail if it goes lower than lets say 5000 in 2 seconds you have a brittle test as it is then contextual to the hardware, not just the implementation. Although that being said these sort of automated tests are only really any use if you are running your tests as some sort of build pipeline i.e Checkout Run Unit Tests Run Integration Tests Run Performance Tests Package So then you can easily compare the stats from one build to another on the CI server as a report of some sort, and again this may not mean much to anyone if you are not used to Continuous Integration. The main crux of this question is to see how people manage this between builds and how they find it best to report upon. As I said it can be subjective but as knowledge will be gained from the answers it seems a worthwhile question."} {"_id": 12, "text": "Scaling Rotating triangle I have a Triangle class and a list of triangles representing my 3D model shape. When I update the position, the rotation or the scale of my model, I also want my triangles list to be updated. I already made the function to update triangle position, but I can't make it for rotation scale... private void UpdateModelTrianglesPos(Vector3 oldPos, Vector3 newPos) Vector3 diff newPos oldPos for (int i 0 i lt trianglesPositions.Count i ) trianglesPositions i .UpdatePosition(diff) Thank you for your help!"} {"_id": 12, "text": "MMORPG Server architecture How to handle player input (messages packets) while the server has to update many other things at the same time? This is more or less like what I'm thinking up to now while(true) if (hasMessage) handleTheMessage() But while I'm receiving the player's input, I also have objects that need to be updated or, of course, monsters walking (which need to have their locations updated on the game client everytime), among other things. What should I do? Make a thread to handle things that can't be stopped no matter what? Code an \"else\" in the infinity loop where I update the other things when I don't have player's input to handle? Or even should I only update the things that at least one player can see? These are just suggestions... I'm really confused about it. If there's a book that covers these things, I'd like to know. It's not that important, but I'm using the Lidgren lib, C and XNA to code both server and client."} {"_id": 12, "text": "How to draw to a surface, then draw that surface to the screen i have a 2D MonoGame Game (using DirectX), that was originally an XNA game. It involves prerendered shadows (they are Texture2Ds drawn with SpriteBatch.draw). Right now the shadows are being drawn with an alpha value, so overlapping shadows appear darker. This is NOT what i want. Overlapping shadows should be the same shade of black. So what i want to do is draw all these shadows to a surface, such that the shadows are completely black (alpha 255), and the surface background is completely transparent (alpha 0), and then take that surface and draw it to the screen using Color.White 0.25f to give alpha to the shadows at the end. I'm not sure how to switch rendering targets, or whatever the terminology is, and go about this. Can someone help? what ive tried so far GraphicsDevice.SetRenderTarget(RENTAR) RENTAR is the name of my RenderTarget2D GraphicsDevice.DepthStencilState new DepthStencilState() DepthBufferEnable true not really sure what this does but it was in examples GraphicsDevice.Clear(Color.White 0.0f) i clear it with a totally transparent white background, in other words, white with alpha 0 now draw shadows normally, but instead of Color.White 0.25f, i use Color.White so that the black shadows are drawn completely black, with no alpha GraphicsDevice.SetRenderTarget(null) switch render target back to the screen SpriteBatch.Draw(RENTAR, new Rectangle(0, 0, 800, 600), Color.White 0.25f) see i added the \" 0.25f\" to try to draw this texture with alpha, but it comes out totally blank So all of this works except that the shadows end up being completely black. I want them completely black in the RenderTarget, so that they dont overlap with any darker shades, and then i want to draw the final RenderTarget on the screen with an alpha of 0.25f, hence \"Color.White 0.25f\" in the final spritebatch draw. But its as if that 0.25f doesn't exit."} {"_id": 12, "text": "HLSL Gaussian blur pixelshader blur is not occurring I am trying to use postprocessing to create a gaussian blur, however, no blur is to be seen, what am I doing wrong? I have included the full code at the bottom of this post in a google docs link, but here are the most important bits and pieces. Part of the xna draw method RenderTarget2D renderTarget renderTarget new RenderTarget2D(this.device, screenWidth, screenHeight, true, pp.BackBufferFormat, pp.DepthStencilFormat) this.device.SetRenderTarget(renderTarget) this.device.Clear(ClearOptions.Target ClearOptions.DepthBuffer, Color.DeepSkyBlue, 1.0f, 0) Rectangle screenRectangle new Rectangle(0, 0, screenWidth, screenHeight) Set the effect parameters (the 'simple' technique creates a red lambertian shaded model, like is shown on the image below) effect.CurrentTechnique effect.Techniques \"Simple\" effect.Parameters \"TextureWidth\" .SetValue(screenWidth) device.DepthStencilState DepthStencilState.Default device.BlendState BlendState.Opaque Draw the model mesh.Draw() Render our scene this.device.SetRenderTarget(null) effect.CurrentTechnique effect.Techniques \"GaussianBlur\" spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect) spriteBatch.Draw((Texture2D)renderTarget, screenRectangle, Color.White) spriteBatch.End() The pixelshader float Pixels 13 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, float BlurWeights 13 0.002216, 0.008764, 0.026995, 0.064759, 0.120985, 0.176033, 0.199471, 0.176033, 0.120985, 0.064759, 0.026995, 0.008764, 0.002216, float4 GaussianPixelShader(float2 TextureCoordinate TEXCOORD0) COLOR Pixel width float pixelWidth 1 TextureWidth float4 color 0, 0, 0, 1 float2 blur blur.y TextureCoordinate.y for (int i 0 i lt 13 i ) blur.x TextureCoordinate.x Pixels i pixelWidth color tex2D(TextureSampler, blur.xy) BlurWeights i return color What I have further found out by testing The code in the GaussianPixelShader does get executed (if I set it to just return a black color it gives an entire solid black screen) but just doesn't seem to work do the blurring. Images This is how currently my model looks (I cant see any blurring but maybe the blurring is just too light) image. Full Code Link to the shader code and the link to the xna c code."} {"_id": 13, "text": "Rendering the whole game world I'm trying to create a live minimap of the complete game world. In order to do that I'm taking a snapshot of the whole game world (not only the part that is displayed) every 100ms or so. The code I've used to take the snapshot is this (called every update()) if (game.time.time lt this.nextUpdate) return this.stage.drawFull(game.world) Draw our black border rect this.thumbnail.rect(0, 0, this.thumbnail.width, this.thumbnail.width, ' 000') And copy the stage capture to our Thumbnail (offset by 2px for the black border) this.thumbnail.copy(this.stage, 0, 0, this.stage.width, this.stage.height, 2, 2, this.thumbnail.width 4, this.thumbnail.width 4) this.thumbnail.update() this.nextUpdate game.time.time this.updateRate The code that creates these variable is this (called in create()) The Stage is a BitmapData the size of the Game window this.stage game.make.bitmapData(game.world.width, game.world.height) Thumbnail will hold our scaled down version ( 4px padding for the black border) this.thumbnail game.make.bitmapData(150, 150) And thumbContainer is a Sprite with the thumbnail for its texture this.thumbContainer game.make.sprite(game.width 150, game.height 150, this.thumbnail) Note we add the thumbContainer to the Stage, not the World, to avoid it being captured itself game.stage.addChild(this.thumbContainer) This is the result As you can see in the bottom right minimap The bitmap is rendered but the background isn't rendered for the whole thing (I think it's only rendered properly for the first 800x600 pixels). Also, if the player goes further down to the bottom ledge the minimap messes up completely It seems like a render issue, or a bitmap copy issue, but I can't find the problem. Does anyone have any idea why is this happening? Thanks!"} {"_id": 13, "text": "How would I create a shadowy \"Fog of War\" effect in Game Maker Studio 2? You know if you ever played \"StarCraft,\" as you explore the map it's dark until you go to that area. I am trying to replicate this effect in Gamemaker studio 2. I want to create a shadowed area effect on the map, so that when a \"obj player\" moves to a darkened area it reveals that part of the map. Here is a picture to help describe the effect i'm trying to achieve"} {"_id": 13, "text": "Rendering 10M point that changing position (individualy) at 30Hz i'm able with openTk (vb.net) to draw 10M of points adn rendering it. The problem is that the bind operation take 114mS on every frame refresh. I need to refresh the position at 30 Hz , so what can i use for speeder this operation."} {"_id": 13, "text": "How do I efficiently determine what objects are visible to a camera? I want to call the rendering methods of only the game objects that are visible. How can I efficiently determine which objects or tiles are within the camera's rendered region?"} {"_id": 13, "text": "Vulkan PushDescriptorSetTemplates (Can only parts of the UpdateTemplate be updated?) I'm exploring the VkDescriptorUpdateTemplate usage and really like the efficiency in coding this versus individual DescriptorSets, except I have one concern. When making an UpdateTemplate for each shader \"program\" with multiple UBOs, SSBOs, combined image samplers, etc. and attempting to update a single buffer sampler, I have to update them all based on the template. In reading the specification and googling (not much information on descriptor templates), it isn't clear if there is a way to update only part of the DescriptorTemplate and allow the remainder of the bindings to remain. Quick Code Example (Updating all three buffer sampler bindings). This works but in changing the sampler, I have to rebind the other buffers as well. FDescriptorInfo Sampler(LinearSampler, Tex gt ImageView, VK IMAGE LAYOUT SHADER READ ONLY OPTIMAL) FDescriptorInfo Desc VertexBuffer, CameraBuffer, Sampler vkCmdPushDescriptorSetWithTemplateKHR(Vulkan gt CommandBuffer, Vulkan gt MeshProgram.UpdateTemplate, Vulkan gt MeshProgram.Layout, 0, Desc) If I just want to update the combined image sampler is there a way to only update the 3rd binding? The example below gives validation errors along with attempting to just pass a single DescriptorInfo as there is no way to tell PushDesctiptor which binding I want to update versus all of them in the template. FDescriptorInfo Sampler(LinearSampler, Tex gt ImageView, VK IMAGE LAYOUT SHADER READ ONLY OPTIMAL) FDescriptorInfo Desc 0, 0, Sampler FDescriptorInfo Desc Sampler Also tried this but there is no way to tell vkCmdPushDescriptorSetWithTemplate I'm only updating the 3rd binding. vkCmdPushDescriptorSetWithTemplateKHR(Vulkan gt CommandBuffer, Vulkan gt MeshProgram.UpdateTemplate, Vulkan gt MeshProgram.Layout, 0, Desc) Is it possible to reduce re binding re pushing other buffers when utilizing the DescriptorSetTemplates? Thanks in advance for any advice."} {"_id": 13, "text": "Vertex buffers interleaved or separate? Interleaved all vertex data (position, normal, texcoord...) kept in 1 vertex buffer, separate each vertex attribute is kept in a separate vertex buffer (1 for positions, 1 for normals...). I know this question came up many times and I also know there's no 1 right answer (sadly). But I'd like to try to list the main advantages disadvantages of both. Or maybe you have some general rules of thumb for when to use each. Advantages of interleaved faster? (all data for 1 vertex is fetched at once? sth about cache working better)? less API calls (for creating and setting buffers but that's probably a very small difference) Advantages of separate when different shaders need different vertex attributes (e.g. one shader needs only position and another needs position, normal and texcoord) it's possible to provide each shader only the data it needs and there's no data duplication when updating only e.g. position of vertices it's not necessary to resend the other attribute data (e.g. normals and texcoords) If you see any other differences please write. From the above it generally looks like a struggle between memory and performance optimisation. But maybe I'm wrong? Maybe one is better worse in most cases? Edit One more concern, actually with interleaved buffers I could end up sending unnecessary data to GPU and the data bandwidth is a big bottleneck in today's cards. Should I worry about that?"} {"_id": 13, "text": "Converting Cube Maps I have cube maps in lat long format, and i need to convert them to Horizontal Vertical Cross, and individual cross images, is there an utility to do that?"} {"_id": 13, "text": "Pygame performance issue for many images I've made a script for generating a game world based off of image pixel data. Trying to make a python map editor My progress so far has resulted in a program which loads an image and draws sprites in positions correlating with the map, like this Now the problem is that even for small levels, I'm noticing a drop in frame rate. The provided example level will make pygame drop from 100 fps to 80 fps. If the map is 40 x 40 the frame rate will be around 17. This is concerning, for two reasons. The program is not doing anything else than drawing images right now, how bad will the frame rate be when game logic is also being calculated every frame? Second, the aim is to ultimately make a two player strategy game, in which the levels would be significantly larger than the example, and in that case 20 frames per second is way below acceptable parameters. Every sprite in the game is a 48x48 pixel png image with some portion of transparency. Everything except rendering the sprites is done once when the game starts. This is the only code being run on every frame def draw(self) self.screen.fill((0,0,0)) for e in self.map layout.fixed list self.screen.blit(e.picture, e.rect) I'm guessing pygame's method for rendering images does not scale very well. Windows task manager shows my CPU utilisation at 2 with a map of size 40x40. My question is What can I do to improve frame rate? I don't mind switching from (or complementing) pygame to something else, so long as the transition is not very difficult for a novice programmer like myself."} {"_id": 13, "text": "Deferred Shading and Transparency Clarification? So, this is a bit of a simple question, but I can't seem to find a real answer anywhere. I've been looking into implementing deferred rendering using MRT into my in progress render engine, but I'm a bit hesitant to for the following reason. I've read in a few places now that deferred shading does not support transparency natively, and if I wanted to achieve transparency, I would need to resort to forward shading of these transparent objects. But, the idea of \"transparency\" seems a bit vague because it seems as if there might (corrct me if I'm wrong) be two types of transparency. One type being the sort of overlay transparency, where I, say, tile a wall with a brick texture. Then I want the wall to be 50 transparent so I apply that on top of the already textured object. This appears to be one \"mode\" transparency in which the engine, as part of its rendering pipeline, inserts this transparency manually. The next type in my mind is using a texture that already has an alpha value associated with it, i.e. a 256x256 image of a person, where everything that isn't the person has an alpha value of zero. Then, if I were to billboard that image of the man onto a simple quad (which is what I'm actually trying to do in my game, for reference), would that sort of \"native\" transparency on the parts of the image with zero alpha still render as transparent, even in a deferred rendering situation? Does such a distinction exist between these two types of transparency, or are they merely two sides of the same coin when it comes to deferred rendering?"} {"_id": 13, "text": "Triangle Strips of Tetraheron I am confused about the triangle strip representation of closed mesh .The vertex buffer for triangle strip representation of the a figure is shown below A(0,1) B(0,0) C(1,1) D(1,0)E(2,1) vertex buffer A,B,C,D,E where, T1 (A,B,C) T2 (B,C,D) T3 (C,D,E) Now, if I have a tetrahedron with four vertex A(0,0,0),B(1,0,0),C(0,1,0) and D(0,0,1) then what would be its vertex buffer representation? Thank you very much."} {"_id": 13, "text": "Camera rotation deforms objects I'm working on a ray tracer in C with an adjustable camera for a university assignment. I'm entirely new with graphics and I'm struggling with one thing. I have a matrix as a mat4 object (4x4 matrix with each cell saved in a 1D array) that I save in a Camera object that handles transformations of every point in the scene (which is currently just two spheres). Translations seem to be working fine, but when I attempt rotations, things break. The spheres deform, and it only gets worse the more I attempt to rotate the camera. This is where I set the camera matrix mat4 Renderer setCameraMatrix(const Camera amp camera) mat4 cameraToWorld mat4() Initialise 4x4 matrix. Translation. cameraToWorld.cell 3 camera.pos.x cameraToWorld.cell 7 camera.pos.y cameraToWorld.cell 11 camera.pos.z Rotation. cameraToWorld.cell 0 camera.orientmat.cell 0 , cameraToWorld.cell 1 camera.orientmat.cell 1 , cameraToWorld.cell 2 camera.orientmat.cell 2 cameraToWorld.cell 4 camera.orientmat.cell 4 , cameraToWorld.cell 5 camera.orientmat.cell 5 , cameraToWorld.cell 6 camera.orientmat.cell 6 cameraToWorld.cell 8 camera.orientmat.cell 8 , cameraToWorld.cell 9 camera.orientmat.cell 9 , cameraToWorld.cell 10 camera.orientmat.cell 10 return cameraToWorld This matrix is then used to set the origin and direction of the camera in the world space later on in the code vec3 orig transformpoint(vec3(0), cameraToWorld) ... vec3 dir transformvector(vec3(x, y, 1), cameraToWorld) orig dir.normalize() The transformpoint and transformvector functions basically multiply a vector v by a matrix M (M.v), except the former takes into consideration translations, and the latter doesn't. Their code can be found here. The orientmat matrix is calculated from the three separate orientation angles (orient.x, orient.y, orient.z) in this line of code cam gt orientmat mat4().rotatexyz(cam gt orient.x, cam gt orient.y, cam gt orient.z) Using this function mat4 mat4 rotatexyz(const float a, const float b, const float c) mat4 M const float ca cosf(a), sa sinf(a) const float cb cosf(b), sb sinf(b) const float cc cosf(c), sc sinf(c) M.cell 0 cb cc, M.cell 1 1 cb sc, M.cell 2 sb M.cell 4 sa sb cc ca sc, M.cell 5 1 sa sb sc ca cc, M.cell 6 1 sa cb M.cell 8 1 ca sb cc sa sc, M.cell 9 ca sb sc sa cc, M.cell 10 ca cb return M (This function basically creates this transformation matrix from the three camera orientation angles.) I've tried to keep this question as compact as possible but I can provide more code if needed. I'm completely baffled about why I'm getting this kind of deformation on my spheres, and some insight would be invaluable! Thanks."} {"_id": 13, "text": "What is a texture atlas? I've heard about this concept, but what is it?"} {"_id": 13, "text": "Drawing pixels with SDL2 advice, is it fine to draw them one by one on the CPU? I want to make a raycaster and I figured out how to open a window and draw pixels to it with SDL2, but the way I am doing it now just doesn't seem very efficient, I figured out how to do it from briefly reading the documentation. For every pixel in the window, I am going through them one by one, setting the render color with SDL SetRenderDrawColor(), then drawing the pixel with SDL RenderDrawPoint() based on an array. It's surprisingly fast doing this but is there some way I can send like a pixel buffer to the GPU or something? I see there is a SDL RenderDrawPoints (plural version) function but it only takes positions, meaning all the pixels drawn with it would be the same color? I'm looking for a similar function but either it also takes the color data too or it is just a buffer of color data and its index determines its position. Rendering a bunch of pixels that are all the same color doesn't seem very useful to me. I later tested it by fading between colors and with window sizes of more than 600 x 400 the performance is horrible with my method, with 1200 x 800 it is like 5fps."} {"_id": 13, "text": "SDL 2 SDL BLENDMODE BLEND way faster. Why? I was just tinkering around with a simple ecs, when I noticed drawing like 20,000 rectangles killed my framerate ( 10 FPS). I thought ok, maybe it's just too many. Later I wanted to draw them transparent and set the blend mode to SDL BLENDMODE BLEND. Now I can draw around 60,000 of them with 60 FPS. I figured maybe it's because of pixel format conversion or something alike. When I use getWindowPixelFormat I get RGB888. No I'm even more confused because of the lacking alpha channel. Code (abbreviated) SDL Window window SDL CreateWindow( quot Test quot , SDL WINDOWPOS CENTERED, SDL WINDOWPOS CENTERED, 1280, 720, wndFlags) SDL Renderer renderer SDL CreateRenderer( window, 1, SDL RENDERER PRESENTVSYNC SDL RENDERER ACCELERATED) while(running) SDL RenderClear(renderer) SDL SetRenderDrawColor(renderer, 0xFF, 0x00, 0xFF, 0xFF) SDL RenderFillRect(renderer, amp rect) SDL RenderPresent(renderer) SDL SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF) Could someone enlighten me please?"} {"_id": 13, "text": "Updating scene graph in multithreaded game In a game with a render thread and a game logic thread the game logic thread needs to update the scene graph used by the render thread. I've read about ideas such as a queue of updates. Can someone describe to a newbie at scene graphs what kind of interface the scene graph exports. Presumably it would be rather complicated. So then how does a queue of updates get implemented in C in a way that can handle the complexity of the interface of the scene graph while also being type safe and efficient. Again I'm a newbie at scene graphs and C ."} {"_id": 13, "text": "Books that discuss practical rendering techniques? I'm looking for some books that discuss practical rendering topics like say rendering a bsp level or md2 3 mode, making a little quake like game as the goal or something to that effect. Any recommendations would be much appreciated."} {"_id": 13, "text": "How can state changes be batched while adhering to opaque front to back alpha blended back to front? This is a question I've never been able to find the answer to. Batching objects with similar states is a major performance gain when rendering many objects. However, I've been learned various rules when drawing objects in the game world. Draw all opaque objects, front to back. Draw all alpha blended objects, back to front. Some of the major parameters to batch by, as I understand it, are textures, vertex buffers, and index buffers. It seems that, as long as you are adhering to the above two rules, there's little to be done in regards to batching. I see one possibility to batch, while still adhering to the above two rules. Opaque objects can still be drawn out of depth order, because drawing them front to back is merely a fillrate optimization, meanwhile state changes may very well be far more expensive than the overdraw of drawing out of depth order. However, non opaque objects, those that require alpha blending at least, must be drawn back to front in order to avoid rendering artifacts. Is the loss of the fillrate optimization for opaques worth the state batching optimization?"} {"_id": 13, "text": "Rotate around a 3d Object (Software Renderer) I have a simple 3d software renderer (SDL C ) which can load a 3ds Model and render it (shaded) and rotate it around X Y Z Axis. Now I would like to rotate move around the object, meaning, the object itself stands still, and everything in the scene is displayed from the angle of the view. Is that what a camera in 3d engines does, and how would I implement something like this ? (No OpenGL DirectX is used, just plain software)"} {"_id": 13, "text": "How do you simulate UV light and materials with UV reflective fluorescent properties within a PBR renderer? I have a PBR setup, say, in Unity (or Unreal, doesn't really matter, I'm asking about the general principle, not specific implementation), and I would like to add a UV light source, and have control over how my materials respond to it, but still ideally have it conform to the rules of physically based rendering. Question is what do I need to extend with what kinds of properties, and what are the equations to wire them together, and where do I plug those? Do I need to actually do modifications like this, or does the fact that it already is PBR mean that I only need to plop in a light source with correct combination of settings, and correct responses to that UV source just naturally happen? Edit I am asking about fluorescence, where I want certain materials to glow in particular visible light colours in places where the invisible UV light hits them."} {"_id": 13, "text": "Forward Shading with multiple shadow casting lights I am currently thinking about how to organize shadowing and lighting. We use forward rendering and currently, our algorithm looks like this collect all items that are visible in the view for each item, collect a list of lights where the item is in the attenuation radius (each item keeps a list of lights) determine the shadow light by the distance of the main character (only one light can currently cast shadow) render the scene by using a constant buffer of the currently processed item to shade it (each item is rendered with a constant buffer which contains light properties. the number of lights per item is predefined so we have a Light 16 and numLights in the constant buffer) How would I do multiple shadow casting lights in an organisatory way? We do not want to go the deferred way, since we dont want to limit us to GBuffers."} {"_id": 13, "text": "Why would you want multiple render targets? In d3d11, you can bind multiple render targets ID3D11DeviceContext OMSetRenderTargets. But why would you want to do this?"} {"_id": 13, "text": "Forward Shading with multiple shadow casting lights I am currently thinking about how to organize shadowing and lighting. We use forward rendering and currently, our algorithm looks like this collect all items that are visible in the view for each item, collect a list of lights where the item is in the attenuation radius (each item keeps a list of lights) determine the shadow light by the distance of the main character (only one light can currently cast shadow) render the scene by using a constant buffer of the currently processed item to shade it (each item is rendered with a constant buffer which contains light properties. the number of lights per item is predefined so we have a Light 16 and numLights in the constant buffer) How would I do multiple shadow casting lights in an organisatory way? We do not want to go the deferred way, since we dont want to limit us to GBuffers."} {"_id": 13, "text": "Ray casting through terrain mesh Octree ( Mesh collision ) I'm currently in development of a terrain editor which i will use for my game. One thing that is partially stopping my development is that I don't have collision detection implemented between mouse ray cast and the terrain mesh. The terrain is consisted of triangles and can be lowered and raised.Also the x and y values of the mesh don't change. Of course what i need to do is ray cast through my mouse positions and get intersected triangle. I would get the point on the triangle using Barycentric coordinates. Just I'm not quite sure how does octree come into play here. As far as I understand it it works like a 3d quadtree, splitting the box into smaller box that the ray intersects. But which box do i choose ? How do i know which box is the closest one to the terrain, if either raised or lowered terrain ? How many subdivisions would i have? I was thinking on having as much as i have tiles( basically the last level of subdivisions would correspond to a x 3 box). Right now i'm just doing collision with the 0 Z value plane, and it works okay, but if the terrain is a bit raised then this can give faulty results. Other two methods that i found is to iterate through the mesh, which of course is insanely inefficient the other is to project the terrain in reverse and then i guess do some checking with the mouse coordinates (think it's called z buffer checking or something). If anyone has any other ideas i'm all ears. Just note that the algorithm should be an efficient one (of course this depends on the implementation) and accurate. Thanks !"} {"_id": 13, "text": "Rendering large and high poly meshes Consider an huge terrain that has a lot polygons, to render this terrain I thought of following techniques Using height map instead of raw meshes Yes, but I want to create a lot of caves and stuff that simply wont work with height maps. Using voxels Yes, but I think that this would be to much since I don't even want to support changing terrain.. Split into multiple chunks and do some sort of LOD with the mesh Yes, but how would I do that? Tessellation usually creates more detail not less. Precompute the same mesh in lower poly version (like Mudbox does) and depending on the distance it renders one of these meshes Graphic memory is limited and uploading only the chunks won't solve that problem since the traffic would be too high. IMO the last one sounds really good, but imagine the following process Upload and render the chunks depending on the current player position. No problem Player will walk straight forward Now we maybe have to change on of the low poly chunk with the high poly one So, Remove the low poly chunk and load the high poly chunk Already to much traffic here, I think I am not very experienced in graphic programming and maybe the upper process is totally okay but somehow I think it is too much. And how about the disk space it would require.. I think 3 kind of levels would be fine but isn't that also too much? (I am using OpenGL but I don't think that this is important)"} {"_id": 13, "text": "Unity 5 Mouse Disappears during runtime My mouse cursor disappears during runtime. When I click esc, it appears and the moment I click on something, it disappears again. This is what I have done so far to fix this. I have added this to a script on an empty gameobject in my scene. void Start() Cursor.visible true The problem persists and so I added the code to the update function. Still the same. I do not understand what am I missing here. Why is the cursor disappearing the moment I click and why doesn't it appear automatically onStart during runtime? I have also tried to implement a custom cursor and the same problem again. I am using 5.3.2f. I hope someone can point me in the right direction. Cant find a solution in any forums."} {"_id": 13, "text": "How to create a vertex buffer that provides this pattern? I have a series of vertices that I want to layout with the following configuration, but I haven't been able to find out how to do this with the square and X pattern. Most of the time I have generally seen a quad split into two triangles usually using triangle lists. I suspect this is using triangle strips but I am not exactly sure how to do it. Could anyone help?"} {"_id": 13, "text": "How can I create a \"cracked glass\" material? I'm trying to figure out how the cracked and chipped glass effect in a Bioshock Infinite Burial at Sea Episode 2 works. My current guess is that it is essentially a transparent shader with gloss. It would have a map defining the direction of reflections from the environment, with the cracks being significantly different from the mesh's normals. It would also include some kind of model of the angular dependence of the amount of refraction transmission to reflection so that it can roughly approximate Fesnel's equations. It doesn't appear to be a full refractive model, so I'm wondering how exactly this is implemented? Am I right with what I have said above?"} {"_id": 13, "text": "Techniques to mitigate microstuttering when the FPS is above 60fps and vsync is off The problem with first person shooters is that your input is important, and coupling it with VSync ruins it. The following frames per second data when rendering with OpenGL shows 60 100 fps annoying jitter 140 fps minor jitter, but certainly noticeable 200 fps very minor small jitter sometimes 260 fps either generally fine or very very small 300 fps perfectly fine The problem is other games I play that use similar rendering algorithms only stutter in the range of 60 100fps, whereas my range is 60 250fps (albeit it gets better when you get into the 200 range but you can still notice it if paying attention). At first I thought my game loop may have been wrong, but after going through it in great detail it is working just fine (and vsync works perfectly smooth with it too, if it was broken this would be an issue the update rate and the vsync monitor refresh rate are not divisible by each other). 60 100 fps is 62.5 10ms 100 250 fps is 10 4ms Not being able to go above 4ms would be pretty constraining! Because I'm using C (note I have zero GC, it doesn't run), I don't know if this means I'm somehow running into higher variability with the VM than I would when I did stuff in C . I don't know if being in the 4 10ms range means that sometimes it will spike. Now I did profile this, and this is what I've seen Ignoring the green line, the blue line is the uncapped version and orange is vsync. Since the vsync line has massive variability but seems to render fine, whereas the blue one has spikes but are all generally below the vsync line (and definitely not greater than the spikes from vsync), I don't understand whether I'm actually seeing those blue spikes and it's because of some kind of intermediate frame tear or not. It doesn't look like a frame tear to me, it just looks like a frame is lost and I lurch forward a bit more than normal like I was lagging online. So the question is... what can I do to diagnose this issue? Or is this normal? I was thinking of rendering to a framebuffer and just drawing that every 1 60 seconds in an attempt to smooth things out and emulate vsync but this comes with it's own drawbacks. Problem is... my back is against the wall and I'm worried I'll be doing potentially stupid and wasteful stuff. EDIT 1 Ticker code that does what I do (int, double) timerFunc() long currentTime GetCurrentTime() accumulation currentTime lastTimeSeen lastTimeSeen currentTime If it returns 1.27, then we have to run 1 tick, and interpolate at t 0.27 double tickFraction accumulation timePerGametick int ticksToRun floor(tickFraction) double fraction tickFraction ticksToRun if (ticksToRun gt 0) accumulation (ticksToRun timePerGametick) return (ticksToRun, fraction) EDIT 2 Game loop and basic logic (uses timerFunc data from above) void update(int ticksToRun) for i in ticksToRun foreach plane in planes that should move plane.Tick() foreach entity in entities entity.Tick() interpolation will be in 0.0, 1.0) void render(double interpolation) foreach plane in planes planeDelta (plane.current plane.prev) planeInterpolated plane.prev (planeDelta interpolation) render(planeInterpolated) foreach entity in entities entityDelta (entity.current entity.prev) entityInterpolated entity.prev (entityDelta interpolation) render(entityInterpolated) swapBuffers() void gameLoop() while (true) (int ticksToRun, double fraction) timerFunc() pollInput() if (ticksToRun gt 0) update(ticksToRun) render(fraction)"} {"_id": 13, "text": "Why is my Tiled map distorted when rendered with LibGDX? I have a Tiled map that looks like this in the editor But when I load it using an AssetManager (full static source available on GitHub) it appears completely askew. I believe the relevant portion of the code is below. This is the entire method the others are either empty or might as well be. private OrthographicCamera camera private AssetManager assetManager private BitmapFont font private SpriteBatch batch private TiledMap map private TiledMapRenderer renderer Override public void create() float w Gdx.graphics.getWidth() float h Gdx.graphics.getHeight() camera new OrthographicCamera() assetManager new AssetManager() batch new SpriteBatch() font new BitmapFont() camera.setToOrtho(false, (w h) 10, 10) camera.update() assetManager.setLoader(TiledMap.class, new TmxMapLoader( new InternalFileHandleResolver())) assetManager.load(AssetInfo.ICE CAVE.assetPath, TiledMap.class) assetManager.finishLoading() map assetManager.get(AssetInfo.ICE CAVE.assetPath) renderer new IsometricTiledMapRenderer(map, 1f 64f)"} {"_id": 13, "text": "How do I prevent receiving data from the network from dropping rendering frames in a multiplayer game? I'm building an HTML5 massively multiplayer online game. I've been working on this project for awhile, but am having some trouble sorting through a couple of performance issues. Since this is a multiplayer game, information is sent to and received from the network. When a client needs to know about new entities on the screen, the server must stream this data. Unfortunately, one big problem I'm having right now is that sometimes either a) a lot of data needs to be streamed or b) lots of small pieces of data are streamed in a short amount of time. Both scenarios currently cause the client to drop rendering frames as the client spends its time receiving packets and processing the data. What is the best way to prevent the networking data from causing frame rate problems? I am particularly interested in approaches to this kind of system that minimize frame drop issues, though suggestions tailored to my specific situation are welcome. Update To elaborate on the type of information sent in my particular case, my client does minimal interpolation and receives updates anytime the state of an entity changes on the server. The client also receives large packets with the entire state of an entity the first time the client needs to know about that entity."} {"_id": 13, "text": "Rendering tiles at a larger size for a detailed look I'm trying to make my 32 bit tiled map become more quot zoomed quot in. However, I experience an error that I can't resolve. Firstly, I followed this post on how to render the tiles larger. This is my code (close to identical to the code in the other post) class TiledMap def init (self, filename) tm pytmx.load pygame(filename, pixelalpha True) self.width tm.width tm.tilewidth self.height tm.height tm.tileheight self.tmxdata tm def render(self,surface) ti self.tmxdata.get tile image by gid for layer in self.tmxdata.visible layers if isinstance(layer,pytmx.TiledTileLayer) for x,y,gid in layer tile ti(gid) tile pg.transform.scale(tile,(64,64)) lt Line that gives Error if tile surface.blit(tile,(x 64, y 64)) def make map(self) temp surface pg.Surface((self.width, self.height)) self.render(temp surface) return temp surface The error that is produced is tile pg.transform.scale(tile,(64,64)) TypeError argument 1 must be pygame.Surface, not None I'm suspecting that some tile that its trying to render simply is empty. I've tried a separate smaller map but the issue persists. Is it the tileset? They've all been processed through the program Tiled where they were initially part of one png. If anyone knows a possible solutions I'll gladly try one. Or any other methods that could make it more zoomed in..."} {"_id": 13, "text": "MonoGame rendering text with black boxes? I have a UI manager that renders a background image and some images and buttons using BlendState.AlphaBlend. This works as intended. However, when I try and draw some text on top of it with the same BlendState, each character is encased in a black box and it looks awful. I played around a bit and found that BlendState.Additive was the only one that didn't render the black boxes. However, the text is now slightly transparent, which looks weird. I then decided to mess around with custom BlendStates, but after around 10 minutes I found that there could be over 67 million different BlendStates. Hmm. My last thought is that it could be the font that is breaking it, because I tried rendering with the Arial font and AlphaBlend worked fine. Is there a way round this using BlendStates without finding a new font? tl dr I can only render text either with black boxes or half transparent. Text rendering code sb.Begin(samplerState SamplerState.PointClamp, blendState BlendState.AlphaBlend, transformMatrix Game.Camera.GetViewMatrix()) sb.DrawString(Game.Font, text, position, color) sb.End() SpriteFont File (using the free Minecraftia font) lt ?xml version \"1.0\" encoding \"utf 8\"? gt lt XnaContent xmlns Graphics \"Microsoft.Xna.Framework.Content.Pipeline.Graphics\" gt lt Asset Type \"Graphics FontDescription\" gt lt FontName gt Minecraftia lt FontName gt lt Size gt 6 lt Size gt lt Spacing gt 0 lt Spacing gt lt UseKerning gt true lt UseKerning gt lt Style gt Regular lt Style gt lt DefaultCharacter gt ? lt DefaultCharacter gt lt CharacterRegions gt lt CharacterRegion gt lt Start gt amp 32 lt Start gt lt End gt amp 126 lt End gt lt CharacterRegion gt lt CharacterRegions gt lt Asset gt lt XnaContent gt It's a pixelly game (so I need a blocky font to avoid weird antialiasing) and I think the font is a bitmap font. Just in case that makes a difference. Edit I found that setting the text size (in the SpriteFont file) to anything other than it's native size fixes the problem (but also renders with antialiasing, which I don't want). Also, this problem seems to happen with other bitmap fonts (tested 'Minecraftia' and '04b03')."} {"_id": 13, "text": "How do I refer to the two types of loading screen? I'm troubleshooting some issues beyond the scope of this forum, and I'd like to be able to talk about certain parts of the gaming experience, specifically the two types of loading screen I see in Prey. Both are shown in this short video I made. The first type with the loading bar is what I usually think of as the quot loading screen quot , but what do I call the second quot loading screen quot that happens right after with the moving squares in the bottom right? To be clear, I'd like a term to be used with non game devs."} {"_id": 13, "text": "Ideas for extending tic tac toe game? I'm building a 3D tic tac toe game and this is what I've implemented so far 3D renderer with texture mapping Playing against the computer Playing online (multiplayer) Now I'm a little lost what I could add. Obviously, tic tac toe isn't that exciting or advanced, but I just miss something to salt it a little bit. Therefore, could anyone please suggest some ideas that would be worth implementing? Thanks!"} {"_id": 13, "text": "Is there any reason to use a \"canvas\" based approach to GUI in isometric games? When designing game engine GUI systems, I know a lot of game engines (notably Unity and Unreal) use a sort of \"canvas\" system. However, in an isometric game where the camera is already orthographic, this seems like it might be overkill. Everything is already dictated in terms of pixels, as is the case in an isometric game I feel that there would be little need for such a \"canvas\", which seems to be the bridge between world space coordinates and screen space coordinates. With the orthographic view, world space is more seamlessly joined with screen space, so wouldn't it be simpler to get the position of the camera, define a set of points (i.e. top left, top right, center, etc.) on a plane that is directly in front of the camera and render controls directly in front of the camera? Would there be any downsides to this method, or am I missing the point entirely?"} {"_id": 13, "text": "What's the use and difference between Forward, Deferred and Physically Based Rendering? Maybe I'm still confused about my own understanding, Forward Render render the lighting of an object according to the light source in the scene. (e.g Phong) Deferred Render render the scene to get geometric information, store it in a buffer, and then apply lighting. (e.g ?) PBR treats lights in the scene the way it behaves in the real world. (e.g Ray tracing, Photon Mapping) I don't see how Forward and Deferred render are going to give much difference to the scene. Why do we need to store the geometrical value in Deferred Render before applying lighting ? Why don't we just compute lighting right away like Forward Render ? Also for Physically Based Rendering, computing each light takes a lot of time, and almost impossible to be done in real time. But why this technique is always considered the best ?"} {"_id": 13, "text": "Manual per glyph rendering with SDL TTF I'm trying to create a font atlas with SDL TTF. My idea was to create an SDL Surface for every character using TTF RenderGlyph Blended() and use TTF GlyphMetrics() to get glyph metrics so that I can position the surface relative to a baseline. I'm struggling with a correct positioning of a glyph. It looks like SDL TTF creates a surface with height which is at least the height of the font and width which is at least advance of a glyph, so the surface is bigger than just the glyph. How do I extract glyph's rectangle from the created surface? How do I position the glyph correctly relative to the base line on the screen? I thought y position of the glyph it should be baselineY maxy (where maxy is from TTF GlyphMetrics), but that places glyph too high above the base line."} {"_id": 13, "text": "Very slow motion smooth rendering cocos2d x I have a a white circle that I move on a black background very slowly. When I look very carefully, I see that the while moving the edge of the circle is jittering. In my opinion it is because the next row col of pixels becomes white from black where the circle should be rendered and as the pixel has some width I see some abrupt advance of the edge toward the direction. Ideally, this should not be visible if I would not have pixel discretization. But on the other hand a have a video sample with such a slow motion and my monitor renders it without any jumps on the edge. Hence, I think that it is because of not the fact that pixel have finite sizes but I render wrongly. How I can solve the problem? Any trick, flag? EDIT Here is the code I have used Sprite bg Sprite create(\"gfx letter background.png\") addChild(bg, 100) bg gt runAction(MoveBy create(80, Vec2(500, 500))) wherer the .png I have used is a white circle attached below You don't see the image above as it is white )"} {"_id": 13, "text": "How is the Unreal rendering pipeline implimented? I know this seems like a very broad question, but i am just interested in getting to know how the Unreal engine's rendering pipeline looks like, specially how it handles meterials, different types of lighting, and post processing. I know that Unreal4 uses differred shading, but how does it handle things like translucency, reflections, etc. I do not have access to the source code, that's why I asked this question here. You could even direct me to the source of the rendering part if available."} {"_id": 13, "text": "How can I create character graphics similar to Valkyrie Profile? I want to create a game with the character graphics similar to Valkyrie Profile. I don't know whether I should make my game character sprites pre rendered or hand drawn, or which technique would let me create a similar look. Are these created pixel by pixel, what sets me off is the ditter found in a lot of the images, kind of looks like the characters from treasure hunter G or harvest moon friends of mineral town. edit Added the screenshots from Treasure Hunter G and Harvest Moon. I know these are pre rendered sprites that are later incorporated into the game, just for comparison against the valkyrie profile ones. Also, the treasure hunter G is a SNES game, and the Valkyrie Profile is PSX one, so I expect an upgrade in graphics."} {"_id": 13, "text": "Input handling between game loops This may be obvious and trivial for you but as I am a newbie in programming I come with a specific question. I have three loops in my game engine which are input loop, update loop and render loop. Update loop is set to 10 ticks per second with a fixed timestep, render loop is capped at around 60 fps and the input loop runs as fast as possible. I am using one of the Javascript frameworks which provide such things but it doesn't really matter. Let's say I am rendering a tile map and the view of which elements are rendered depends on camera like movement variables which are modified during key pressing. This is only about camera viewport and rendering, no game physics involved here. And now, how can I handle input events among these loops to keep consistent engine reaction? Am I supposed to read the current variable modified with input and do some needed calculations in a update loop and share the result so it could be interpolated in a render loop? Or read the input effect directly inside the render loop and put needed calculations inside? I thought interpreting user input inside an update loop with a low tick rate would be inaccurate and kind of unresponsive while rendering with interpolation in the final view. How it is done properly in games overall?"} {"_id": 13, "text": "How to use a mask texture with Kobold2D I am an iOS developer but I'm new to cocos2d. I'm working on new game, I use Kobold2D, have cocos2d installed too, and I want to make this effect I know how is done with Flash, but can't make it with Kobold2D. There's 2 images with the same size one is a low res image for the background and the second is a hi res over the first one. When the \"reticle\" mask moves, it reveals the second image inside the circle and the background is visible outside only. I googled with no success, saw some Ray Wenderlich projects they weren't helpful."} {"_id": 13, "text": "Partial mesh culling by checking against the AABB tree of objects vertices instead of only the AABB of the whole objects First thing this is more of a conceptual question than an implementation oriented one, but still tips about implementation will be very much welcome if you happen to have any (athough I have some experience programming different parts of games, graphics are certainly my weak spot as you will see). So, I have an application in which all high poly objects have their vertices grouped in an object specific AABB tree to speed up the narrow phase of collision detection. Now, it occurred to me the following. Since that structure is already in place, would it be possible to use it for culling parts of objects instead of the usual all or nothing approach of the frustum and occlusion culling techniques? The idea for that is simple in concept. Instead of testing for visibility only using the whole objects' AABB, I would do that first but in the positive cases I would proceed to visibility checks of the sub AABBs containing that object's vertices. Once identified the sub AABBs that are visible, only the triangles that are contained in these sub AABBs would be sent to the GPU for rendering. Therefore, in a more systematized way, my three related questions are 1) is such an approach even possible in what regards the way GPU gets and processes the mesh geometry information pulled from CPU? 2) given that in such scenario the CPU would have to break the meshes somehow and pass to the GPU only the vertices that were identified as being in the visible parts of the visible objects, wouldn't that pose additional load on the processing time such that the cost would overcome the gains? 3) most importantly, passing to the GPU only some triangles of a mesh could cause graphically distorted results when shader and texture are rendered for that partially only rendered object? I searched quite a bit for academic references on this subject but came almost empty. I would gladly welcome reading suggestions of any sort."} {"_id": 13, "text": "Rendering a selected part of the terrain with different shading I'm trying to understand how to modify the shading of the section of the terrain based on some user selection. In a game like Civ5, when a user selects a city or unit, that area is lit up more than the other parts of the terrain. I'm trying to implement this effect. In the civ 5 example the selected tile is has a circle outline and the selected city has a transparent overlay that follows the height of the terrain nicely. My current pipeline so far is at a primitive state. I render a quad and texture it with a grass texture. Then I draw a rectangular grid on top of this (a set of lines, with a slightly higher height value than the background grid). Upon selection (ie a mouse click inside the grid area), I calculate the approriate grid index by converting mouse to world coordinates and then to grid coordinates, and highlight the appropriate grid rectangle by changing the color of that particular rectangle. But, my approach gets outdated the moment I get a height map (as it assumes constant height), and looks pretty bad, hence this question. EDIT Added my pipeline description"} {"_id": 13, "text": "How do 3D rendering pipelines render light effects? How does 3D software like Blender, Maya, Unity, or Houidini etc. render the effects of lights illuminating a 3D scene?"} {"_id": 13, "text": "Drawing a line between 2 vectors I was trying to implement a simple mechanic by drawing a line between the sprite and the mouse, but it's not working that well extends KinematicBody2D onready var player CollisionShape2D var pos two var pos func physics process(delta) var vel Vector2() pos two player.get position() pos get global mouse position() look at(pos) if Input.is action pressed( quot movethere quot ) vel Vector2(400 , 0).rotated(rotation) vel move and slide(vel) func draw() draw line( pos two ,pos, Color(255 , 0 , 0))"} {"_id": 13, "text": "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. I'm making a game in GML (GameMaker Language). Regardless of the language software, this should be a universal topic. Okay, 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. The 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. So, 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. Remember, 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. MORE INFO in 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. My ds grid contains enumeration values, such as tile.grass or tile.water. The terrain does not fit within the screen borders, and resolution directly affects view size."} {"_id": 13, "text": "16bit triangle lists vs 32bit triangle strips When drawing geometry we may use indexed drawing, where we pass index of the vertex we want to draw in array. In this case we need to pick a topology for our geometry and the type of indices. Popular topologies are triangle lists, where we have to specify 3 indices for each triangle, and triangle strips, where each new triangle shares its first 2 vertices with last 2 vertices of previous triangle. As for index types we have 16 bit indices, which allow for 65k vertices per model, and 32 bit indices, 4B vertices. My GPU (1050ti) fetches 32 bit indices at half the rate of 16 bit indices, where 16 bit indices triangle list topology gets it at its maximum throughput, but so do 32bit triangle strips. As my GPU isn't that old, I expect many GPUs to be quite alike in this manner. So, is the inconvinience of having to specify geometry in strips worse than having a limit to 65k vertices per model?"} {"_id": 13, "text": "How can I render cloud patterns like in these examples? I have a quick question. I see in many games, usually in the menu, some moving \"clouds\" in the background, apparently additive blended into each other, which does a really nice job immersing the player, in my opinion. A couple of examples that jump to mind right now are the Far Cry 3 main menu background https www.youtube.com watch?v B5XcMx3GjPA and the Plague Inc main menu background https www.youtube.com watch?v RQv60ywrLxU (the first seconds show it) These cloudy patterns seem like some kind of noise to me, like Perlin or other. So, how would you proceed to achieve that kind of blurred cloud effect with vivid colors? More specifically, would you pre generate sets of clouds and include them in the game package? Or generate them on the fly? On the CPU as a regular texture or on draw in the GPU shader program? I am interested in mastering this kind of visual effect, and as such any help would be appreciated pointing me in the right way. Thanks."} {"_id": 13, "text": "How can I keep straight alpha during rendering particles? Rencently,I was trying to save textures of 3D particles so that I can reuse the in 2D rendering.Now I had some problem with alpha channel.Some artist told me I that my textures should have unpremultiplied alpha channel.When I try to get the rgb value back,I got strange result.Some area went lighter and even totally white.I mainly focus on additive and blend mode,that is ADDITIVE srcAlpha VS 1 BLEND srcAlpha VS 1 srcAlpha I tried a technique called premultiplied alpha.This technique just got you the right rgb value,its all you need on screen.As for alpha value,it worked well with BLEND mode,but not ADDITIVE mode.As you can see in parameters,BLEND mode always controlled its value within 1.While ADDITIVE mode cannot guarantee. I want proper alpha,but it just got too big or too small consider to rgb.Now what can I do?Any help will be great thankful. PS If you don't understand what I am trying to do,there is a commercial software called \"Particle Illusion\".You can create various particles and then save the scene to texture,where you can choose to remove background of particles. Now,I changed the title.For some software like maya or AE,what I want is called straight alpha ."} {"_id": 14, "text": "How should I implement multi pass rendering in a game engine? I have done multi pass rendering, before, and understand how it works. I made a simple example, which rendered a basic scene with shadows. This was all part of one file. Now, I am trying to figure out is how to put it into my game engine. Currently, my game engine uses a single pass. It is in a hierarchical structure, and uses Direct3D 9. I have a graphics component, which will load and draw a 3D model. In my game loop, I update all of the entities in the world, then I call the draw function for each one. This draw function gets the vertex buffer, index buffer and texture or material, and draws the 3D model using a shader. This works fine. To do multi pass rendering, to allow for shadows, I will need to draw each model multiple times. It doesn't seem right, to me, that in each models draw function I should put the second pass code this will then be completed before the next models first pass. How should I implement multi pass rendering in a game engine?"} {"_id": 14, "text": "How do I create a manual object with colors for each vertex? How do I create a shaded manual object with colours for each vertex? Eg if ogreObj is the Ogre ManualObject ogreObj gt begin(\"BaseWhiteNoLighting\", Ogre RenderOperation OT TRIANGLE LIST) will allow me to select each vertex's colour with ogreObj gt colour(r, g, b) after each ogreObj gt position(x, y, z) and ogreObj gt normal(x, y, z) call. However, if I change the material to BaseWhite, color() instructions are ignored. I read that you must disable lighting int the .material script, but I need it active... Any advice? ANSWER This Ogre forum's thread has a simple .material script that works for this purpose material Voxel Default technique pass diffuse vertexcolour specular vertexcolour ambient vertexcolour lighting on"} {"_id": 14, "text": "cocos2d mask rotation I've been experimenting with Ray Wenderlich's tutorial about masking sprite using shaders with cocos2D 2.0. It works pretty well but now I'd like to rotate the mask independently of the masked texture. Does anyone have any idea about how to achieve it ?"} {"_id": 14, "text": "Using multiple shaders I'm currently studying opengl shaders but I can't figure out something how to apply different shaders to the objects, for example, a teapot rendered using toon shader and another one in the same scene using a very reflective surface and other distorted from a noise function, like in this video http www.youtube.com watch?v 1ogg4ZfdBqU Another one is applying a bloom shader in a scene and a motion blur shader afterwards. How to achieve those effects when you can only have one vertex shader and one fragment shader? Is there any trick such as using more than one shader program?"} {"_id": 14, "text": "Vertex Shader Fundamental Workings I understand that water ripples (e.g. stone thrown into a pond) are often handled with vertex shaders. My first question is are the ripples nothing more than an algorithm that is the function of time? If yes, it means that the size and diameter of ripples is not \"additive.\" It means water vertices do not statefully \"remember\" their previous \"disturbance\" positions and accumulate more translation info. Rather it means that, as a function of time, the position of \"disturbed\" water vertices are freshly computed each frame per unit time. If no, it means that indeed the vertices accumulate disturbance translation information the vertices are stateful. I hope the answer is \"yes,\" because that actually makes sense to me. If the answer is no, the I feel it creates tremendous burden on the CPU GPU to keep track of all the state per vertice. If the answer is \"neither,\" do tell. ) My second question is, assuming a \"yes\" above, how does such a \"water disturbance shader algorithm\" account for continuous interaction with irregular shapes? For example, please look at the video 40 second mark showing a car crashing through water. It is not so clear how the vertex shader knows how to make a rectangular disturbance shape (the shape of the car). Perhaps, over simplifying, the vertex shader takes both time and a vector to generate the ripples, where the vector is the speed direction of a car (and the shader code always makes a car shaped rectangle no matter what). Is this the right high level understanding of how this water trick works?"} {"_id": 14, "text": "Cocos2d x Differences between applying shader to child node and entire scene? I'm beginning with shader. I wonder what if i apply shader for single node, what'll happen? The gl FragCoord (0.5,0.5) is the bottom left of the screen or the bottom left of the node? I get some wrong caculations while wanting to draw something in the center of the node (not the screen). Many shader tutorias with sample code to draw at center using gl FragCoord.xy resolution.xy, if it's 0.5, it's center. In this case, it might be wrong because i want to draw in center of the node. Finally, how's about texture2D i use texture2D instead of texture, are they the same? I've applied this code on the node and it prints out the whole screen with stretch version (resolution device resolution) vec2 xy gl FragCoord.xy resolution.xy vec4 texColor texture2D(CC Texture0,xy) gl FragColor texColor"} {"_id": 14, "text": "How can I replicate the color limitations of the NES with an HLSL pixel shader? So since 256 color mode is depreciated and no longer supported under Direct3D mode, I got the idea to use a pixel shader instead to simulate the NES palette of all possible colors so that fading objects and whatnot don't have smooth fade outs with alpha channels. (I know objects couldn't really fade out on the NES, but I have all objects that do fade in and out on a solid black background, which would be possible with palette swapping. Also, the screen fades in and out when you pause which I know also was possible with palette swapping as it was done in a few Mega Man games.) Problem is, I know next to nothing about HLSL shaders. How do I do it?"} {"_id": 14, "text": "Monogame fails to load Effect I'm currently porting an old XNA game over to MonoGame and everything (including custom shaders) build fine. However when i try to load the xnb file using content.Load lt Effect gt (\"BaseDraw\") I receive the following error An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll Additional information HRESULT 0x80070057 , Module General , ApiCode E INVALIDARG Invalid Arguments , Message The parameter is incorrect. I even tried building the shaders with 2MGFX.exe and loading it manually but that throws the same error. I have no idea what to so any help would be appreciated!"} {"_id": 14, "text": "bug in webgl phong shader lighting rotates with object I'm working on a simple phong shader in webgl, and I think I'm getting close but something is still wrong. Dead give away if I have a billboard and have it roll (so it spins like a wheel), the part of the billboard that is lit up spins with it (. This confuses me, because it seems like a problem with the model matrix, but the transform makes all the positions amp rotations correct, and lighting math is done entirely in world coordinates , just the lighting wrong. Ditto with the view matrix, I can move around and look freely and everything is located in its proper place, just lit wrong. Here are my shaders (minus the definitions for space, and with the lighting in the model matrix moved into GPU for clarity) if you prefer reading in github https github.com nickgeorge quantum blob master index.html L41 lt script id \"fragment shader\" type \"x shader x fragment\" gt void main(void) vec3 lightWeighting if (!uUseLighting) lightWeighting vec3(1.0, 1.0, 1.0) else vec3 lightDirection normalize(vLightPosition.xyz vPosition.xyz) float directionalLightWeighting max(0.0, dot( normalize(vTransformedNormal), lightDirection)) lightWeighting uAmbientColor uPointLightingColor directionalLightWeighting vec4 fragmentColor if (uUseTexture) fragmentColor texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)) else fragmentColor uColor gl FragColor vec4(fragmentColor.rgb lightWeighting, fragmentColor.a) lt script gt lt script id \"vertex shader\" type \"x shader x vertex\" gt void main(void) vPosition uModelMatrix vec4(aVertexPosition, 1.0) TODO Move back to CPU vLightPosition uModelMatrix vec4(uPointLightingLocation, 1.0) gl Position uPerspectiveMatrix uViewMatrix vPosition vTextureCoord aTextureCoord vTransformedNormal normalize(uNormalMatrix aVertexNormal) lt script gt Thanks a lot, and let me know if there's anything else useful to add."} {"_id": 14, "text": "Algorithm for a rain effect (Shaders) I'm trying to implement a rain effect using shader, I use godot 3 alpha, which uses a simplified GLSL 3.0 language. But I'm just finding very complex examples for me, I understand little about shaders, I wanted to achieve something very basic even to be able to walk. I thought of doing the following, moving the texture with just a few painted pixels. Yet I still do not know where to start. I found this code, I really wanted to understand what is done in it http www.glslsandbox.com e 36547.0 I managed to translate the code for godot 3, but it does not work very well, I believe this line is to blame p 0.5 0.35 sin(11.0 fract(sin((s p scale) mat2(vec2(7,3),vec2(6,5))) 5.0)) f What really is done that line? I can not understand what he does. I did so shader type canvas item uniform float direction uniform float velocity 1.0 uniform float intensity float snow(vec2 uv, float scale, float time) float w smoothstep(1.0,0.0, uv.y (scale 10.0)) if(w lt 0.1) return 0.0 uv time scale uv.y time velocity scale VELOCITY uv.x sin(uv.y time 0.5) scale uv scale vec2 s floor(uv) vec2 f fract(uv) vec2 p float k 3.0 float d vec2 t (s p vec2(scale)) mat2(vec2(7.0, 3.0), vec2(6.0,5.0)) p.y (0.5 0.35 sin(11.0 fract(sin((s.y p.y scale) t.y) 5.0)) f.y) p.x f.x d length(p) k min(d,k) k smoothstep(0.0,k,sin(f.x f.y) 0.01) return k w void fragment() vec2 uv (COLOR.xy 2.0 SCREEN UV.xy) min(SCREEN UV.x,SCREEN UV.y) float c smoothstep(1.0,0.3,clamp(uv.y 0.3 0.8,0.0,0.75)) c snow(uv, 30.0, TIME) 0.3 c snow(uv, 20.0, TIME) 0.5 c snow(uv, 15.0, TIME) 0.8 c snow(uv, 10.0, TIME) c snow(uv, 8.0, TIME) c snow(uv, 6.0, TIME) c snow(uv, 5.0, TIME) c snow(uv, 2.0, TIME) COLOR vec4(vec3(c),0.5) and this happens I have discovered that by decreasing the value I am passing to the scale, it increases the \"particles\", I mean how octaves in a noise, the smaller the number last, the greater the peaos generated. But my screen seems to be divided in two, cut by a diagonal line, I do not understand much because. I realize that here is the problem vec2 uv (COLOR.xy 2.0 SCREEN UV.xy) min(SCREEN UV.x,SCREEN UV.y) Up 1 I managed to improve with this vec2 uv UV now it's like this but what he wanted was to be able to pass three uniforms, direction, velocity and intensity, and to be able to control the direction (right equer), the speed with which they fall, the intensity (higher or lower particles, more or less drops). But I still do not understand how well it is done to do that. Even more that what I will do is rain, I have to understand what is done with the colors to get the idea of rain and not snow. Up 2 I was stirring here and the velocity, intensity and direction I was able to configure passing a uniform. But I can not change the color of the drops, it always comes out black and white. How would you put a blue color for example? I try to change the color to red for example using the mix() function vec3 col2 vec3(1.0, 0.0, 0.0) vec3 resultColor mix(vec3(c), col2, 0.7) COLOR vec4(vec3(resultColor),0.3) and I get this I wanted to change only the color of the drops? R I got it like this COLOR vec4(vec3(0.3, 0.3, c),0.5) but I'm not very fond of the result, it's very bright, and my breasts are too big, I'll fix it."} {"_id": 14, "text": "HLSL How to flip geometry horizontally I want to flip my asymmetric 3d model horizontally in the vertex shader alongside an arbitrary plane parallel to the YZ plane. This should switch everything for the model from the left hand side to the right hand side (like flipping it in Photoshop). Doing it in pixel shader would be a huge computational cost (extra RT, more fullscreen samples...), so it must be done in the vertex shader. Once more this is NOT reflection, i need to flip THE WHOLE MODEL. I thought I could simply do the following Turn off culling. Run the following code in the vertex shader input.Position mul(input.Position, World) World 3 0 holds x value of the model's pivot in the World. if (input.Position.x lt World 3 0 ) input.Position.x World 3 0 input.Position.x else input.Position.x input.Position.x World 3 0 ... The model is never drawn. Where am I wrong? I presume that messes up the index buffer. Can something be done about it? P.S. it's INSANELY HARD to format code here. Thanks to Panda I found my problem. SOLUTION Do thins before anything else in the vertex shader. Position.x 1 To invert alongside the object's YZ plane."} {"_id": 14, "text": "What are the pros and cons of HLSL vs GLSL vs cg? What are the pros cons of the three?"} {"_id": 14, "text": "Fragment shader for lighting in isometric perspective What I'm trying to do is to achieve basic lighting in 2D from an isometric perspective. Here I have 2 textures that are used as tiles for the ground Color Normal map I have a fragment shader that was adjusted a bit to my needs, but mostly made from this tutorial https github.com mattdesl lwjgl basics wiki ShaderLesson6 Here is my fragment shader uniform sampler2D texture uniform sampler2D normal texture values used for shading algorithm... uniform vec2 Resolution resolution of screen uniform vec4 AmbientColor ambient RGBA alpha is intensity uniform vec3 LightPos 3 light position, normalized uniform vec4 LightColor 3 light RGBA alpha is intensity uniform vec3 Falloff 3 attenuation coefficients void main() vec4 DiffuseColor texture2D(texture, gl TexCoord 0 .xy) vec3 NormalMap texture2D(normal texture, gl TexCoord 0 .xy) vec3 Sum vec3(0.0) for (int i 0 i lt 3 i ) The delta position of light vec3 LightDir vec3(LightPos i .xy (gl FragCoord.xy Resolution.xy), LightPos i .z) Correct for aspect ratio LightDir.x Resolution.x Resolution.y Determine distance (used for attenuation) BEFORE we normalize our LightDir float D length(LightDir) normalize our vectors vec3 N normalize(NormalMap 2.0 1.0) vec3 L normalize(LightDir) Pre multiply light color with intensity Then perform \"N dot L\" to determine our diffuse term vec3 Diffuse (LightColor i .rgb LightColor i .a) max(dot(N, L), 0.0) pre multiply ambient color with intensity vec3 Ambient AmbientColor.rgb AmbientColor.a calculate attenuation float Attenuation 1.0 (Falloff i .x (Falloff i .y D) (Falloff i .z D D)) the calculation which brings it all together vec3 Intensity Ambient Diffuse Attenuation vec3 FinalColor DiffuseColor.rgb Intensity Sum FinalColor gl FragColor gl Color vec4(Sum, DiffuseColor.a) This shader WORKS with traditional 2D perspective. That's because in traditional perspective the ground tiles normal map would have a color scheme closer to something like this, just wouldn't be tilted to fit an isometric perspective of course. The issue How do I go about adjusting the math in my fragment shader to fit an isometric perspective and work with the \"greenish\" ground normal maps. Here's what I'm currently getting with this shader. Light should be equally going in all directions, but it's as if it's going down a slope."} {"_id": 14, "text": "Basic equation for pure metallic reflectance I'm working on a live wallpaper that shows a pure metallic object. Since it's a live wallpaper, I can make a ton of approximations...this isn't a full blown scene in a game world. My shader only has to support this one material. People won't expect extreme detail, etc. So, for example, I don't even bother with diffuse since a pure conductive material barely has any. So I'm trying to implement a reflective conductive surface that pulls the reflection from a cubemap representing the lighting environment. On a very basic level it looks like this vec3 fresnelSchlick (vec3 f0, float cosTheta) return mix(f0, vec3(1.0), pow(1.0 cosTheta, 5.0)) ... float NdV dot(normal, viewDir) vec2 brdf texture2D(u brdf, vec2(u roughness, NdV)).rg from a LUT vec3 reflection textureCube(u cubemap, reflect(viewDir, normal)) gl FragColor reflection (fresnelSchlick(materialColor, NdV) brdf.x brdf.y) The problem with my simple math here is that the range of possible final pixel colors does not produce a proper looking range of hues. Suppose my material color is 0050ff and the environment is monochrome white. Then all of the possible colors that could be seen are This doesn't allow for bright looking reflections at the light sources in the envmap. I found this example material render for comparison. The cubemap in the example here is close to monochrome white. But at the bright areas of the reflection, there is a lot of red component in the color. With my limited range of colors, my object looks dull and lifeless. Can anyone point out what I'm missing in my equation?"} {"_id": 14, "text": "Shader authoring editing tools for GLSL ES Since Render Monkey has been discontinued (perhaps due to the complexity of today's shading languages), there are few successors that can match its functionality. Is there any useful tool for material editing aimed at developers and artists alike, but concentrated (or with substantial support for) on embedded GLSL shaders? Render Monkey itself wasn't that flexible (I'm not aware if it allowed the usage of several textures, each with its own set of texture coordinates plus, it didn't seem to be that intuitive either). Apart from complete engines, is there such a stand alone tool that can be used together with a stand alone engine (able to interface with a custom application)?"} {"_id": 14, "text": "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. The vertex shader has a uniform vec3 realPlanePosition and calls a height calculation function Vertex shader code uniform vec3 realPlanePosition varying vPosition float heightCalculation(vec2 verticePosition) Just for pseudo code (more black magic append here). return magicNoise2D(verticePosition.x, verticePosition.y) void main(void) vec3 vPosition position vec2 verticePosition vec2(vPosition.x realPlanePosition.x, vPosition.y realPlanePosition.z) vPosition.z heightCalculation(verticePosition) gl Position projectionMatrix modelViewMatrix vec4(vPosition, 1.0) In 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. Is this good practice? Also, how do I detect collisions with it? And finally, how can I control other terrain objects' generation (rocks, trees, ...)"} {"_id": 14, "text": "Can't import shaders textures to Godot from Blender 2.8 I'm using this shader for my models and then i import them like this This is the original model in blender the result in godot I think i might have missed some step but not sure of which one, i followed the tutorial video on how to import and other similar guides but the results is the same. Any ideas of what i'm doing wrong? Looks like my model not importing shader and textures cor"} {"_id": 14, "text": "Bump mapping Problem GLSL I am having a slight problem with my Bump Mapping project. Although everything works OK (at least from what I know) there is a slight mistake somewhere and I get incorrect shading on the brick wall when the light goes to the one side or the other as seen in the picture below The light is on the right side so the shading on the wall should be the other way. I have provided the shaders to help find the issue (I do not have much experience with shaders). Shaders varying vec3 viewVec varying vec3 position varying vec3 lightvec attribute vec3 tangent attribute vec3 binormal uniform vec3 lightpos uniform mat4 cameraMat void main() gl TexCoord 0 gl MultiTexCoord0 gl Position ftransform() position vec3(gl ModelViewMatrix gl Vertex) lightvec vec3(cameraMat vec4(lightpos,1.0)) position vec3 eyeVec vec3(gl ModelViewMatrix gl Vertex) viewVec normalize( eyeVec) uniform sampler2D colormap uniform sampler2D normalmap varying vec3 viewVec varying vec3 position varying vec3 lightvec vec3 vv uniform float diffuset uniform float specularterm uniform float ambientterm void main() vv viewVec vec3 normals normalize(texture2D(normalmap,gl TexCoord 0 .st).rgb 2.0 1.0) normals.y normals.y normals (normals gl NormalMatrix).xyz vec3 distance lightvec float dist number length(distance) float final dist number 2.0 pow(dist number,diffuset) vec3 light dir normalize(lightvec) vec3 Halfvector normalize(light dir vv) float angle max(dot(Halfvector,normals),0.0) angle pow(angle,specularterm) vec3 specular vec3(angle,angle,angle) float diffuseterm max(dot(light dir,normals),0.0) vec3 diffuse diffuseterm texture2D(colormap,gl TexCoord 0 .st).rgb vec3 ambient ambientterm texture2D(colormap,gl TexCoord 0 .st).rgb vec3 diffusefinal diffuse final dist number vec3 finalcolor diffusefinal specular ambient gl FragColor vec4(finalcolor, 1.0)"} {"_id": 14, "text": "Disney BRDF where is metallic factor input into BRDF? Burley states about metallic parameter \"This is a linear blend between two different models. ...\" What are the two models? I can't see this described in the Frostbite or the Unreal papers either. Is it simply a blend between the diffuse and specular terms or a scaling factor on the specular term? Disney Paper"} {"_id": 14, "text": "Alpha is not working in diffuse light shader I am following this tutorials series on rastertek.com and I got a bit stuck on the Diffuse Lighting Tutorial. Particulary, the part that does not work for me is alpha channel of the light color. Here are the I think they are relevant code parts Light Shader cbuffer MatrixBuffer matrix worldMatrix matrix viewMatrix matrix projectionMatrix Texture2D shaderTexture SamplerState SampleType cbuffer LightBuffer float4 ambientColor float4 diffuseColor float3 lightDirection float padding struct PixelInputType float4 position SV POSITION float2 tex TEXCOORD0 float3 normal NORMAL float4 LightPixelShader(PixelInputType input) SV TARGET float4 textureColor float3 lightDir float lightIntensity float4 color textureColor shaderTexture.Sample(SampleType, input.tex) lightDir lightDirection lightIntensity saturate(dot(input.normal, lightDir)) color saturate(diffuseColor lightIntensity) color color textureColor return color PixelInputType LightVertexShader(VertexInputType input) PixelInputType output input.position.w 1.0f output.position mul(input.position, worldMatrix) output.position mul(output.position, viewMatrix) output.position mul(output.position, projectionMatrix) output.tex input.tex output.normal mul(input.normal, (float3x3)worldMatrix) output.normal normalize(output.normal) return output The problem here is the shader completely ignores the alpha channel of the light. If I set the diffuse color to red, then the texture will be reddish no matter what alpha is supplied. The only way I could make the alpha work is changing the line color color textureColor to color color color.w textureColor in the pixel shader. This however gives overall wrong result. Might it be the DirectX setup issue, here are some parts of the device initialization Set regular 32 bit surface for the back buffer. swapChainDesc.BufferDesc.Format DXGI FORMAT R8G8B8A8 UNORM ... Set up the description of the depth buffer. depthBufferDesc.Width screenWidth depthBufferDesc.Height screenHeight depthBufferDesc.MipLevels 1 depthBufferDesc.ArraySize 1 depthBufferDesc.Format DXGI FORMAT D24 UNORM S8 UINT depthBufferDesc.SampleDesc.Count 1 depthBufferDesc.SampleDesc.Quality swapChainDesc.SampleDesc.Quality depthBufferDesc.Usage D3D11 USAGE DEFAULT depthBufferDesc.BindFlags D3D11 BIND DEPTH STENCIL depthBufferDesc.CPUAccessFlags 0 depthBufferDesc.MiscFlags 0 ... Setup the raster description which will determine how and what polygons will be drawn. rasterDesc.AntialiasedLineEnable false rasterDesc.CullMode D3D11 CULL BACK rasterDesc.DepthBias 0 rasterDesc.DepthBiasClamp 0.0f rasterDesc.DepthClipEnable true rasterDesc.FillMode D3D11 FILL SOLID rasterDesc.FrontCounterClockwise false rasterDesc.MultisampleEnable false rasterDesc.ScissorEnable false rasterDesc.SlopeScaledDepthBias 0.0f What's wrong with this shader? I'm not sure what other code might be relevant, I will gladly add any at your request."} {"_id": 14, "text": "Using Jump Flooding Alghorithm for pathfinding? I am creating a distance to river texture. I am using the Jump Flood Alghorithm in a compute shader to do this using simple distance() and it works well. See code below. I want to augment this by adding blockers walls so raw distance to seed might be blocked by pixels inbetween. I need to adapt it to a more pathfinding alghorithm. Is this possible to do with JFA? Or do I need some other solution? cbuffer JFAConstants register( CBUFFER REGISTER EXTRA ) int2 gSampleOffset RWTexture2D lt uint2 gt gJumpFloodRiverMap register( UAV REGISTER 0 ) void UpdateClosest( inout int2 currentValue, int2 currentTexcoord, int2 jumpTexcoord ) int2 jumpValue gJumpFloodRiverMap jumpTexcoord if ( IsZero( jumpValue ) ) return float jumpDistance distance( (float2)currentTexcoord, (float2)jumpValue ) if ( IsZero( currentValue ) ) gJumpFloodRiverMap currentTexcoord jumpValue currentValue jumpValue return float currentDistance distance( (float2)currentTexcoord, (float2)currentValue ) if ( jumpDistance lt currentDistance ) gJumpFloodRiverMap currentTexcoord jumpValue currentValue jumpValue numthreads(TERRAIN NORMAL THREADS AXIS, TERRAIN NORMAL THREADS AXIS, 1) void cs main(uint3 groupID SV GroupID, uint3 dispatchTID SV DispatchThreadID, uint3 groupTID SV GroupThreadID, uint groupIndex SV GroupIndex) int2 texCoord dispatchTID.xy int2 currentValue gJumpFloodRiverMap texCoord int2 texCoordT texCoord int2( 0, gSampleOffset.y ) int2 texCoordTR texCoord gSampleOffset int2 texCoordR texCoord int2( gSampleOffset.x, 0 ) int2 texCoordBR texCoord int2( gSampleOffset.x, gSampleOffset.y ) int2 texCoordB texCoord int2( 0, gSampleOffset.y ) int2 texCoordBL texCoord gSampleOffset int2 texCoordL texCoord int2( gSampleOffset.x, 0 ) int2 texCoordTL texCoord int2( gSampleOffset.x, gSampleOffset.y ) UpdateClosest( currentValue, texCoord, texCoordT ) UpdateClosest( currentValue, texCoord, texCoordTR ) UpdateClosest( currentValue, texCoord, texCoordR ) UpdateClosest( currentValue, texCoord, texCoordBR ) UpdateClosest( currentValue, texCoord, texCoordB ) UpdateClosest( currentValue, texCoord, texCoordBL ) UpdateClosest( currentValue, texCoord, texCoordL ) UpdateClosest( currentValue, texCoord, texCoordTL )"} {"_id": 14, "text": "What is an efficient way to manage uniforms in a game? Most engines on the market have their drawbacks and it's difficult to find a simple light weight one that's open source and doesn't have to put you through a rather complex learning process. Writing one is a difficult task on its own, but it might not be a bad idea if what you want that engine to do is to support a specific kind of games (e.g. 2.5 D games on mobile devices). So, in search for a good game engine architecture, I've found a few logistical issues. Consider this scenario Objects Each object is comprised of two principle structures of render information a model (geometry mainly) and a material (that tells the object what textures and what shaders to use). Of course, it is natural to allow an object to switch its material definition on the fly. But a material encapsulates the shaders, so these drag along with them some slots for uniforms and vertex attributes. Since an uniform, for example, can be object specific (color, specular exponent, etc.) global superglobal (lights, weather conditions fog wind,etc.) or specific to a group of objects (they all have, let's say, a reflectivity factor) then it means that it's wrong to put them in either the object's property region or in the material's property region. It's clear that both uniforms and attributes are always declared in the shader sections of a material, but where their values come from is an enigma in the frames of a pretty general rendering engine. You have to allow for the existence of numerous types (by semnatics!) of uniforms position, colour, bone matrices, indices, lighting parameters, etc. The big question now how would you suggest to organize and manage uniforms? (especially the information flow they're declared by shaders, but their values are supplied by apparently different type of entities some renderable, some more abstract, being themselves controllers or managers)."} {"_id": 14, "text": "One Giant Shader VS Many Small Shaders I am building forward rendering engine combined with atlas shadow map technique. My goal is to build an engine that is capable of rendering similar scenes from games such as.. Doom Overwatch So I wonder, do I need to write one giant shader that does all? or do I have many different shaders for each different materials?"} {"_id": 14, "text": "Use of the xyY color space? What's the use of the xyY colorspace in games? I'm not sure what's the advantage of using it in shader programming or elsewhere."} {"_id": 14, "text": "What will happen if the argument of mix() or clamp() is above 1 or below 0? There's two magnificent intrisincs mix() in GLSL and clamp() in HLSL, which are used to implement linear interpolation. Let's say we have a variable float v ? where ? can be FLOAT MAX, FLOAT MAX and then we do gl FragColor mix(value1, value2, v) So, the question is does it works the correct way under GL or DirectX? Should I EXPLICITLY normalize the value of v like this gl FragColor mix(value1, value2, clamp(v, 0.0, 1.0))"} {"_id": 14, "text": "Make part of albedo transparent I have a shader which creates a circle inside of a plane mesh. I would like to get get rid of the parts around the circle, which are the r and b parts of the ALBEDO but I can't seem to figure out how to do it. The only thing I've managed to find is ALPHA but that changes the transparency of the entire shader and not just parts of it. shader type spatial float circle(vec2 position, float radius, float feather) return smoothstep(radius, radius feather, length(position vec2(0.5))) void fragment() ALBEDO vec3(0, circle(UV vec2(0), 0.5, 0.005), 0) Which currently looks like"} {"_id": 14, "text": "Failed to pass uniform in Metal shader modifier I'm trying to write a simple shader able to pass the color to be used for drawing in the fragment shader, through a uniform. I load the shader modifier and pass the uniform let fragmentShaderPath bundle.pathForResource(\"Cube\", ofType \"fragment\")! let fragmentShader try String(contentsOfFile fragmentShaderPath) let shaderModifiers String String SCNShaderModifierEntryPointFragment fragmentShader cube.geometry?.shaderModifiers shaderModifiers SCNTransaction.begin() cube.geometry?.setValue(NSValue(SCNVector4 SCNVector4Make(0.0,1.0,0.0,1.0)), forKey \"myColor\") SCNTransaction.commit() And this is my fragment shader modifier code include lt metal stdlib gt using namespace metal float4 myColor output.color myColor But nothing happens the object is drawn as black. If I try declaring myColor as a uniform, I get an error"} {"_id": 14, "text": "How would one construct a realistic \"infrared vision\" effect? How would you go about constructing a realistic infrared vision effect with shaders? By realistic I mean one that looks realistic, like this example. I have an idea about making a texture to determine how much heat a material emits and then determine by using the dot product of normal and view vector how much of that heat reaches the viewer but I'm not even sure that this is how thermal vision even works so I wanted to check if there's a better approach before starting to implement something that might be entirely wrong."} {"_id": 14, "text": "Strange result, when changing variable name I have no idea, what is going on. The mat4 xxx is the cause. Renaming it to \"bones\" \"bone transfromations\" etc. won't work it gives me an error. Renaming it to \"test\" works perfectly fine... This is my GLSL code version 400 core data from VBO in vec3 position in vec2 texture coordinates in vec3 normal bone data in int bone pointer in float bone intensity vertex color output out vec4 color texture coordinates out vec2 pass texcoords out vec2 texCoord0 normal out vec3 surface normal vector pointing towards the light out vec3 to light vector position, rotation, scale uniform mat4 transformationMatrix perspective projection uniform mat4 projectionMatrix TODO material color uniform vec3 in color camera viewmatrix uniform mat4 viewMatrix lights uniform vec3 lightPosition uniform vec3 lightColor skeleton data uniform mat4 xxx void main() mat4 total transform xxx transformationMatrix vec4 worldPosition worldPosition total transform (vec4(position, 1)) vec4 pos projectionMatrix viewMatrix worldPosition gl Position pos Texture pass texcoords texture coordinates light surface normal (total transform vec4(normal, 0)).xyz to light vector lightPosition worldPosition.xyz textures texCoord0 texture coordinates"} {"_id": 14, "text": "Specular intensity of non metals(plastics) in metalness pbs workflow The specular color in metalness roughness workflow is usually defined as following float3 specColor lerp(0.03f, albedoColor, metallic) The Cook Torrance BRDF is given with the following formula The final color will be Ci (diffColor (n.l) Ks specColor cook) My question is won't specular be too dim for non metals? Cook Torrance term will be multiplied by 0.03 in case of dielectrics this will make the specular component virtually non existent. This doesn't seem realistic to me, because smooth plastic reflects a lot of light, almost as much as metals What am I missing?"} {"_id": 14, "text": "Recreating this flat shaded look I'll keep it short. How does one achieve the effect depicted in the image below? Is it feasible to do in realtime? It looks deceptively simple, but it probably isn't. Are there any keywords I can search for to get more information about programming the shaders to achieve this look? Thanks."} {"_id": 14, "text": "How to determine vertex index using Shader Model 3 or lower? I need something like SV VertexId (added in Shader Model 4) in HLSL shader to determine which vertex is currently handled. Unfortunatelly, I can compile only vs 3 0 or lower. The objective is to change position of one specific vertex using HLSL. I can't edit the mesh and can't pass any data from game engine, my capabilities are limited by HLSL shader. Shader is writing only for one mesh (humain face), I need to change it's shape a bit (for example, close an eye or make it smiling). I already tried to locate vertex by TEXCOORD, but had no idea how to separate it from other triangles verticles connected to it (placed at the same point where many triangles are met). if ( VS.TC 0 gt 0.8828125 amp amp VS.TC 1 gt 0.6328125 amp amp VS.TC 1 lt 0.671875 ) Upper lip center VS.Position VS.Normal uUpLip Could you, please, give me any advice how to identify move only one specific verticle in HLSL? I need something like moving verticle in Blender's Edit Mode (wytn neighbour triangles are still connected in one point), but my attempt with TEXTCOORD makes them moving in different directions Thanks"} {"_id": 14, "text": "GLSL Editor and Debugger for MacOSX with ES2 support is there a GLSL editor for the mac? I need it for iOS OpenGLES2 shader. How do you best debug shader? Regards"} {"_id": 14, "text": "Low level GPU code and Shader Compilation Bear with me, because I will raise several questions at once. I still feel, though, that overall this can be treated as one question that may be answered succinctly. I recently dove into solidifying my understanding of the assembly language, low level memory operations, CPU structure, and program optimizations. This also sparked my interest in how higher level shading languages, GLSL and HLSL in particular, are compiled and optimized, as well as what formats they are reduced to before machine code is generated (assuming they are not converted directly into machine code). After a bit of research into this, the best resource I've found is this presentation from ATI about the compilation of and optimizations for HLSL. I also found sample ARB assembly code. This sort of addressed my original curiosity, but it raised several other questions. The assembler code in the ATI presentation seems like it contains instructions specifically targeted for the GPU, but is this merely a hypothetical example created for the purpose of conceptual understanding, or is this code really generated during shader compilation? If so, is it possible to inspect it, or even write it in place of the higher level syntax? My initial searches for an answer to the last question tell me that this may be disallowed, but I have not dug too deep yet. Also, along the same lines, are GLSL shader programs compiled into ARB assembly code before machine code is generated, and is it possible to write direct ARB assembly? Lastly, and perhaps what I am most interested in finding out are there comprehensive resources on shader compilation and low level GPU code? I have been unable to find any thus far. I ask simply because I am curious )"} {"_id": 14, "text": "Special relativity shader in GLSL I'm trying to implement a GLSL shader which helps understanding special relativity Lorentz Transformation. Let's take two axis aligned inertial observer O and O' . The observer O' is in motion w.r.t observer O with velocity v (v x,0,0). When described in terms of O' coordinates, an event P' (x',y',z',ct') has transformed coordinates (x,y,z,ct) L (x',y',z',ct') where L is a 4x4 matrix called Lorentz transformation which helps us writing the coordinates of event P' in O coordinates. (for details look http en.wikipedia.org wiki Lorentz transformation Boost in the x direction) I've wrote down a first preliminary vertex shader that apply the Lorentz transformation given the velocity to every vertex, but I can't get the transformation to work correctly. vec3 beta vec3(0.5,0.0,0.0) float b2 (beta.x beta.x beta.y beta.y beta.z beta.z ) 1E 12 float g 1.0 (sqrt(abs(1.0 b2)) 1E 12) Lorentz factor (boost) float q (g 1.0) b2 http en.wikipedia.org wiki Lorentz transformation Matrix forms vec3 tmpVertex (gl ModelViewMatrix gl Vertex).xyz float w gl Vertex.w mat4 lorentzTransformation mat4( 1.0 beta.x beta.x q , beta.x beta.y q , beta.x beta.z q , beta.x g , beta.y beta.x q , 1.0 beta.y beta.y q , beta.y beta.z q , beta.y g , beta.z beta.x q , beta.z beta.y q , 1.0 beta.z beta.z q , beta.z g , beta.x g , beta.y g , beta.z g , g ) vec4 vertex2 (lorentzTransformation) vec4(tmpVertex,1.0) gl Position gl ProjectionMatrix (vec4(vertex2.xyz,1.0) ) This shader should apply to every vertex and perform the non linear Lorentz transformation, but the transformation it performs is clearly different from what I'd expect (in this case a length contraction on x axis). Has somebody already worked on special relativity shader for 3D videogame?"} {"_id": 14, "text": "How does the GPU know how to form triangles for a given mesh? I have just begun learning shader programing. What I learned is that the rasteriser groups three vertices to form a triangle for doing further operations. If that's true how does the rasteriser determines appropriate vertices which form a triangle in the mesh geometry? Is it the 3D software which saves geometry in the proper order in model file like .3ds or .obj, .x or is it the GPU which internally triangulates the geometry irrespective of the order the vertices are passed?"} {"_id": 14, "text": "How to draw a Bezier line with shaders? I found a shader code to draw a filled Quadratic Bezier in https developer.nvidia.com gpugems GPUGems3 gpugems3 ch25.html How can I use something similar to draw a Bezier line that follows the same path?"} {"_id": 14, "text": "What is an efficient way to manage uniforms in a game? Most engines on the market have their drawbacks and it's difficult to find a simple light weight one that's open source and doesn't have to put you through a rather complex learning process. Writing one is a difficult task on its own, but it might not be a bad idea if what you want that engine to do is to support a specific kind of games (e.g. 2.5 D games on mobile devices). So, in search for a good game engine architecture, I've found a few logistical issues. Consider this scenario Objects Each object is comprised of two principle structures of render information a model (geometry mainly) and a material (that tells the object what textures and what shaders to use). Of course, it is natural to allow an object to switch its material definition on the fly. But a material encapsulates the shaders, so these drag along with them some slots for uniforms and vertex attributes. Since an uniform, for example, can be object specific (color, specular exponent, etc.) global superglobal (lights, weather conditions fog wind,etc.) or specific to a group of objects (they all have, let's say, a reflectivity factor) then it means that it's wrong to put them in either the object's property region or in the material's property region. It's clear that both uniforms and attributes are always declared in the shader sections of a material, but where their values come from is an enigma in the frames of a pretty general rendering engine. You have to allow for the existence of numerous types (by semnatics!) of uniforms position, colour, bone matrices, indices, lighting parameters, etc. The big question now how would you suggest to organize and manage uniforms? (especially the information flow they're declared by shaders, but their values are supplied by apparently different type of entities some renderable, some more abstract, being themselves controllers or managers)."} {"_id": 14, "text": "Is there a way to make the boundary between materials wavy? I have a sea trading game that I'm working on developing. Right now, my world looks like this There are 4 different \"biomes\", with more to be added. Internally, this is a large mesh which has 4 different types of materials added to it, to make it work. Each region has a material associated with it. The problem that I'm trying to overcome is to make it look less squary, I believe the process is known as bitmasking. The traditional way to do so I believe is to use images to show the boundary between each one, having one for each possible curve. That doesn't work with my current mesh architecture so far as I can tell. What I'm wondering is if there is a way to make the edges of the mesh to be curvy instead of straight lines. I assume it would have to be a shader of some kind, but my mind isn't quite figuring out the specifics of how to make it work. Any tips? Thanks!"} {"_id": 14, "text": "ShaderBytecode Compiler one technique multiple passes I have an effect code with a basic structure like technique TechniqueName pass FirstPass Profile fx 4 0 VertexShader RenderFirstVS GeometryShader null PixelShader RenderFirstPS pass SecondPass Profile fx 4 0 VetrexShader RenderSecondVS GeometryShader null PixelShader RenderSecondPS pass ThirdPass Profile fx 4 0 VertexShader RenderThirdVS GeometryShader null PixelShader RenderThirdPS Now I tried to compile this with using (BinaryReader reader new BinaryReader(stream)) CompilationResult result ShaderBytecode.Compile(reader.ReadBytes((int)stream.Length), \"fx 4 0\") if (result.HasErrors) throw new Exception(result.Message, new Exception(result.ResultCode.ToString())) Data result.Bytecode.Data stream is new MemoryStream(Encoding.Default.GetBytes(effectContent)). The Data Property (byte ) is about 1 KiB large but if I try to load it via context.InputAssembler.InputLayout new InputLayout(device, effect.Data, someElements) it crashes with following exception D3D11 ERROR ID3D11Device CreateInputLayout Input Signature in bytecode could not be parsed. Data may be corrupt or in an unrecognizable format. STATE CREATION ERROR 161 CREATEINPUTLAYOUT UNPARSEABLEINPUTSIGNATURE Any idea how I can fix this or why the error is thrown? I do not want to use multiple shaders because I reuse many parameters I do not want to reassign in a deferred shading setup."} {"_id": 14, "text": "Drawing a deferred decal when the camera clips its bounding geometry I have a building grid effect that I decal onto my terrain using a cube that moves to follow the cursor. You can see if the camera gets too close to the cube, it gets clipped by the camera's near plane See the clipping just starting here I'd like to find a solution to this as the camera may be this low to the ground or lower upwards of 50 of the time during gameplay. (the rest of the time you would use the view from above, as illustrated by the clip I provided). Is there any way to solve this problem? I'd like to correctly render the cube's shader despite while clipping with the camera. is this possible and how? . . . EDIT amp UPDATE I'm implementing camera to cubemesh clipping detection and already having issues public class Grid MonoBehaviour region Header( quot First point to Camera Controller quot ) SerializeField public CameraController CameraController MeshRenderer constructionGrid private Camera cam private void Start() cam GameObject.FindGameObjectWithTag( quot MainCamera quot ).GetComponent lt UnityEngine.Camera gt () constructionGrid GameObject.FindGameObjectWithTag( quot GridViewer quot ).GetComponent lt MeshRenderer gt () void Update() Plane frustumPlanes GeometryUtility.CalculateFrustumPlanes(cam) if (GeometryUtility.TestPlanesAABB(frustumPlanes, constructionGrid.bounds)) Debug.Log( quot Clipping quot ) else Debug.Log( quot Not quot ) This always logs quot Cliping quot whether clipping or not. If I add a meshCollider to the shadercube the same happens but the shadercube jitters all over the place. I can't figure out clipping detection."} {"_id": 14, "text": "What is the math behind the light effect in krakatoa? I'd like to know the math behind the light effect in krakatoa (click here for an example). Light source is traveling with particles, but how is shading done? Is it something simple, like Phong shading? Is it possible to implement such effect in real time on GPU?"} {"_id": 14, "text": "DirectX11 how to use textures and samplers in slots in shaders I have a system to render many objects, but I don t know how to render more tan one object with same shader, let me explain I have a sphere and a cylinder, but both objects can be rendered by different shaders, example Shader1 Shader to render object using 1 texture Shader2 Shader to render object using 2 textures Both objects need to coexist in space, so if I want to render sphere with shader 1 and I use shader1 resources context gt PSSetShaderResources(0, 1, amp texture) context gt PSSetSamplers(0, 1, amp sampler) shader2 resources context gt PSSetShaderResources(1, 1, amp texture) context gt PSSetSamplers(1, 1, amp sampler) context gt PSSetShaderResources(2, 1, amp texture) context gt PSSetSamplers(2, 1, amp sampler) in Shader1 the resources are references like this Texture2D colorTexture register(t0) SamplerState sampler register(s0) And in Shader2 the resources are references like this Texture2D colorTexture register(t1) SamplerState sampler register(s1) Texture2D colorTexture register(t2) SamplerState sampler register(s2) But what if I need to use shader1 resource s in shader2???? How to manage those resources or do I need to replicate shader2 with shader1 registers?? this is the simplest example, this is part of a very much complex system with many many shaders and many textures, but I don t know in what slot will be setted the resources, this can be absolutely generic, example, slot 5 will be used for texture 1 of shader2 It is possible to render many objects with minimal change of shaders, but the resources could be updated at any time.. I m using directX11."} {"_id": 14, "text": "How many active shaders at one frame in the game should I typically use? 5 or more like 100? How many shaders are usually active, at the same time in one scene, in modern games? I know that multiple shaders are being used, with the games switching between them in each frame, and it's common to draw objects via the shader Draw all objects with shader one Change from shader one to shader two Draw all objects with shader two Still, I know it's not as simple, especially with effects like a glow effect for whole scene, render to texture, etc., but I guess we can assume it works that way most of the time, right? The \"group by shader\" approach is good, because switching shaders is an expensive operation. From one side, you cannot have too many shaders, because you want to render the scene fast. On the other hand, you need many different shaders (or uber shader with branches quite similar) for skin, metal, water etc. How many (and which) different shaders would the theoretical, modern, third person, 3D detective game for PC (DirectX 11, if it matters) use? It would be 5, 20 or more like 100 active shaders, counting only active, at some \"frame X\"? I know it's not one number, but I wonder what scale and factors are important, in consideration for a PC game. In my sample game, I would use about 9 11 per frame (count it as different, small shaders or one uber shader doesn't matter now) Skin shader Eye shader (not too much? but they are different) Metal shader Ground shader Snow rain shader (if required) Water shader (if the water exists in scene) Glow shader (only when some special effects are involved) Light emiter shader (street lamps etc.) Standard shader (for all other, just standard shading) Standard shader with normal maps 2D shader (for GUI etc.) Is it \"much\" or \"not many\"? Did I forget about some important shaders that I would need?"} {"_id": 14, "text": "How do I mask a height based fog? I've been trying to implement a 3D (with the Y axis being utilized) fog of war system similar to what XCOM uses. There is only one hint that really seems to nail it, but I can't read the actual function that was in place. http etiennecarrier.com zombie tycoon 2 fog of war shader The key difference here is that I'm also trying to apply this to a multi leveled building. So the question is... How do you go about implementing a height based fog shader, with a masking texture to prevent it from drawing in certain world spaces."} {"_id": 14, "text": "Normal Matrix in plain English I'm into shader language with Webgl and GLSL. I've seen some tutorial about normal matrix and I don't really understand it. I mean, I think I'm ok with the math such as modelViewMatrix mat4.multiply(camera.view, modelMatrix) inverseModelViewMatrix mat4.invert(this.modelViewMatrix) normalMatrix mat3.fromMat4(inverseModelViewMatrix) normalMatrix mat3.transpose(this.normalMatrix) But why do I need it? Where can I find a case where I can see the difference between using it and not using it? Ot when do I don't need it?"} {"_id": 14, "text": "What do shaders encompass? I'm researching shaders as I'm thinking about doing them for my final year project at Uni. I've looked at a lot of examples online and I think I get it. It's something that you apply to an object or scene in order to create a desired effect without changing the original object scene, I think. I know that there are different types of shaders but that's the basic goal right? Furthermore, what do shaders encompass? Are weather systems in games shaders? Particle effects? Landslides? I don't know where the line is drawn between animations cinematics and shaders. Also I guess shaders which effect something in the game world, for example, a tower blowing up in BF4. The explosion itself would be shaders but the way the tower effects the world around it would be physics and collisions. Am I right?"} {"_id": 14, "text": "What is a Fragment Pipe? I remember someone saying \"24 fragment pipes on nVidia 7800\" in a presentation. Am I correct in saying that a fragment is the data that can generate a pixel in the frame buffer? Or are fragments the same thing as pixels? I'm getting confused here. What is a fragment pipe?"} {"_id": 14, "text": "Making a crosshatching effect in Unity Shader Graphs I'm learning Shader Graph and am trying to experiment with toon shading effects. One thing I'd love to do is make a traditional art styled crosshatching effect either inside shadows or at the edge of shadows. However, I'm lost as to how to do that. I have a sample crosshatch texture I can use as a texture2D but I'm unsure how to use this as an input in shadows and to which nodes to hook it up to. I'm very new to dabbling in shaders so I'd appreciate any tips."} {"_id": 14, "text": "PBR texture conversion Is it possible to convert from specular glossiness to metallic roughness textures for UE4?"} {"_id": 15, "text": "How to implement in app Billing in libgdx? I'm trying to implement in app Billing in libgdx game. Does someone have a working example? There is some explanation on developer.android but it's not helpful for libgdx."} {"_id": 15, "text": "Label not properly centered in TextButton I'm using LibGDX v1.1.0 and I see that the label of a TextButton is not properly centered. I have the following code m resumeButton new TextButton(\"resume\", skin) m resumeButton.addListener(new ChangeListener() public void changed(ChangeEvent event, Actor actor) m state GameState.RUNNING getGame().getWorld().pauseWorld(false) ) The default TextButtonStyle is defined as \"com.badlogic.gdx.scenes.scene2d.ui.TextButton TextButtonStyle\" \"default\" \"up\" \"menu button\", \"down\" \"menu button down\", \"checked\" \"menu button down\", \"disabled\" \"menu button disabled\", \"font\" \"font24\", \"fontColor\" \"white\" The menu button images are simple 240x48 bitmaps saved as 9 patch images. An image can be found here to illustrate the problem https www.dropbox.com s cwuhu5xb9ro5w6m screenshot001.jpg Am I doing something wrong? Or is there a problem with the button images I'm using?"} {"_id": 15, "text": "Scene2D set table cell size in percentage of tables s size Is it somehow possible to set Scene2D table cell s size in percentage of the table? I would like to have orientation independent menu, with buttons filling let s say 75 percent of the screen, and also to respond on window resizing (desktop version). I have tried several methods, for example using Value table.add(button).width(Value.percentWidth(.75F)) but when value.get(actor) is called inside cell, it is supplied with inner button actor not its container (table). I have also tried to set it in fixed fashion table.add(button).width(Value.percentWidth(.75F).get(table)) This works fine, but since I set pixel value insted of Value object it is not recalculated upon resizing. Is there any way to achieve this?"} {"_id": 15, "text": "Using the same font with different sizes in libgdx I am using BitmapFonts, LabelStyles and Labels for my texts. I want to resize some labels, so i use this. fontType.scale( .6f) LabelStyle style new LabelStyle(fontType, Color.WHITE) titleLabel new Label(\"Points\", style) titleLabel.setColor(Color.RED) titleLabel.x 260 titleLabel.y 310 but when i want to resize another label, all the labels containing that font resize (I create a new LabelStyle). So i resize the label instead of the font, but that doesnt solve the problem, because it doesnt resize the label, any idea?"} {"_id": 15, "text": "LibGDX Camera and viewport initialization in show()? I'm reading the book LibGDX game development by example and the author tends to follow a pattern like public class MyGame extends Game Override public void create() setScreen(new GameScreen(this)) ... public class GameScreen extends ScreenAdapter private Viewport viewport private Camera camera private final MyGame myGame code omitted for brevity public GameScreen(MyGame myGame) this.myGame myGame Override public void show() camera new OrthographicCamera() camera.position.set(WORLD WIDTH 2, WORLD HEIGHT 2, 0) camera.update() viewport new FitViewport(WORLD WIDTH, WORLD HEIGHT, camera) ... It seems to me that creating a new camera and viewport in the show() method is not correct, as it would create new objects every time the screen becomes active (eg when the game has multiple screen and the user can switch between them). So my questions Am I correct in my reasoning? Should the camera and the viewport be created in the GameScreen class constructor? Would it be possible advisable to have just a single camera and viewport shared by all screens?"} {"_id": 15, "text": "Box2D rotate and set position to a static body with another origin I try to rotate a static body of a PolygonShape, from another origin, and set the position regarding this new origin. Why ? Because I create bodies from TiledMapEditor object. And origins of objects in this editor are in the left upper corner. Regarding the documentation, I can set origin using the setAsBox method. But then when I set the position, the body is not where it is supposed to be. (an offset is apply between the current position and the expected position) I assume that the origin is used for the rotation, but not the position. How can I set the position from another origin, and rotating from this same origin ? (the upper left corner and not the center of the shape) My attempt val rotation 45f rotation angle (in degree) val shape PolygonShape() shape.setAsBox(rectangle.width 0.5f, half width rectangle.height 0.5f, half height Vector2(0f, rectangle.height), new origin rotation MathUtils.degreesToRadians) angle to radians val bodyDef BodyDef() bodyDef.type BodyDef.BodyType.StaticBody bodyDef.position.set(rectangle.x, rectangle.y) set the position Regards"} {"_id": 15, "text": "Box2D meters and pixels I am confused about pixels and meters in Box2D. I know that Box2D work only in mters so I need SCALING FACTOR. How big I need it? For example I want that from my mouse coordinates position X and Y for example(1527, 30) throw an Box2D object how I need to do that? if my scaling factor is private final static float PPM 1 100f so my x 152,7, y 3meters Here is my code private void setBox2DFigures() world new World(new Vector2(0, 9.81f), true) rend new Box2DDebugRenderer() cam new OrthographicCamera() Camera body new BodyDef() bodyPhysics new FixtureDef() CircleShape c new CircleShape() body.type BodyType.DynamicBody c new CircleShape() c.setRadius(20 PPM) c.setPosition(new Vector2(Gdx.input.getX() PPM, Gdx.input.getY() PPM)) bodyPhysics.shape c world.createBody(body).createFixture(bodyPhysics) and here in a draw method I want to coin position set to my mouse position public void draw() c.setPosition(new Vector2(Gdx.input.getX() PPM, Gdx.input.getY() PPM)) mouse coordinates PPM rend.render(world, cam.combined) But I don't see anything in my screen. Whats wrong? How I need to choose My scaling factor(PPM)? here's my main public class DesktopLauncher public static void main (String arg) LwjglApplicationConfiguration cfg new LwjglApplicationConfiguration() cfg.title \"Catch Me!\" cfg.width 1800 1800 cfg.height 900 900 new LwjglApplication(new Game(), cfg)"} {"_id": 15, "text": "Which is the best method implementing a background scrolling for game in libgdx? My question is very simple I am new to libgdx development, which is the best approach implementing a background that is to make the background move in y direction 1)My First approach is drawing the background image 10 times towards positive y direction using camera.translate(x,y) function to move camera from bottom to top 2)second approach is to make the camera still while making the background scroll ie drawing the background frame by frame updating the position each time Can you please suggest which is the best approach?"} {"_id": 15, "text": "How can I make my button do something when clicked? I'm trying to create a game with libGDX in Android Studio, and I am struggling with my code to add a command to the program to do something when I press the button. I have added an ImageButton, but now I struggle to get it to do something when I click on it. Here's my code bplay.addListener( new ClickListener() public void clicked(InputEvent event, float x, float y) batch.begin() batch.draw( splash, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ) batch.end() )"} {"_id": 15, "text": "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 I 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. I think I have to change the space between the cards whenever a card is removed or added but I don't know how much. This is my code CardActor cards new CardActor 14 HorizontalGroup hand new HorizontalGroup() int width Gdx.graphics.getWidth() 10 int height width 2 hand.setBounds(width 2, height 4, stage.getWidth() width, height) hand.space(width 3f) hand.align(Align.bottom Align.center) for (int i 0 i lt cards.length i ) cards i new CardActor(new Card(MathUtils.random(3), MathUtils.random(3, 10))) hand.addActor(cards i ) stage.addActor(hand) And this is the CardActor public class CardActor extends ImageButton public CardActor(Card card) super(new TextureRegionDrawable(CardTextures .getTexture(card.getType(), card.getRank()))) int width Gdx.graphics.getWidth() 10 int height width 2 getImageCell().prefSize(width, height) setBounds(getX(), getY(), getWidth(), getHeight()) addListener(new ChangeListener() Override public void changed(ChangeEvent event, Actor actor) onSelected() )"} {"_id": 15, "text": "Deploying GWT application LibGDX and TextureAtlas problem I encountered with a little problem. After GWT (and LibGDX) deployment I got an error GwtApplication exception Couldn't load image ' images objects.png', file does not exist Couldn't load image ' images objects.png', file does not exist This error throws when TextureAtlas tries to load the image from settings.text file images objects.png format RGBA8888 filter Nearest,Nearest repeat none hills rotate false xy 0, 0 size 1024, 146 orig 1024, 146 offset 0, 0 index 1 I tried to use any type of path \" assets images object.png\" \" clutchkick assets images object.png\" \" public html clutchkick assets images object.png\" and so on.. Any suggestions? By the way there are no any problems on android or desktop deployment. EDIT The same problem occurs when trying to load a Tmx map."} {"_id": 15, "text": "How do I find the shape of Tiled's circles or ellipses in libGDX? I created a level in the 'Tiled Map Editor' and loaded it into my libGDX game. I can easily transform almost all objects into Box2D objects (although this problem is not Box2D specific), but I have trouble with ellipses. Tiled seems to only create ellipse objects, without a special case for circles. I'd be happy with just circles if they existed in Tiled. However, even the EllipseMapObject I load in libGDX only has an x,y position. I don't see any information about area or vertices. Did I miss something? How can I create circle or ellipse objects in Tiled and load them into libGDX with right dimensions? Tiled version 0.10.1, libGDX version 1.4.1"} {"_id": 15, "text": "Act on Right Mouse Button click on Button I want to be able to listen for a right mouse click onto a TextButton. Is this possible without removing the default ClickListener of the TextButton? If yes, how? Or should I use a different listener?"} {"_id": 15, "text": "When should one use LibGDX's FrameBuffer and when SpriteCache? In my game I have some graphics that I want to draw once and only redraw whenever something is changed by the player. Now, I'm wondering, whether I should use the FrameBuffer or the SpriteCache class. I know that a framebuffer is much more general concept and also works for 3D, while a SpriteCache is only for 2D. However it seems to me that they would both make sense in my use case, so I'm wondering.. What are the differences, drawbacks and advantages of using one over the other?"} {"_id": 15, "text": "libgdx game not disposing My game does not exit entirely even after calling dispose() method. It loads a black screen when I launch it for the second time and works well if I kill the game manually and restart it. I get an error that says buffer not allocated with newUnsafeByteBuffer or already disposed when I try to dispose off the SpriteBatch object. This is were I suspect the problem to be. But not able to fix it entirely. Please help! Here is how I have built it (I have put the sample code here just to show you guys that there are no visible loop backs in dispose function, please correct me if I'm wrong) In game screen, public void dispose() AssetLoader.dispose() render.dispose() Gdx.app.exit() Under class AssetLoader public void dispose() Texture.dispose() sound.dispose() Under game render class public void dispose() spritebatch.dispose() throws an error when I GameScreen.dispose is called font.dispose() shaperender.dispose() I believe that my spritebatch isn't disposing which is causing the black screen but I cannot find a way to dispose it off successfully. Any help would be greatly appreciated."} {"_id": 15, "text": "LibGDX , Scale button with animation when it is pressed I am developing game using LibGDX . I want to create beautiful menu and to scale buttons when they are pressed but not in this way , when it is pressed scale it 1.5f , I want to scale it with animation . I am using imagebuttons ."} {"_id": 15, "text": "LibGDX On the \"slowness\" of loading assets Many tutorials I've seen put the loading of assets via AssetManager in a dedicated screen which displays some progress bar or image while the loading happens in background. Each \"real\" screen then gets the resources it needs from the asset manager, typically in the constructor, eg public class GameScreen extends ScreenAdapter private MyGame game private Texture t1 private Sound s1 public GameScreen(MyGame game) this.game game AssetManager am game.getAssetManager() t1 am.get(\"....\", Texture.class) s1 am.get(\"....\", Sound.class) use t1 and s1 Now another source I've seen takes this concept a bit further and also does the actual get()s in the asset loading class, so screens don't have to do them themselves, eg in the Loader class public AssetManager am new AssetManager() public Texture t1 public Sound s1 ... am.load(...) am.load(...) am.load(...) finishLoading() or update().... ... t1 am.get(...) s1 am.get(...) ... in the screen class t1 game.am.t1 s1 game.am.s1 ... use t1 and s1 Now my question is is this good practice? What's the expensive part of loading assets, the AssetManager's .load()s or also the .get()s? (I thought it was only the .load()s.) Is removing the get()s from the screens really a performance gain?"} {"_id": 15, "text": "Deleting Cleaning Screen Objects with all child objects in libGDX For my game, Im using libGDX Ashley (ECS) Box2D Ive got a lot of screens but for simplification MainMenuScreen and InGameScreen. In InGameScreen Im init the ECS (Ashley) and create a lot of entities. Some have PhysicsComponent. The PhysicsSystem will catch them and call Box2D to spawn some objects based on the parameters within the PhysicsComponents. So far so good. Now, when the player dyes, I run setScreen(new MainMenuScreen()) from my \"Main\" Class (MyGame.java). the game starts and MyGame loading at first the MainMenuScreen than the InGameScreen will get loaded (when player presses a key) than the player dyes MyGame recognized it and loading again (throu calling setScreen(...)) the MainMenuScreen When Player press key MyGame loading another round (setScreen(new InGameScreen)) I guess I have to do something like a complete clean up between switching screens. But how should I implement this? Just \"deleting\" the old InGameScreen Object shouldent be enought, right? Do I have to use the dispose() Method? Is it enough to instantiate everything new (in the init from InGameScreen) since it will instantiate all child object new for its own like Box2DWorld world new World()"} {"_id": 15, "text": "How do I scale and rotate around different points in Libgdx? I'm using a SpriteBatcher to rotate and scale a TextureRegion in libGDX. I'd like to rotate the texture around an origin outside of the region, but have the texture scaled around the region's center. As far as I'm aware, this has to be performed in one action in the SpriteBatcher.draw() method. The region is scaled to the correct size, but scaled away from the origin. I could compensate by adjusting the origin location, but is there a better method?"} {"_id": 15, "text": "Google Play Services Message Handling with Libgdx I'm looking for some idea of how to handle Reliable Messages in Google Play Services with libGDX. So far I've been using it like this I was waiting for message with OnRealTimeMessageReceivedListener, setting an outside byte array to the message received, changing a flag that suggests that new message arrived to true, getting that message in my libGDX class using methods from interface, setting newMessage flag again to false, handling message, and so again waiting for new one private OnRealTimeMessageReceivedListener mMessageRecievedHandler new OnRealTimeMessageReceivedListener() Override public void onRealTimeMessageReceived( NonNull RealTimeMessage realTimeMessage) Handle received message here byte message realTimeMessage.getMessageData() byte tbye message ByteBuffer bb ByteBuffer.wrap(tbye) if(bb.getFloat() 1884) Log.d(\"MESSAGETEST\", \"Message received in anL \" debugIntL) debugIntL byteArray message newMessageFlag true Override public boolean getNewMessageFlag() return newMessageFlag Override public byte getMessage() newMessageFlag false return byteArray Libgdx class Override public void render (float delta) ... checkForNewMessage() ... private void checkForNewMessage() if(game.customHandler.getNewMessageFlag()) handleMessage() handling message here private void handleMessage() byte message game.customHandler.getMessage() ByteBuffer bb ByteBuffer.wrap(message) float typeOfMessage bb.getFloat() if(typeOfMessage NEW UNIT MESSAGE) Gdx.app.log(\"MESSAGETEST\", \"Message received in gdx \" debugInt) debugInt ... But the result is, when uncommenting the code in OnRealTimeMessageReceivedListener and adding similar log to my handleMessage() that some messages are skipped between receiving it in listener and checking for new in my libGDX class, I don't know why, maybe because some render calls take longer to do everything inside and it skips through one check call when there's significant number of those in small amount of time On the image you can see that first log is from OnRealTimeMessageReceivedListener, which receives every message, but the second one is from handleMessage, and at 251 there it wasn't called, so handleMessage just skipped this message and went to the next one. So here's my question, what's good way to handle those messages so that I won't skip any?"} {"_id": 15, "text": "How do I scale and rotate around different points in Libgdx? I'm using a SpriteBatcher to rotate and scale a TextureRegion in libGDX. I'd like to rotate the texture around an origin outside of the region, but have the texture scaled around the region's center. As far as I'm aware, this has to be performed in one action in the SpriteBatcher.draw() method. The region is scaled to the correct size, but scaled away from the origin. I could compensate by adjusting the origin location, but is there a better method?"} {"_id": 15, "text": "TiledMap blocks makes Animation invisible Got it fixed. Thanks to anyone who tried to help me. New Code mapManager.render() spriteBatchForeground.setProjectionMatrix(Main.getGraphicsManager().getAdvCamera().getCamera().combined) spriteBatchForeground.begin() worldManager.render(delta, spriteBatchForeground) animationManager.render(spriteBatchForeground) particleEffectManager.render(delta, spriteBatchForeground) spriteBatchForeground.end() I just implemented my animations but now I discovered a problem with my TiledMap. Here some Screenshots Code for 1 spriteBatchForeground.begin() mapManager.render() spriteBatchForeground.setProjectionMatrix( Main.getGraphicsManager().getAdvCamera().getCamera().combined ) worldManager.render(delta, spriteBatchForeground) animationManager.render(spriteBatchForeground) particleEffectManager.render(delta, spriteBatchForeground) spriteBatchForeground.end() Code for 2 spriteBatchForeground.begin() mapManager.render() spriteBatchForeground.setProjectionMatrix( Main.getGraphicsManager().getAdvCamera().getCamera().combined ) worldManager.render(delta, spriteBatchForeground) animationManager.render(spriteBatchForeground) particleEffectManager.render(delta, spriteBatchForeground) spriteBatchForeground.end() Issue The animation isn't drawing when I enable the drawing for the tiledmap. I have no idea why this happens..."} {"_id": 15, "text": "Conditionally use java or android classes I'm using bezier curves in my libgdx project. I was testing the desktop version using java.awt.geom with GeneralPath but when I went to test on android, it raised an error saying that I can't import java.awt. Android have corresponding classes for GeneralPath, Point2D etc so my question is how can I use those classes in their respectives environments?"} {"_id": 15, "text": "Using Delta for a stopwatch, delta too fast than real time seconds I search for methods to create a stopwatch on libgdx and came across with this public void trigger(float delta) playTime delta playTimeRounded ((double)Math.round(playTime 100) 100) Gdx.app.log(\"deltaTime\", delta \"\") But its not accurate and its much faster. How can i create an accurate stopwatch?"} {"_id": 15, "text": "Statemachine to behaviour tree? Background I was able to convert simple statemachines like this... Into a BT looking like this (Notation describtion)... root sequence After another playAnimation name idle sequence walks? Breaks current sequence if false playAnimation name walk sequence runs? playAnimation name run Goal But how do we convert more complex multi layered animation states into a behaviour tree ? How would such a BT look like ? The difficult parts here are transistions between the different states, something i couldnt solve in an BT. Question Is it possible to convert every statemachine into a behaviour tree ? What does the theory says and how does it look like in practice ?"} {"_id": 15, "text": "Correct way of texture mapping a 2D mesh in libgdx this is a question regarding the libGDX framework. I have managed to UV map a texture to vertices (in 2D) but have come across a few problems that I think might be caused by incorrect order of vertices. In the first two pictures, you can see a rendering produced by the code bits below (without blending enabled). It seems fine at first, but you can clearly notice that the lower triangle seems to have a rough transition. Is there an easy way to prevent this (without writing too much low level stuff) or is this an expected limitation of this approach? The second problem occurs with the same code but with blending turned on. In the fragment shader, you can see that I adjust the alpha level of each pixel in the region, but with this mesh, it produces a rather weird and distorted image in the right triangle area. Here's the code Shaders Vertex shader attribute vec4 a position attribute vec4 a color attribute vec2 a texCoord0 uniform mat4 u projTrans varying vec4 v color varying vec2 v texCoords void main() v color vec4(1, 1, 1, 1) v texCoords a texCoord0 gl Position u projTrans a position Fragment shader ifdef GL ES precision mediump float endif varying vec4 v color varying vec2 v texCoords uniform sampler2D u texture void main() gl FragColor v color texture2D(u texture, v texCoords) vec4(0, 0, 0, 0.50) Mesh Mesh m new Mesh(true, 5, 0, new VertexAttribute(Usage.Position, 2, \"a position\"), x,y new VertexAttribute(Usage.TextureCoordinates,2,\"a texCoord\" 0)) u,v m.setVertices(new float 20f, 360f, 0f,0f, upper left 60f, 20f, 0f, 1f, lower left 180f,20f,1f,1f, lower right 220f, 360f, 1f, 0f, upper right 20f, 360f, 0f, 0f ) upper left (closure) Render Gdx.gl.glEnable(GL20.GL BLEND) Gdx.gl.glBlendFunc(GL20.GL SRC ALPHA, GL20.GL ONE MINUS SRC ALPHA) shaderProgram mesh.begin() shaderProgram mesh.setUniformMatrix(\"u projTrans\", camera.combined) texture.bind() m.render(shaderProgram mesh, GL20.GL TRIANGLE STRIP, 0, 5) shaderProgram mesh.end()"} {"_id": 15, "text": "LibGDX ImageButton resizeing How can I resize ImageButton ? It show very big on screen . How I know it is an Actor and it is not resizing automatically . I can t find the method for resizing it. Any ideas?"} {"_id": 15, "text": "LibGdx How to check if VSync is enabled I am just about finished my options screen, the only thing I need is some way of detecting if Vsync is enabled or not. I'm using LibGdx 1.5. I have tried to find an access to wglSwapIntervals, but haven't found one. Libgdxs API only allows a setVsync options that accepts a Boolean. If anyone could shed some light on this, it would be greatly appreciated!"} {"_id": 15, "text": "Label not properly centered in TextButton I'm using LibGDX v1.1.0 and I see that the label of a TextButton is not properly centered. I have the following code m resumeButton new TextButton(\"resume\", skin) m resumeButton.addListener(new ChangeListener() public void changed(ChangeEvent event, Actor actor) m state GameState.RUNNING getGame().getWorld().pauseWorld(false) ) The default TextButtonStyle is defined as \"com.badlogic.gdx.scenes.scene2d.ui.TextButton TextButtonStyle\" \"default\" \"up\" \"menu button\", \"down\" \"menu button down\", \"checked\" \"menu button down\", \"disabled\" \"menu button disabled\", \"font\" \"font24\", \"fontColor\" \"white\" The menu button images are simple 240x48 bitmaps saved as 9 patch images. An image can be found here to illustrate the problem https www.dropbox.com s cwuhu5xb9ro5w6m screenshot001.jpg Am I doing something wrong? Or is there a problem with the button images I'm using?"} {"_id": 15, "text": "neon effect to textures libgdx I am working on a live wallpaper with Libgdx . I am wondering if I can give neon glow to my textures , at runtime . Is this possible? If yes can anybody give me any pointers?"} {"_id": 15, "text": "How to achieve sprite reflection effect in libgdx I am currently working on an open world game similar to Pokemon using libgdx. I am currently stuck on this effect that I really want to be done before moving to other features of my game. How can I achieve the following water reflection effect? I also want it to shimmer like in this video \"Pok mon Sapphire Reflections in the water Episode 4\" 3 38"} {"_id": 15, "text": "How do I properly link an OrthographicCamera to a OrthogonalTiledMapRenderer how to properly link an OrthographicCamera to a OrthogonalTiledMapRenderer How do I properly link an OrthographicCamera to a OrthogonalTiledMapRenderer? I have tiled map i'd like render and two stages that have actors on them.. I call render.render() in my screens render method as well as stages.draw() but every i put render.setView(camera) the screen displayed flashes or does other weird things. How do I properly attach a moveable camera to a tiled map renderer? I render the map first, do game logic and then call draw on the stages. when I call translate on the camera the tiled map zooms way out for some reason? here is my render method public void render(float delta) Gdx.gl.glClearColor(1, 0, 0, 1) Gdx.gl.glBlendFunc(GL20.GL SRC ALPHA, GL20.GL ONE MINUS SRC ALPHA) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) camera.update() renderer.render() gameLogic() backStage.act() acts are called but do nothing frontStage.act() frontStage.draw() backStage.draw() here is where the camera and renderer get created public void addMap(GameMap map) this.map map maps.add(map) renderer new OrthogonalTiledMapRenderer(map.getTiledMap(), 1 20f) camera new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) float aspect Gdx.graphics.getWidth() Gdx.graphics.getHeight() camera.setToOrtho(false, 20 aspect, 20 aspect) renderer.setView(camera) frontStage new Stage() backStage new Stage() xSize map.getXSize() ySize map.getYSize() Gdx.input.setInputProcessor(this)"} {"_id": 15, "text": "LibGDX camera position shifted on movement I'm programming a game with LibGDX and Box2D and I want my camera to follow my player. But as I zoom in (because Box2Ds metric system, using camera.zoom x) the camera is shifted when the player moves (the camera follows the player) Shifted View Normal View That only happens when the player moves, so there can't be a problem with the coordinates. My Question is how to remove this shifting as the player moves. Here's some of my code Render Loop (excerpt) Override public void render(float delta) set the camera position to player's position cam.position.set(player body.getWorldCenter().x, player body.getWorldCenter().y, 0) cam.update() world.step(Gdx.graphics.getDeltaTime(), 6, 2) world.clearForces() handleInput() Gdx.gl.glClearColor(.05f, .05f, .05f, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.setProjectionMatrix(cam.combined) debugRenderer.render(world, cam.combined) Make the player move if (Gdx.input.isKeyPressed(Keys.W)) player body.setLinearVelocity(transX, transY) player.setMoving(true)"} {"_id": 15, "text": "LibGDX Shader does not work with FBO texture I have a shader and I want to run the shader on the whole rendered image at the end instead of each individual sprite that I render on screen. For this purpose I created an FBO, I render the all my images to the FBO and then I render to colorBufferTexture generated by the FBO. There is just one problem, the shader does not work when I render the FBO texture. The withoutFbo() method render the image with the shader working just fine, but the withFbo() method only renders the image without the shader. Also I know that the shader in withFbo() is working because if I try to render something other then the colorBufferTexture from the FBO the shader will work. So why isn't the shader working with the texture generated by the FBO? public class Application3 extends ApplicationAdapter float time Sprite sprite FrameBuffer fbo SpriteBatch batch Texture noiseTexture TextureRegion fboTexture ShaderProgram shaderProgram Override public void create() ShaderProgram.pedantic false batch new SpriteBatch() sprite new Sprite(new Texture(\"game.png\")) sprite.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) shaderProgram new ShaderProgram(Gdx.files.internal(Shader.GLITCH2.getVertex()), Gdx.files.internal(Shader.GLITCH2.getFragment())) noiseTexture new Texture(Gdx.files.internal(Shader.GLITCH2.getPath() \"noise.png\")) noiseTexture.bind(0) fbo new FrameBuffer(Pixmap.Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false) fboTexture new TextureRegion(fbo.getColorBufferTexture()) fboTexture.flip(false, true) Override public void render() withFbo() withoutFbo() void withoutFbo() Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) time Gdx.graphics.getDeltaTime() shaderProgram.setUniformi(\"u noise\", 0) shaderProgram.setUniformf(\"u time\", time) batch.setShader(shaderProgram) batch.begin() batch.draw(sprite, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight()) batch.setShader(null) batch.end() void withFbo() Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) time Gdx.graphics.getDeltaTime() fbo.begin() batch.begin() batch.draw(sprite, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight()) batch.end() fbo.end() shaderProgram.setUniformi(\"u noise\", 0) shaderProgram.setUniformf(\"u time\", time) batch.setShader(shaderProgram) batch.begin() batch.draw(fboTexture, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight()) batch.setShader(null) batch.end()"} {"_id": 15, "text": "How to split a screen in half using LibGDX without scaling? I am currently working on a racing game with libGDX and I need to split the screen in half for a two players mode. (Player 1 in first half and Player 2 in second half). I already have Camera1 that will follow Player 1's car, and Camera2 that will follow Player 2's car. Basically, I want the first half to show Player 1's car and the second half to show Player 2's car. I have been searching for a while online for a way to split screens with LibGDX and found how to split the screen in two with this code Left Half Gdx.gl.glViewport( 0,0,Gdx.graphics.getWidth() 2,Gdx.graphics.getHeight() ) Right Half Gdx.gl.glViewport(Gdx.graphics.getWidth() 2,0,Gdx.graphics.getWidth() 2,Gdx.graphics.getHeight() ) However, it squeezes the screen into the right half, which is not what I want. Is there a way to split the screen without squeezing it?"} {"_id": 15, "text": "Why is my texture drawn in a different place when in fullscreen? I'm trying to draw a texture (with a crescent moon) in the middle of the y axis public void draw(SpriteBatch batch) batch.draw(lune, 0, Gdx.graphics.getHeight() 2) It renders this when windowed And in full screen mode I don't understand why it doesn't work since I'm always drawing at the top of the middle in the y axis. I add a little update to what i do exactly Override public void resize(int width, int height) this.levelDatas.screenWidth width this.levelDatas.screenHeight height this.levelDatas.lune.updateSize(width, height) My render method Override public void render(float delta) Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL10.GL COLOR BUFFER BIT) this.levelDatas.batch.begin() this.background.draw(this.levelDatas.batch) this.levelDatas.lune.draw(this.levelDatas.batch) this.levelDatas.batch.end() ... And this is the updateSize and draw method for the \"Lune\" object public void updateSize(int width, int height) this.widthScreen width this.heightScreen height public void draw(SpriteBatch batch) batch.draw(new TextureRegion(lune), 0, this.heightScreen 2, 0, 0, this.lune.getWidth(), this.lune.getHeight(), 1f, 1f, 0) Still got the problem !"} {"_id": 15, "text": "Box2D fixed timestep updating is twitchy on constant FPS I'm messing around with libgdx and box2d and I'm trying to implement sidescroller movement with fixed timestep logic according to the famous Fix Your Timestep! tutorial guide. However, logic updating seems to be twitchy and I'm not exactly sure why. Here's the render method where the issue lies public void render() handleCameraInput() handleTestBodyInputImpulse() handleTestBodyInputVelocity() accumulator Math.min(Gdx.graphics.getDeltaTime(), STEP) int logicStepCount 0 while (accumulator gt STEP) world.step(STEP, VELOCITY ITERATIONS, POSITION ITERATIONS) accumulator STEP logicStepCount Gdx.graphics.setTitle(\"FPS \" Gdx.graphics.getFramesPerSecond() \", Logic steps \" logicStepCount \", Test body vel \" testBody.getLinearVelocity()) cam.update() update box2d world camera Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) renderer.render(world, cam.combined) renders box2d bodies From what I've noticed the logic while loop responsible for updating the physics sometimes doesn't execute (counter goes from 1 to 0 for one frame) and that seems to be causing the twitching. This is weird to me since delta time added to the accumulator is clamped and since the FPS is constant 60 on my machine I'd assume that the loop should always execute once. Am I doing something wrong? Is this behavior normal and is it something I am supposed to solve during rendering with interpolation? Complete minimal example can be found here on Gist and can be run on any LibGdx project with Box2d dependency."} {"_id": 15, "text": "Using Delta for a stopwatch, delta too fast than real time seconds I search for methods to create a stopwatch on libgdx and came across with this public void trigger(float delta) playTime delta playTimeRounded ((double)Math.round(playTime 100) 100) Gdx.app.log(\"deltaTime\", delta \"\") But its not accurate and its much faster. How can i create an accurate stopwatch?"} {"_id": 15, "text": "How do I manually make a .pack file like TexturePacker (without using TexturePacker)? I am using libGDX and apparently the only way I see for creating a UI is with texture packs. I would say that since a texture pack is nothing more than JSON or XML file and a large png I could manually code a texture pack. How?"} {"_id": 15, "text": "How can I create a button with an image in libGDX? I am new to LibGDX. I am trying to develop a game for Android (so it will support different screen sizes), but I don't know how to put a button with an image. I tried ImageButton but I can't resize it. I have put TextButtons in my app and it works and resizes fine too. Any suggestions ?"} {"_id": 15, "text": "How to set orthographic camera for libgdx I have implemented a basic demo of camera but it is not showing any sprites on screen. I cannot figure out what's wrong with my code. public class MyGdxGame extends ApplicationAdapter private int width, height private OrthographicCamera camera private SpriteBatch batch private Texture roboTex private Sprite roboSprite private World world private Body robot Override public void create() width Gdx.graphics.getWidth() height Gdx.graphics.getHeight() world new World(new Vector2(0, 0f), false) camera new OrthographicCamera() camera.setToOrtho(false, Constants.viewportWidth, Constants.viewportWidth (height width)) camera.update() batch new SpriteBatch() textures roboTex new Texture(\"Images robot.png\") roboSprite new Sprite(roboTex) roboSprite.setBounds(0,0,3,6) Override public void render() batch.setProjectionMatrix(camera.combined) Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.begin() roboSprite.draw(batch) batch.end() Override public void resize(int width, int height) float screenAR width (float) height camera.setToOrtho(false, Constants.viewportWidth, Constants.viewportWidth screenAR) camera.update() batch new SpriteBatch() batch.setProjectionMatrix(camera.combined) Override public void dispose() world.dispose() roboSprite.getTexture().dispose() batch.dispose() Did I missed anything??"} {"_id": 15, "text": "How to use Actors Groups with ShapeRenderer instead of Batch? I am intersted in using Actors and Groups on a Stage so that I can make components and subcomponents which draw relative to their parents, but I intend to do my drawing with a ShapeRenderer instead of a Batch. From what I understand of an Actor, the batch which is passed in to the draw() method has all of its matrices set up properly so that I can just use a coordinate system WITHIN THE PARENT to lay out the subcomponents. But it seems that this coordinate system is focused on Batches, and I want to draw using a ShapeRenderer. What do I have to do to get the child Actors to draw themselves RELATIVE TO THEIR PARENT (rather than in global coordinates) when drawing them with ShapeRenderers? Also, one other question How should I be managing begining ending the ShapeRenderer? I am currently passing in a reference to a global ShapeRenderer when I construct my parent object, and this parent object passes in references to each of its children. Should I be calling begin() end() separately in the draw method of each parent child actor? Or should I call it in my main app's draw() method, so I'm only calling it once each frame?"} {"_id": 15, "text": "How to create a Pixmap from an OrthographicCamera in LibGDX I am trying to create a picture based on what one of my OrthographicCamera can see. LibGDX has a ScreenUtils class that has a getFrameBufferPixels method, but it does not what I want as I want to get only what one camera sees, not the whole screen."} {"_id": 15, "text": "How can I check if a player drawn line follows a path? I want to draw an invisible path that the user must follow. I've stored that path as points. When a player draws a line, how can I test if it follows the path I've stored? Here's an example for tracing the letter A. if((traitSprite.getX() lt Invisible.X amp amp traitSprite.getX() gt Invisible.X )) ... (traitSprite is a sprite.)"} {"_id": 15, "text": "Player customization of entity and handling textures I'm developing a racing game where you can customize your vehicle with pre made textures and also user generated ones (players can add assets to the game). I want to know what you think is the best approach to this type of customization. Use pre packed textures and load the corresponding atlases for every single part (I think this is the easiest, but wastes memory having 3 or 4 atlas in memory and just using one texture of each). Check what the user selected and pack those textures into an atlas at runtime and use that until the user changes any part and pack it again, and so on... (more complex, less gargabe in memory). Take into account that customizable parts include wheels, spoilers, hoods, decals, exhausts and the user also has the possibility to add content. I've never implemented something like this so any help would be appreciated."} {"_id": 15, "text": "Using Box2d to model rotating turret I would like to model a rotating \"turret\" on top of a tank like object in 2D from the side view like pictured here tank with turret http uofitorn.net static images tankwithbox2dturret.png Notice the faint outline of a gun protruding to the upper left courtesy of libgdx's debug renderer (the actual gun sprite is not being rendered). How do I best implement this using Box2d? Should I use two bodies? If so, how? Or one body with two fixtures? I tried using two bodies connected by a Revolute Joint, but the turret \"gun\" does not maintain a constant angle but instead rotates down until it is vertical and then just hangs there. Or should I not model the turret aspect of the tank in box2d at all?"} {"_id": 15, "text": "LibGDX, Box2D , Destroy body into parts I am developing a game using libGDX game engine and box2d physics engine. There are asteroids in my game, I want to destroy their bodies randomly and fill with texture. How can I do it?"} {"_id": 15, "text": "What causes undefined geometry to be drawn? I am currently using the polygonSpriteBatch of libgdx to draw triangles, rectangles and a concave polygon as border. After adding the concave polygon for the colored borders everything seems to break and random geometry appears (sometimes even with a gradient). Some Examples Here you can see on the left everything looks good and after drawing the additional rectangle with its border and removing the other borders you can still see some weird red regions. This is even more extreme. On the left part of the concave polygon is drawn with a different color, and after it despawns (on the right) there is still part of it left and other triangles not created by me are drawn. I am quite confident that all convex polygons are defined in counter clockwise ordering. In the past I had trouble with providing the correct TextureRegion and it still doesn't feel like my current implementation is how it should be, but it worked for simple rectangles and triangles. Currently I have a (3px) (3px) Region and all polygon vertices are between (0f,0f) and (3f,3f). Because I define all triangles of the polygons myself the short array given to the PolygonRegion for a rectangle looks like this (0, 1, 2, 3, 4, 5) and the corresponding Vector2 polygon array like this ((0.0, 3.0), (0.0, 0.0), (3.0, 0.0), (0.0, 3.0), (3.0, 0.0), (3.0, 3.0)) I experienced even more artifacts when executing this on android and for some reason drawing a small rectangle for each vertice (for debugging) fixed some of the artifacts above. This is quite a complex problem but I hope somebody knows what could cause such a behaviour."} {"_id": 15, "text": "Using a vector to measure an angle relative to the screen camera My game is supposed to have an object that changes it sprite depending on which way the mouse faces. programming this has become a challenge, because I want to calculate the angle relative to the center of the screen using the X axis. To explain what I mean, pretend that under a sprite in the center of a screen is a protractor. I want to measure the angle that's formed between the cursor and the center. If I use the X axis as a base, I should get an angle between 180 and 180 . How would I achieve this? I've tried vector.angle(reference vector), but that doesn't seem to give the desired result."} {"_id": 15, "text": "undo touchdown in LibGDX with scene2D i'm making a game in libgdx and i have a question. I have a Button from scene2d. If there is a touchDown event on this button, i want the touchUp event only inside my button. Now if i touchDown a button, then swipe outside my button, libgdx consider this like a touchUp. I know that i can extend stage and work with it, the question is if there is a simple way to do this..."} {"_id": 16, "text": "What are some techniques used for mouse tracking, with a bit of \"emulated lag\"? I am trying to implement a system, where the cursor (in my case the player's avatar) is always about 1.5 seconds (a configurable interval) behind where the mouse actually is. If I change the cursor's location every time through, I get an emulated mouse cursor with no delay, I'm wondering if there are any pre canned type of solutions I can throw at this before I \"roll my own.\" Source code or even just basic steps you've used would be helpful."} {"_id": 16, "text": "Path finding algorithms? I posted this question on stack overflow first, but I guess no one is very interested in video games there... What are some path finding algorithms used in games of all types? (Of all types where characters move, anyway) Is Dijkstra's used a whole lot? I would think not, as it doesn't actually trace out the steps to take to get somewhere, right? If I'm understanding it right, it only determines which object is the closest. I'm not really looking to code anything just doing some research, though if you paste pseudocode or something, that would be fine (I can understand Java and C ). I'm basically looking for a quick overview of path finding in general. I know A is like THE algorithm to use in 2D games. That's great and all, but what about 2D games that are not grid based? Things like Age of Empires, or Link's Awakening. There aren't distinct square spaces to navigate to, so what do they do? What do 3D games do? I've read this thingy http www.ai blog.net archives 000152.html, which I hear is a great authority on the subject, but it doesn't really explain HOW, once the meshes are set, the path finding is done. IF A is what they use, then how is something like that done in a 3D environment? And how exactly do the splines work for rounding corners?"} {"_id": 16, "text": "Would A or Dijkstra be more proper for a grid based tactics game? In a grid based tactical game (think Fire Emblem), would A or Dijkstra be more proper for finding a path to use for enemy AI to determine the best place to move? A has a better performance that Dijkstra, however Dijkstra may offer me better smarter looking results for an AI. If possible, I'd like to have the answer for both a hexagon based grid, and a rectangle based grid, if it'll make a difference."} {"_id": 16, "text": "Overlaying grid for pathfinding My game is not grid based, so units can be at any arbitrary coordinate and move at different speeds. My obstacles are all rectangular and axis aligned, so naturally it makes sense for me to overlay a grid over the map for pathfinding. Each unit will take up a grid cell (floor(unit.x CELL SIZE), floor(unit.y CELL SIZE)). I will then run standard A grid based pathfinding on the grid. The problem is that although the path is grid aligned, the unit movement is not. Thus, in the midst of moving, the unit might end up colliding with a cell that is blocked, and get stucked. Here's a picture to illustrate I'm trying to get from point A to point B. B is the center of the grid cell, since it is a waypoint from the found path. A is the point the unit is currently at. The pathfinder thinks A to B is valid movement, since it takes the grid cell of A as the start point and the diagonal neighbour B is not blocked. But moving from A to B might result in position C, which is blocked. I thought of using a soft collision radius for pathfinding, but it has its problems. The pathfinder will not return any paths where there's a soft collision. So if the current location of the unit already has a soft collision, the unit cannot move! It seems that it is necessary to keep the pathfinding collision and physics collision identical... How do I resolve this problem, and what is the standard way to overlay a grid for pathfinding?"} {"_id": 16, "text": "Simple Stupid Funnel Algorithm (SSFA) for 3D Navigation tl dr I need an algorithm similar to SSFA except for portals with 4 vertices (or n vertices if an algorithm like that exists). I'm working on a game that requires pathfinding in 3 dimensions. By this I mean agents have full control over their position as opposed to many games where agents only control forward, back, left, right, and need to walk up stairs or ramps to go up and down. To do this I made a \"nav mesh\" using an octree that checks for collision at each region, and subdivides if there is a collision (until a certain cube size limit). So I now have a graph where each node is a cube with some size based on the octree. Using this I can run the A algorithm for pathfinding on the graph. Unfortunately, just moving towards the center of each node looks bad, and even moving towards the center of each connecting face of the node (the smaller of the two connected node's adjacent faces) looks bad. In the past, I've used the SSFA for path simplification, but it only applies to situations with an edge as a portal, not a face. Is there an algorithm for this, or is there a way to make my pathing look better? Ninja edit I'm already somewhat using steering behaviors, but since the center of nodes can vary wildly, based on the complexity of the octree, it still doesn't look nice."} {"_id": 16, "text": "Basic A star implementation tutorial Possible Duplicate Pseudo code examples of A ? Hey guys Iam making a TD game and now I am stucked in implementing A star algo. I know there are many 3d party softwares but they are difficult to understand and modify. I want to make own for my game. I need a step wise programming tutorial for implementing A OR if someone has basic snippet. I am using unity and c ."} {"_id": 16, "text": "Tiled based pathfinding in a 1 or 2 dimensional array As far as I know all tile based map editors export a JSON object containing one dimensional arrays. While most pathfinding libraries tutorials are only provided for two dimensional arrays. Also if for example I would like to do pathfinding in this one dimensional array and this array is huge i'm geussing this would cause performance issues. So why is it that most tile based map editors output a one dimensional and how should I handle those regarding pathfinding? example tile editor http elias schuett.de git Online Tile Map Editor Just google pathfinding to find all the two dimensional patfhfinding tutorials"} {"_id": 16, "text": "Restrict A pathfinding to overlapping \"safe zones\" within map I've been bashing my head against this idea for a few days without luck, I'm hoping someone sees something I don't. So I have a 2D map containing walls and obstacles, and I have a unit that navigates through it (A and funnel algorithm). So far so good. Now, for gameplay purposes, I need to limit the movement of this unit to circular safe zones that I can place on the map. Think of them like cell towers, the unit has to stay within range of at least one tower, with the max range dictated by the tower (possibly different for each tower). Effectively, imagine drawing a set of interlocking circles over the map, and the unit must remain within that. Now for the complicated part. The map is a constrained Delaunay triangulation, not a grid, so the triangles that A is using can vary in size and shape. With a grid, I could imagine limiting individual grid cells by circle distances, but in my case these triangles could be larger than any one circle. There could even be cases where the start and end points of a path are within the same triangle, but because of the network of circles, an indirect path would have to be chosen to stay within the circles. The only option I can think of involves adding these circles into the triangulation as additional edges, altering the map. This would mean rebuilding the map triangulation each time a player adds or removes these circles, and would require that I maintain a separate copy of that triangulation per player. And since these circles don't care about map walls, I'd have to alter my triangulation method to allow edge splitting and removal, to prevent overlapping lines from rendering the triangulation invalid. I feel like there has to be another way to do this. I've considered Running A purely on the circles first, then placing that intermediate path on the map and re pathing it to avoid obstacles. Finding all of the circle intersections between the start and end points, and treat those lines as portals that I must pass through, somehow altering the A pathing to prioritize passing through them. Performing a regular path search on the triangulation, but forcing a dead end whenever entering a triangle that is too far from a circle. Then refining that path to conform to the circles themselves. Each of these have issues, or scenarios where they fall apart. Has this been done before? Any input on how this might possibly be achieved would be appreciated. Edit Adding an image to show what I'm trying to accomplish. The red lines show the path that A would generate using just the map triangulation. The green lines show the desired path, taking the circle bounds into account."} {"_id": 16, "text": "Finding N shortest paths I know about several of path finding algorithms that exist depth first search, Dijkstra's algorithm, A etc. Now I would like an algorithm that gives me the N paths with lowest cost. Can this be obtained by some simple modification of one of the above? Or is a different algorithm needed, and if so which?"} {"_id": 16, "text": "How can I navigate to a target between bodies moving along fixed paths? The problem An autonomous ship starts at the outskirts of a solar system, and wants to move to a moving target, which is one of the planets. There are also many other planets moving at the same time, and these should be considered the only obstacles. I want to find the optimal path to the target. To keep it simple, the world is 2D, and the planets are moving in uniform circular motion around the sun as opposed to how planets actually behave. Also, assume the ship knows pretty much everything about the world. Most importantly, the location, speed, and orbit radius of every planet. With complete knowledge, this seems conceptually simple. For any planet and any time, you can find its location by doing some fairly simple math. But how would you apply this to pathfinding? Would it be just to pathfind in 3 dimensions x, y, and t? In theory this makes sense, but I think working that out to an actual solution would involve a lot of complications. Is it really as simple as 'setup a on a grid with x,y,t values'?"} {"_id": 16, "text": "How can I compute the shortest path in Euclidean environments with non convex polygons? Can someone suggest papers or algorithms about calculating shortest paths in Euclidean spaces with non convex polygon as obstacles?"} {"_id": 16, "text": "How should I use Monte Carlo method to simulate some police cars that keep patroling in a tile based map? I have a tile map (isometric) and I have some police cars that they patrol all the time on the map, there is some building and other cars in map too so they are considered as constraints in my shortest path algorithm (below). I use to randomly select some target for each police car and use A algorithm to find the path to the randomly selected destination tile and this cycles over and over. because cars should move all the time! (except those that gamer should control) The problem is police cars routes are correlated and they do not just traverse the area randomly, for instance, they do not usually cover a same area or they do not repeat their own route so my implementation based on some random destination point wasn t a good idea and the result was not satisfying. Take a look at the following picture, it shows how randomly selecting the destinations worked for me, obviously, it is a dumb patroling for sure, even a cockroache could do better! Suddenly, I remembered Monte Carlo Method and I thought it would solve my problem, because it exactly does what I wanted to do, However may be I should use Zobrist Hashing since it is tile base in nature. Does anyone has any idea how should I use this kind of methods? Question in Brief How can I use Zobrist Hashing or Monte Carlo method to set destinations points for my patroling car (like police car)? If anyone knows another way to implement a patrolling method, he she is very welcome to post an answer, I am not sure if Zobrist Hashing is the best and worth to implement. First Edit (added following paragraph) I need to distribute the cars and their destination points in a homogeneous manner. Every kind of solution that get me close to a good pattern could be my answer, of course there is a lot of methods to do so, but I dont have any clue."} {"_id": 16, "text": "Simple bare bones path finding routine I have a 2D grid with a number of cells. I need to find a path from one cell to another. There are no obstacles or opponents, and all cells are identical. What is a SUPER SIMPLE routine to calculate the shortest path? I have read about A and other routines, but they are waaaaaaaay overkill in my case at this point. (Maybe I will need them later, in the future.) Thanks!"} {"_id": 16, "text": "Roguelike corridor creation Connecting rooms I have a simple Tile , that I populate with Rooms. Now I need to connect the rooms with a single tile wide corridor. At first I used A to hook up the rooms but that, of course, get's the best path from tile to tile, but that's a bit boring. So I decided to roll my own path walker, which very inefficiently get's me the same paths currently as A except for some reason it never reaches the end tile. I was planning to add a randomness to it by adding a random chance to go in a random direction for a few steps before going back to it's route. public static List lt Tile gt GetPath( Room startRoom, Room endRoom, Tile , map, int drunkenStep ) Select random tile from the wall list Tile startTile startRoom.wallTiles UnityEngine.Random.Range( 0, startRoom.wallTiles.Count) Tile endTile endRoom.wallTiles UnityEngine.Random.Range( 0, endRoom.wallTiles.Count) startRoom.wallTiles.Remove( startTile ) endRoom.wallTiles.Remove( endTile ) Make it a floor tile startTile.type RoomType.FLOOR endTile.type RoomType.FLOOR startRoom.floorTiles.Add( startTile ) endRoom.floorTiles.Add( endTile) Add the start tile to the list Tile selectedTile startTile List lt Tile gt path new List lt Tile gt () path.Add( selectedTile ) List lt Tile gt tilesToCheck new List lt Tile gt () do loop four times for each adjascent tile for(int i 0 i lt 4 i ) int x selectedTile.x Convert.ToInt32( selectedTile.adj i .x ) int y selectedTile.z Convert.ToInt32( selectedTile.adj i .y ) x y because 2D map. Tile y is for height displacement Check if we are within bounds if( x lt 0 x gt map.GetLength(0) y lt 0 y gt map.GetLength(1) ) continue We cant back track through a room and only use tiles that aren't set yet if( map x,y .type RoomType.NONE (map x,y .type RoomType.FLOOR amp amp map x,y .roomId 1) ) tilesToCheck.Add( map x,y ) float minDist Mathf.Infinity Vector2 endPos new Vector2( endTile.x, endTile.z ) foreach (Tile t in tilesToCheck) float dist Vector2.Distance( new Vector2( t.x, t.z), endPos) if (dist lt minDist) selectedTile t minDist dist path.Add(selectedTile) tilesToCheck.Clear() while( selectedTile ! endTile ) return path Right now this never resolves and i'm not entirely sure why it doesnt reach the end tile. So my question is What is going wrong and what should I do to get straighter corridors and maybe some drunken randomness maybe have a path loop around a little bit Thanks for your time!"} {"_id": 16, "text": "2D Top Down Can't follow the path accurately In my game, there are many agents. Agents request a path, then after attaining a path to \"goal\" they follow the path. However player and many other things in the world can impact their position by pushing them or pulling them. When agents get pushed and they happen to advance forward closer to \"goal\", I want them to smartly follow the previously given path. I have pictures below to enhance your understanding of my situation. I COULD recalculate path every a few seconds or when agent gets out of path BUT I have DOZENS of these little agents. I don't want to do path finding for DOZENS of agents again, again, again, and again whenever they walk out of the path."} {"_id": 16, "text": "Navigation Mesh, Chunks and Funnel Algorithm I am building a little RTS like game as a side project and I am currently working on pathfinding. My approach to pathfinding is heavily inspired by things I saw in the Starcraft II map editor, which enables diagonal obstacles. My map consists of tiles that are subdivided into 4 triangles each and each triangle can be passable or not passable. I then build a navigation mesh by generating polygons (with holes) of the passable area and then triangulating them. See the following pictures for an example The colored areas are the triangulated polygons that make up the navigation mesh. As an optimization I thought it would be a good idea to subdivide the map into chunks (i.e. 32x32 grid tiles) to allow for fast updates of the mesh (as soon as a triangle changes from passable impassable I rebuild the whole chunk and update the navigation mesh accordingly). See the following picture for an example The red lines are the chunk borders (which is also why the color of the navigation mesh sometimes changes accross the borders). The triangulation is a separate constrained delaunay triangulation for each chunk. For the chunk wise updates to work I had to introduce constraints at the chunk borders for the triangles to line up. Up until now everything seemed to work fine. I then went to implement some pathfinding using A on edge midpoints and path smoothing using the Simple Stupid Funnel algorithm (see \"Efficient Triangulation Based Pathfinding\" by Demyen and Buro or How does the Simple Stupid Funnel Algorithm work?). The problem is now that some triangles have their vertices at chunk borders that don't correspond to an obstacle. If such a triangle is part of a path found by A the funnel algorithm uses it if it was a corner point of an obstacle and produces a wrong path. See the folowing picture for an example The red area is the passable area and has no obstacles inside. The green path is the path as it is found by e.g. A and the blue path is the smoothed path using the funnel algorithm. Since there is an extra vertex in the navigation mesh introduced by the the chunk borders (where the 4 chunks meet) the funnel algorithm handles it the same as if it was the corner of an obstacle and thus the path is not a straight line but takes a detour around the corner. Ultimately I wanted to implement something along the lines of \"Compromise free Pathfinding on a Navigation Mesh\" by Cui, Harabor and Grastien to find truly optimal paths in a navigation mesh. But all of those methods seem to assume that the navigation mesh contains no extra vertices except for the corners of obstacles (and the outer border of course). I am looking for a solution for the problem of splitting the map into chunks for efficient updates of the navigation mesh while still being able to find optimal paths in an efficient manner (e.g. i don't want to do real line of sight checks instead of the funnel algorithm). My only other option it seems would be an algorithm for dynamic constrained delaunay triangulations and having a single triangulation for the whole map (since this would not introduce extra obstacles) which for one is pretty complicated and second (and more importantly) doesn't scale. I know that this is a pretty open question. I hope it comes clear what I am looking for, since it was kind of difficult to phrase the problem D If anything needs clarification, please tell me D"} {"_id": 16, "text": "How to generate a navmesh from a set of 3D meshes from scratch I've found a great article on how to build a constrained delaunay triangulation that can be used to create a simple navmesh from cutout geometry. However, this does not seem sufficient to generate a high quality navmesh from any arbitrary set of level geometry from scratch. One of the problems is that it only deals with triangles in XZ space. But how should I handle situations where an arbitrary 3D mesh is intersecting another arbitrary 3D mesh? Within their intersection, each triangle would need to retriangulated in some way."} {"_id": 16, "text": "Correct way to handle A no pathing? I'm developing a little game for fun and I wrote a pathfinding system based on the A algorithm. What is the best or correct way to deal with unavailable paths? A by default will go through every node on the grid until it either finds the target node or it has exhausted all of them. This can become problematic if certain areas are cut off into \"islands\" and A tries to find a path there. The obvious solution might be to flood fill regions and check in advance, but the problem is that I plan for my world to be a bit dynamic new areas might appear, some areas which are accessable at one point might not be later, etc. Another solution I've read about is that I can limit the amount of nodes it's allowed to search before it gives up, but this sounds a bit hacky and something I'd like to avoid if possible if there are better ways, because it means that there could be a very long and complex path to the target but it'll still not find it just because of this limit. So how should I do it? I appreciate any help here, fellow devs!"} {"_id": 16, "text": "Node representations in a navigation mesh There are different ways to represent nodes in a navigation mesh. It's either along triangle centroid, along triangle vertices or along edge midpoints. As I understand if you choose triangle centroid or edge midpoints as nodes, the path isn't going to be optimal, but you can use a funnel algorithm to optimize it. If you choose triangle vertices as nodes however, I understand you can find the more optimal path from get go. But you will get a \"wall hugging\" issue. Which you can solve by using some algorithm I unfortunately forgot the name of. What is the preferred or most optimal option?"} {"_id": 16, "text": "Pointy top hexagonal A pathfinding I'm trying to create a game with a hex based map with the points at the top. I have most of it working, however the path finding is being a little awkward. The heuristic I'm using is called Euclidean I believe and is like so var dx Number destinationNode.c node.c var dy Number destinationNode.r node.r return Math.sqrt((dx dx) (dy dy)) Node is the node the unit is currently on, c is the node's column number and r is its row number. I'm using these as a simpler x and y coords. I'm trying to limit the unit to 3 hex moves in one round, so initially I thought it'd be as simple as IF returned heuristic lt 3 unit can move to that hex, however it's not working out quite like that. As you can see in the pic above, the bottom right selected hex with the \"1 9 3.162277\" is moveable to in 3 moves, however the hex with \"9 1 3.162277\" on the far right would need 4 moves to reach it. Can anyone offer any advice on how to make this work? EDIT My problem was being caused because I was using a Cartesian coordinate system and was just staggering every other Y coord. Fixed this by making the Y axis go down at a 60 degree angle. Thanks to amitp for the links that showed me what I was doing wrong."} {"_id": 16, "text": "Godot How do I asign movement cost to tiles in a Tilemap? Pathfinding I am trying to apply godot's Navigation to create a pahtfinding enemy in a Platformer game. I've read about a method to allow for pathfinding to take into account gravity. My issue is that what I know I must do is to add more movement cost to higher tiles. How do I do this? EDIT I have since found the documentation for the Astar Node. Wish me luck."} {"_id": 16, "text": "Longest path algorithm for roguelike maze generation I have a simple grid based map composed of rooms, like this (A entrance, B exit) 0 1 2 3 0 B 1 2 3 4 5 A 6 And I'm stuck trying to make a suitable algorithm to create a path of doors between the rooms, in such a way that the player has to explore most of the map before finding the exit. In other words, I'm trying to find the longest possible path from A to B. (I'm aware that this problem can be solved for acyclic graphs however, in this case there can be cycles.) EDIT Another example where rooms are connected using floodfill, and the exit is chosen as the farthest room from the entrance 0 1 2 3 0 B 1 2 3 4 A 5 6 Note that the path to the exit is not the longest possible path at all."} {"_id": 16, "text": "Path Planning in a chaotic, ever changing environment I've implemented Path Planning a few times, using A on nav meshes, and also Continuum Crowds but now I am trying to plan paths in very chaotic environments. In this environment, new routes and new blockages are created constantly, and chaotically. This is because the environment is fully destructible, and the debris can create new obstacles. In such an environment, nothing can be pre computed. What would be a good way to sense the traversability in such a world? There is no concept of a grid in my world, b.t.w, but I wonder if I should introduce an artificial one for the purpose of planning. But if navigation could be achieved without a grid, that would be much better of course. Note that the navigation is not merely dynamic in the sense that certain transitions get opened closed, but actually chaotic. This stops me from a simple approach of enabling disabling certain edges on the navigation mesh. That approach would be usable if, e.g. a gate gets locked unlocked. But in my case, in a blink of an eye, the routes could be drastically changed where simple mutations of a pre computed mesh are not doable."} {"_id": 16, "text": "Algorithm for waypoint path following? I have a worldmap, with different cities on it. The player can choose a city from a menu, or click on an available cities on the world map, and the toon should walk over there. I want him to follow a predefined path. Lets say our hero is on the city 1. He clicks on city 4. I want him to follow the path to city 2 and from there to city 4. I was handling this easily with arrow movement (left right top bottom) since its a single check. Now I'm not sure how I should do this. Should I loop threw each possible path and check which one leads me to D the fastest ... and if I do how do I avoid running in circle forever with cities 1 5 2 ?"} {"_id": 16, "text": "Delaunay triangulation. Where to start? I'm trying to learn procedural generation technique's. Specifically for dungeons. I started off with a 2D array and I generate my rooms fine. Each room contains wall tiles as seen in the screenshot below. Right now I use A to link the rooms together. But this has some paths go straight through other rooms or around rooms. Having done some googling I found this demo which game me the idea of using Delaunay Triangulation to properly connect the rooms without going through already existing connections rooms. But how to apply it to my 2D array setup? My initial thinking is that I should think out side of the box (2d array haha) and grab my rooms and create a complete graph from this and then apply the Delaunay Triangulation. I've never done anything with graphs before. So what I would to know is a) is my thinking correct in creating the graph with all the rooms linked and then to apply the triangulation and b) where should i start? small edit after some more looking around stackoverflow i found this post explaining Graphs more in depth. https stackoverflow.com questions 15306040 generate an adjacency matrix for a weighted graph"} {"_id": 16, "text": "Traversing an acyclic binary tree to construct paths from a given starting node, but the paths come out wrong The tree is an acyclic binary tree. It's composed of node objects that have a list of connections to link objects (at most 3), and link objects that have a list of connections to node objects (always 2). I am trying to construct a list of possible paths to other nodes that can be reached given a fuel budget and a fuel cost on each link. What it is supposed to do is go through each non backtracking connection of a node, and spawn a new route and thread to investigate that, leaving the current one to end at that node and thus create a list of routes to every node in the reachable area. When executed, the list of end destinations are valid but many of the paths that are constructed to get to them are wrong, going down other branches in the tree that are extraneous or entirely outside of the reachable area bounded by the fuel budget as well as jumping between nodes that aren't directly connected. There seems to be some pattern in the errors, when going down from the root of some branches of the tree the path goes down every offshoot in order first instead of going in a straight line, and when going up the tree the path tends to go further out and make triangle shapes, often landing somewhere other than the listed destination. I have already checked the link and node connections themselves to see if they are assigned properly, and they are. What am I getting wrong? Route class definition var origin Node var destination Node var totaldV float var totalt float var dVBudget float var tBudget float var tdVRatio float var links Array var nodes Array func duplicate values(originator Route) origin originator.origin destination originator.destination totaldV originator.totaldV totalt originator.totalt dVBudget originator.dVBudget tBudget originator.tBudget tdVRatio originator.tdVRatio nodes originator.nodes links originator.links func init(originator route) if originator route ! null duplicate values(originator route) Tree traversal algorithm var routes Array onready var root get node( quot .. quot ) func traverse(current node Node, previous route Route) if previous route null Starts off the recursion by providing an initial node previous route Route.new(null) previous route.origin current node previous route.nodes.append(previous route.origin) previous route.dVBudget 2000 previous route.totaldV 0 for link in current node.connections if (previous route.totaldV link.dV lt previous route.dVBudget amp amp !IsBacktracking(previous route, LinkDestination(link, current node))) If there is enough fuel and the link isn't backtracking, go through it. var working route Route Route.new(previous route) Copy the previous route to make the new route routes.append(working route) working route.destination LinkDestination(link, current node) working route.totaldV link.dV working route.totalt link.t working route.links.append(link) working route.nodes.append(working route.destination) traverse(working route.destination, working route) DisplayRoutes() root.get parent().pathSelectionFlag true UI control boolean func IsBacktracking(route Route, destinationNode Node) gt bool for nodeI in route.nodes if (destinationNode nodeI) return true return false func LinkDestination(link Node, originNode Node) gt Node Finds the node on the other side of a link for nodeI in link.connections if (nodeI ! originNode) return nodeI return originNode"} {"_id": 16, "text": "Restrict A pathfinding to overlapping \"safe zones\" within map I've been bashing my head against this idea for a few days without luck, I'm hoping someone sees something I don't. So I have a 2D map containing walls and obstacles, and I have a unit that navigates through it (A and funnel algorithm). So far so good. Now, for gameplay purposes, I need to limit the movement of this unit to circular safe zones that I can place on the map. Think of them like cell towers, the unit has to stay within range of at least one tower, with the max range dictated by the tower (possibly different for each tower). Effectively, imagine drawing a set of interlocking circles over the map, and the unit must remain within that. Now for the complicated part. The map is a constrained Delaunay triangulation, not a grid, so the triangles that A is using can vary in size and shape. With a grid, I could imagine limiting individual grid cells by circle distances, but in my case these triangles could be larger than any one circle. There could even be cases where the start and end points of a path are within the same triangle, but because of the network of circles, an indirect path would have to be chosen to stay within the circles. The only option I can think of involves adding these circles into the triangulation as additional edges, altering the map. This would mean rebuilding the map triangulation each time a player adds or removes these circles, and would require that I maintain a separate copy of that triangulation per player. And since these circles don't care about map walls, I'd have to alter my triangulation method to allow edge splitting and removal, to prevent overlapping lines from rendering the triangulation invalid. I feel like there has to be another way to do this. I've considered Running A purely on the circles first, then placing that intermediate path on the map and re pathing it to avoid obstacles. Finding all of the circle intersections between the start and end points, and treat those lines as portals that I must pass through, somehow altering the A pathing to prioritize passing through them. Performing a regular path search on the triangulation, but forcing a dead end whenever entering a triangle that is too far from a circle. Then refining that path to conform to the circles themselves. Each of these have issues, or scenarios where they fall apart. Has this been done before? Any input on how this might possibly be achieved would be appreciated. Edit Adding an image to show what I'm trying to accomplish. The red lines show the path that A would generate using just the map triangulation. The green lines show the desired path, taking the circle bounds into account."} {"_id": 16, "text": "Simple bare bones path finding routine I have a 2D grid with a number of cells. I need to find a path from one cell to another. There are no obstacles or opponents, and all cells are identical. What is a SUPER SIMPLE routine to calculate the shortest path? I have read about A and other routines, but they are waaaaaaaay overkill in my case at this point. (Maybe I will need them later, in the future.) Thanks!"} {"_id": 16, "text": "Navigation Mesh, Chunks and Funnel Algorithm I am building a little RTS like game as a side project and I am currently working on pathfinding. My approach to pathfinding is heavily inspired by things I saw in the Starcraft II map editor, which enables diagonal obstacles. My map consists of tiles that are subdivided into 4 triangles each and each triangle can be passable or not passable. I then build a navigation mesh by generating polygons (with holes) of the passable area and then triangulating them. See the following pictures for an example The colored areas are the triangulated polygons that make up the navigation mesh. As an optimization I thought it would be a good idea to subdivide the map into chunks (i.e. 32x32 grid tiles) to allow for fast updates of the mesh (as soon as a triangle changes from passable impassable I rebuild the whole chunk and update the navigation mesh accordingly). See the following picture for an example The red lines are the chunk borders (which is also why the color of the navigation mesh sometimes changes accross the borders). The triangulation is a separate constrained delaunay triangulation for each chunk. For the chunk wise updates to work I had to introduce constraints at the chunk borders for the triangles to line up. Up until now everything seemed to work fine. I then went to implement some pathfinding using A on edge midpoints and path smoothing using the Simple Stupid Funnel algorithm (see \"Efficient Triangulation Based Pathfinding\" by Demyen and Buro or How does the Simple Stupid Funnel Algorithm work?). The problem is now that some triangles have their vertices at chunk borders that don't correspond to an obstacle. If such a triangle is part of a path found by A the funnel algorithm uses it if it was a corner point of an obstacle and produces a wrong path. See the folowing picture for an example The red area is the passable area and has no obstacles inside. The green path is the path as it is found by e.g. A and the blue path is the smoothed path using the funnel algorithm. Since there is an extra vertex in the navigation mesh introduced by the the chunk borders (where the 4 chunks meet) the funnel algorithm handles it the same as if it was the corner of an obstacle and thus the path is not a straight line but takes a detour around the corner. Ultimately I wanted to implement something along the lines of \"Compromise free Pathfinding on a Navigation Mesh\" by Cui, Harabor and Grastien to find truly optimal paths in a navigation mesh. But all of those methods seem to assume that the navigation mesh contains no extra vertices except for the corners of obstacles (and the outer border of course). I am looking for a solution for the problem of splitting the map into chunks for efficient updates of the navigation mesh while still being able to find optimal paths in an efficient manner (e.g. i don't want to do real line of sight checks instead of the funnel algorithm). My only other option it seems would be an algorithm for dynamic constrained delaunay triangulations and having a single triangulation for the whole map (since this would not introduce extra obstacles) which for one is pretty complicated and second (and more importantly) doesn't scale. I know that this is a pretty open question. I hope it comes clear what I am looking for, since it was kind of difficult to phrase the problem D If anything needs clarification, please tell me D"} {"_id": 16, "text": "In A star, do I use the sum or the edge cost? When you add a new node to the closed list, you need to check all the adjacent nodes. If you find any adjacent nodes on the open list, you have to check if G would be lower if you went through the current node to get there. My questions is, when checking if the G would be lower if you went through the current node, do you add up from the last node or start from 0? Say you're using G 14 for diagonal and G 10 for horizontal. Last one on the closed list's G was 20. Your current node is one block lower from the last one on the closed list, and has an adjacent one that's on the open list with G 34. Are you supposed to check if the G would be lower if you went through your current node by doing 20 10 14 44, 44 ! lt 34. Or, are you supposed to start from 0, so 0 10 14 24, 24 lt 34? I'm pretty sure it's the latter as with the former, the number is never going to be lower. But if it's the latter, wouldn't the number be lower every single time after a certain point?"} {"_id": 16, "text": "Sample Projects Source for Navigational Meshes Anyone aware of any sample source code that contain Navigational Meshes? I'm aware of recast navigation (which is a little bit too complicated). Written in C . Preferably C but C is ok."} {"_id": 16, "text": "What is the difference between Djikstra and flow fields? I understand flow field pathfinding (as illustrated in recent Gas Powered Games titles) consists of 1) computing a vector field covering the map for a given destination, 2) deriving unit directions from their position on that field, and 3) recomputing it at each frame to take dynamic obstacles into account. I was wondering if the very same steps could be used, but by computing the vector field simply with Dijkstra. After all, if you apply Dijkstra in reverse (from the destination), and continue until you've covered the whole map, you end up with a vector field giving the best direction for each unit trying to get to that destination. If you recompute it each frame, don't you end up with the same behavior and efficiency as flow field, only without the math I don't understand?"} {"_id": 16, "text": "How to reduce the time taken to path find to an unreachable location? I have a 2048x2048 map and if I path find to an unreachable location, it makes the pathfinder go through every node on the map which freezes the thread for 4 seconds. How can I reduce that time? I'm using JPS It's a dynamic map (it changes at runtime)"} {"_id": 16, "text": "Tiled based pathfinding in a 1 or 2 dimensional array As far as I know all tile based map editors export a JSON object containing one dimensional arrays. While most pathfinding libraries tutorials are only provided for two dimensional arrays. Also if for example I would like to do pathfinding in this one dimensional array and this array is huge i'm geussing this would cause performance issues. So why is it that most tile based map editors output a one dimensional and how should I handle those regarding pathfinding? example tile editor http elias schuett.de git Online Tile Map Editor Just google pathfinding to find all the two dimensional patfhfinding tutorials"} {"_id": 16, "text": "How to handle pathfinding on a non grid non node terrain map I'm not sure if this is even path finding. All I have is a 3D map that has hills, etc. I'd like the enemy to flock an object, but also walk around other objects. These blocking objects may be added after the path is calculated, which would cause a re calculation of the path. What algorithm am I looking at here?"} {"_id": 16, "text": "Pathfinding to Get In Attack Range with \"Transparent\" Tiles Currently I'm using A and a raycasting algorithm to determine the path an entity (Player) should take to get close enough to the enemy (Enemy). The player has an attack range (it's illustrated around the enemy to show how close the player has to get to the enemy in order to attack it). This works pretty well, but as soon as I add tiles that prevent entities from moving from them, but allows them to attack through them (imagine a river). Using my current implementation the player entity takes the purple route to attack the entity, but I want it to take the yellow path. I came up with the following, but this is highly inefficient Mark the tiles around the enemy (cyan circle), which are in line of sight to the enemy (raycasting) as possible destinations Run the pathfinding algorithm to find which one of those destinations is the closest to the player I know A is good for finding a single destination and Dijkstra is better for multiple destinations, but since I already got this working with A I wanted to know if it's possible to achieve this is an efficient manner. Side question how are the tiles where you cannot walk through, but can shoot through called in the industry? I know the wall likes entities are mostly called \"solids\"."} {"_id": 16, "text": "Voxel river flow simulation I am making a Voxel game and I'd like to add rivers that can be redirected. So I thought that if a player replaces a river block or digs up a block next to a river block the river would repath itself to the sea. The rivers path would have a direction and a speed in that direction. The rivers path would be determined by these rules If the river can go down in its direction it will and then pick up speed. or if it has a speed under 2 and it can go sideways and down it will and keep its direction. Otherwise it will keep going in its direction until blocked, where it will pick a new direction. If the river can't go anywhere it will fill up the layer its on like a bathtub and go up. Repeat until it reaches the ocean. However I can't figure out how you can know what to fill. The data would be stored in some sort of height map. 1 same level, 0 down a level, 2 up a level For example 222222 211112 211112 211112 211112 222222 I can tell that the 2s completely surround the 1s meaning that all the 1s should get filled with water if the river goes up. But how can a computer tell?"} {"_id": 16, "text": "Pathfinding and collision avoidance on mobile Currently I'm developing a Diablo like game for mobile platform(iphone5 ). A simple A search will find the path, but collision avoidance still needs to be taken into consideration. There will be about 50 monsters active at the same time, so performance is very important. I found some methods that might work. NavMesh RVO The recast detour library works well on the pathfinding part, but its crowd simulation quickly reach the limit(more than 5ms for 30 agents). Another library RVO2 seems fine(less than 2ms for 50 agents), but the library has some license issues. Flow Fields Physics Engine Many RTS games use this method, but it seems that a physics engine is required to resolve collisions. If many agents don't share a common goal, this method might cost more than traditional A pathfinding. Steering Behaviors Physics Engine Steering Behaviors includes many concepts, I think simple avoidance behavior might work(just turn left right if there is something in front) , but the method still requires a physics engine to work together. I'm still not sure which one to use, maybe there exists other pathfinding and collision avoidance methods. P.S. Halo Spartan Strike uses Havok AI(based on RVO?), but I didn't see many enemies in that game, so I wonder whether the first method(NavMesh RVO) will works well on mobile platform."} {"_id": 16, "text": "Can A path finding cost functions allow for path following shapes? Recently I begun developing a game prototype which could create procedural generated dungeons using a collection of room types. To ensure the hallway paths between these rooms would always be connected I implemented a A path finding algorithm following along the tile map of randomly placed rooms. The problem with doing this however is I was not necessarily trying to find the shortest path between rooms which in most cases would be a diagonal. Since being thematically a 'dungeon' I wanted them to twist and turn at 90 degree angles. By using a Manhattan distance for the heuristic I managed to get the intended shape but I've ended up with one final problem which I come to you kind people to help me with ). Though now using 90 degree angles to move the path, its saves doing the run till the end of path(See picture below). This makes the whole thing at a distance feel cramped in places instead of using all the space effectively. Seeing how simply changing the heuristic from distance to Manhattan distance has made a difference my question is, is there a cost function I could implement that would give the desired results of this non conventional path? Any answers would be appreciated, thank you. Note The algorithm also has access to the normal direction of the start and end goals."} {"_id": 16, "text": "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? And another question, I have element with stepSize (concretely called movementSpeed), and getPosition().getX(), getPosition().getY() AND getRadius() which returns the radius of a circle. How would you do A algorithm with radius? Btw I am implementing it in Java, so maybe some Java snippet would be helpful. EDIT As 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"} {"_id": 16, "text": "Dynamic obstacles avoidance in navigation mesh system I've built my path finding system with unreal engine, somehow the path finding part works just fine while i can't find a proper way to solve dynamic obstacles avoidance problem. My characters are walking allover the map and collide with each other while they moving. I try to steering them when collision occurs, but this doesn't work well. For example, two characters block on the road while the third one's path is right in the middle of them and he'll get stuck. Can someone tell me the most popular way of doing dynamic avoidance? Thanks a lot."} {"_id": 16, "text": "A in 2D game. corner pathfinding issue the issue I'm having will be best described with pictures more so than with code, so lets have a look if you will. So all the mobs followed the player and started attacking him, but as soon as 4 spots to the E, S, W, N were taken, mobs 1 and 2 are no longer able to find the path. When mob from E S W N spot dies they can of course find a way to the player. My question therefore is what is the way to implement this so that mobs can get to the player when only corners are free? Diagonal movement is not allowed and i'm using Euclidean distance. I've read this How do I avoid pathfinding characters getting stuck in corners? and other questions, but they dont quite cover what I need here. I'm sorry if this isnt specific enough, happy to clarify."} {"_id": 16, "text": "Ponderate dijkstra relative to previous position I use dijkstra in my rust game to find path to a destination. My game is in a square grid like this There is, for illustration, the Rust code which use dijkstra use crate map Map use crate physics GridPoint use pathfinding prelude dijkstra pub fn find path(map amp Map, from amp GridPoint, to amp GridPoint) gt Option lt Vec lt GridPoint gt gt match dijkstra(from, p map.successors(p), p p to) None gt None, Some(path) gt Some(path.0), ... pub fn successors( amp self, from amp GridPoint) gt Vec lt (GridPoint, i32) gt let mut successors vec! for (mod x, mod y) in ( 1, 1), (0, 1), (1, 1), ( 1, 0), (0, 0), (1, 0), ( 1, 1), (0, 1), (1, 1), .iter() let new x from.x mod x let new y from.y mod y if new x lt 0 new y lt 0 continue if let Some(next tile) self.terrain.tiles.get( amp (new x as u32, new y as u32)) successors.push((GridPoint new(new x, new y), next tile.pedestrian cost)) successors ... And visualization of found path (white is found path, pink is goal) The found path is not a direct line. I'm not surprised, because the weight of diagonal is the same as lateral. With what I understand with dijkstra is I can return successor with weight for a coordinate. But I can't increase weight of diagonal lateral according to previous position (ex comming from West gt moving to Est will be less weight maybe it is not the solution ...). How can I achieve that ? With another algorithm than dijkstra ?"} {"_id": 16, "text": "Pathfinding with car steering Is there pathfinding algorithm which takes car steering into account? I have large space where user can place cars (trucks actually) and other blocker objects. Objects can be placed vertically or horizontally oriented and have different sizes (may be 3x6 or 2x4 or other size). User needs to be able to select new location for any car then I need to calculate how can that car move to selected location. I have pathfinding working, and I can find paths with different size but only for square objects. Update Pathfinding need to give only path that is possible with that type of car. For example on empty map with only one car, if user selects new location right next to its current location, car can't strafe or turn in place it has to either reverse and steer or do U turn or something. Also it must ensure that car orientation at end is what user requested."} {"_id": 16, "text": "Find shortest path (quickly) on the surface of a 3d model? Imagine this scenario we 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). Now 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). What 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). We 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? But this is not terribly fast. Any advice about that is appreciated."} {"_id": 16, "text": "Pathfinding with different sized units I am actually working on a general purpose pathfinding library (find it here), mostly oriented for grid based maps. I was looking for ways to integrate support for pathfinding with units of different sizes. Actually, I am working with the assumption that all units are square (i.e. their widths and heights in tile units are the same). In researching, I came across a very comprehensive article about Annotated A star, using True clearance values for pathfinding. I tried it, and succeeded in implementing it, and got it working with a wide range of search algorithms (A star, Theta , Dijkstra, DFS, Breadth first search and Jump Point Search). There are some small details of implementation I think I am still missing. First of all, when an agent is 2x2 sized (i.e it occupies 4 tiles on the grid map), what tile can be assumed to be the agent position ? On the same page, clearance based pathfinding will fail in some cases. Let's consider the following map, where 0's are passable tiles, 1's are obstacles and x's matches walkable goal to be reached. Let's assume we are pathing with a 2x2 sized unit 00000000 00111100 001xx100 001xx100 00000000 For targets on the left (tiles 4,3 and 4,4), clearance value is 2, for both. No problem here. But for the others (tiles 5,3 and 5,4), clearance value is 1. So depending on how the agent position is taken, pathfinding will fail while obviously, for each of these target, the agent can properly fit into the dead end space. Another scenario, with the same 2x2 sized agent 0000000x 0000000x 0000000x 0000000x xxxxxxxx Well, all tiles are walkable here, no obstacles. We want the object to reach any goal on the rightmost or bottom most border. Each of these targets have a clearance of 1, so annotated pathfinding wil obviously fail here...depending on how the agent's position is taken. How do I work around this issue?"} {"_id": 16, "text": "Obstacle avoidance in Bezier Curves I use an A algorithm to find a path voiding obstacles. On obtaining the path it would be a good idea to reduce the number of points. Then I would like to typically do a spline interpolation or Bezier Curves to find a smooth path but is it not possible that post smoothening my character bumps into an obstacle? If not possible then why and if it is possible, then how do I avoid it?"} {"_id": 16, "text": "A path finding for road network data structure to represent directivity I have been reading A path finding to apply on a road like network structure. Most of the code I saw is about A on tile based maps. There is a short description at Amit's page here about what I am looking for. My question is about what data structure should I use to define a road network map. I have infromation like, node, cost,etc. But not sure how to represent both one directional and bidirectional roads. In a graph structure, can I mix directed and undirected edges or use two edges to represent that a segment of road can be traversed in both direction. Any good example available? Thank you so much."} {"_id": 16, "text": "Pathfinding towards a moving target in 2D Platformer I have an enemy in my 2D platformer that chases the player around the level. I implemented a modified version of A that works with gravity as described here https gamedevelopment.tutsplus.com tutorials how to adapt a pathfinding to a 2d grid based platformer theory cms 24662 But for a moving target I would have to calculate a new path whenever the target moves. Of course I'm going to run the pathfinding on a separate thread and only once a second or something like that, but it's still a waste to calculate the path from scratch. So I found this algorithm for transforming the old path to the new path with the new start and target position called FRA http idm lab.org bib abstracts papers ijcai09b.pdf However the platformer version of A has a kind of 3D grid where nodes with different jump values in the same 2D location has a different z coordinate. Is it possible to use FRA when jump values comes into play? Do I have to recalculate jump values?"} {"_id": 16, "text": "Which algorithm for controlling cars on a race track? I think A is a good place to start, but since cars cannot move in all directions (they move like cars do, trying to move forward and steer), I was wondering if someone could point me at other approaches they've used. Also, I was wondering about the \"Racing Line\". Should one just precompute the optimal paths, and then use the A to select the path that isn't blocked by other cars ? EDIT My question is different from Driver AI in racing game because that question is about approaches. I am interested in learning about specific tried and trusted algorithms like A ."} {"_id": 17, "text": "MMO In App vs. Website Purchase Im currently writing a turn based start game, which will be played in an MMO style (players download clients, central server handling the game logic etc.) and now I need to decide how I charge my players for playing my game, since this will have some implications on how player account handling is going to work. After looking a bit around, I found two alternative ways of doing this a) Classical in app purchase, for which my clients need to be able to take the payment info, send them to my server which then charges the selected amount (using some API like stripe.com) and provides the selected services b) Account administration and payment via website, and then synchronization between website and game server over some database Most MMO games I know use the website approach (b) although I assume that in app purchase (a) is faster and easier for my players and will therefore yield higher conversion rates. So, my question is Are there some major problems (security, paperwork) or drawbacks (complicated to implement) with in app purchase I overlooked? Im not doing a mobile game (full desktop) and Im from europe, just in case this information might be needed."} {"_id": 17, "text": "Strategy City Builder browser game technical details I actually have multiple questions into one. Hopefully someone can hit all of them. I wanted to give a try at a massively multiplayer web based game. Basically, the game would have similarities to Evony, or Eve Online (a much scaled down version). The idea is it would be a mostly real time city builder (like Evony) that allows complex actions between players (like Eve Online but without the graphics and much scaled down). It would sort of be like a database game. I want it to be able to support around 500 people simultaneously online off one server. However, I have multiple issues that I want to pin down before I actually start writing the code. Continuous database updating The database has to be continuously updated on a small time interval to reflect the passage of time in the game verse. Furthermore, the effects of all actions will have to be calculated as well. Right now I'm thinking about using mysql with events using the innoDB engine to do this. Is there a better faster approach to this? Continuous graphical updating Certain details (such as \"time till completion\" etc when building something) need to be continuously updated on the user interface. I'm thinking about having each page in the user interface continuously make ajax calls for the information. Again, is there a better faster way? Thanks"} {"_id": 17, "text": "Browser based MMOs (WebGL, WebSocket) Do you think it is technically possible to write a fully fledged 3D MMO client with Browser JavaScript WebGL for graphics, and WebSocket for Networking? Do you think future MMOs (and games generally) will be written with WebGL? Does today's JavaScript performance allow this? Let's say your development team was you as a developer, and another model creator (artist). Would you use a library like SceneJS for the game, or write straight WebGL? If you would use a library, but not SceneJS, please specify which. UPDATE (September 2012) RuneScape, which is a very popular 3D browser based MMORPG that used Java Applets so far has announced that it will use HTML5 for their client (source). Java (left) and HTML5 (right) UPDATE (June 2013) I have wrriten a prototype of a WebGL WebSocket based MMO https github.com alongubkin xylose"} {"_id": 17, "text": "MMO Server monster handling Dabbling with basic MMO code because it intrigues me. How does the server handle monsters mobs? I understand that generally on each game tick, the server loops through each player to send them updated positions of each other nearby player or mob. So every player loop you're also looping through every other player but is it just standard to loop through the entire mob list too? I mean there could be 1000 mobs idling around the game world zone. Would this just slow the loops down? I thought maybe they keep a seperate list of ACTIVE mobs, ones that are either near a player or are chasing a player, but that would still require looping the idle ones to check if a moving player comes near one. Unless the aggro loop is less frequent (thinking out loud here).. Is there some tricks or common workarounds involved? Or is that just how they work?"} {"_id": 17, "text": "Alternatives to storing all my entities in an SQL database I've been trying to build my entity system based on pure SQL data storage as explained in this post series. The idea is that every entity or component is stored in an SQL table. I created my framework to manage that, only to realize that many SQL queries took more than 10ms, which is unsuitable for use in a game loop. I first thought the delay was I O bound, so I created an in memory MySQL cluster. This was better, but still not real time enough for a game loop. Has anyone built an SQL based entity system? If so, how did you manage to keep query times manageable? If an SQL database isn't feasible for performance issues, what data structure could I use to retain the entity system idea and the possibilities of direct SQL requests on components? I've heard of many MMOs running on SQL. Do they use it for only part of the data or a full entity system? How to separate database stored and classical memory stored structures in that case? Edit for clarification Yes, all game data is stored in the database. If say I run my physics system it will first get data from SQL, then do its stuff, then insert the updated data back to the database."} {"_id": 17, "text": "Level loading philosophy in MMO games I've been working on project for quite a while, and I've returned to dilemma about level loading. The problem is i trust the client with it's local level loading, when it's done loading it tells the server to join it to server room data stream and server start to send data. My current setup Client logs in, on login server sends the characters. Client chooses the character and start to load level locally. When client scene done loading, it request to add to room. Client receives the data he needs. I fear that user could hack the client and actually load other scene, that would result in players and characters going through props and models, it could also be an exploit to see hidden data and items. Instead, after server sends the chosen character it could \"wait\" for user to send response that level has finished loading. After that, server joins the character to room and send data to the user. That way client doesn't know anything about rooms or it's names. Any suggestions?"} {"_id": 17, "text": "How to update the monsters in my MMO server using Node.js and Socket.IO Currently I am creating an MMO using Node.js and Socket.IO. The node server needs to handle connections for players, and also use a loop to update all monsters positions in my game and let them attack players in range. For the loop I read that you can use process.nextTick or use a child process, which option would be the best choice? What are the advantages disadvantages of using each? Also, how many times per second should I run this loop for the monsters?"} {"_id": 17, "text": "Preventing item duplication? For my game, there's two types of items stackable, and nonstackable. Nonstackable items get assigned a unique ID that stays with it forever. A character ID is assosicated with the item, as is a state (CHANGED, UNCHANGED, NEW, REMOVED). The character ID and state is used for item saving purposes. Stackable items have one unique ID, as in the entire stack has one unique ID. For example 5 Potions (stacked ontop of each other) has one unique ID. When dropping a nonstackable item, the state gets set to REMOVED, and the unique ID and state don't change. If picked up by another player, the state gets set to NEW, and the character ID gets changed to the new character's ID. When dropping all items in a stack of stackable items (for example, 5 potions out of 5) it behaves just like a nonstackable item. When dropping some of a stack of stackable items (for example, 3 potions out of 5)... I really have no clue what to do. The 3 dropped potions have the state of REMOVED, but the same unique ID and character ID. If another player picks it up, it has no choice but to obtain a new unique ID, and its state gets changed to NEW and its character ID to the new one. If the dropping player picks it back up, they'd just be readded to the stack. There's two issues with that though. 1. If the player who dropped the 3 potions picks it back up, there's no way to tell if they legitimately dropped the items, or if they're duped items. 2. If another player picks up the 3 potions (assuming they're duped), there's no way to know if they're duped or not. My question is How can I create a system that detects duplicated items for both nonstackable and stackable items?"} {"_id": 17, "text": "Why are so many games not fully voiced? I'm wondering why so many MMOs are only partially voiced? I asked makers of games (Thimbleweed Park, in their Q amp A) how expensive voiceover is, and they said it wasn't especially expensive unless you hire A list stars. So why would so much game dialogue be only present as text to be read onscreen? The only reason I can think of is the same that exists for localization in all software You can't record VO until all the dialogue is finished and frozen, so it is another fixed delay between finishing the rest of the game and shipping. So it doesn't seem like it's not manageable. To be clear I'm not looking for opinions or theories (that would only make the mods close this question) but actual reasons and experiences from people who have shipped games with partial voiceover."} {"_id": 17, "text": "MMORPG Representing Money in a DB table Where to begin... I'm currently busy with a few Udemy courses on game development using Unreal Engine 4. My end goal is to develop an MMORPG that I've always wanted to play, but never found online. Q How would I represent in game money in a database table? I've thought of adding it as a field in the \"character\" table, but then I struggle to see how I can implement it as a field in the \"bank\" table... Bank already has a quantity field, so I though about adding the money values as \"items\", but I just can't get myself to approve that... Some information on the table fields Each players bank will have a size limit (upgrade able) on how many items they can place in it. I was thinking of moving it out to the \"character\" table as it doesn't really have anything to do with the bank table... As for the rest of the tables, I'm still working on them. For now I just wanted to get the communities opinion on how to represent money in an mmorpg database."} {"_id": 17, "text": "Why does editing the client's memory in some MMOs allow them to cheat? Why editing the memory of the game client works? Why so many \"Hack protection\" tools coming with the clients? If I were to design a client server game, everything would happen at the server (the simulation of the game world) and clients would be only passive consumers receiving status updates of the part of the world near their characters, sending only some information like keystrokes or move action commands. Maybe I missing something here, but with that design, any hack like raising my STR by 200 in the client memory (if the value is present at all), just won't have any effect. The only explanation I can think is that games in which memory editing works let parts of the simulation run in the client and the server then just synchronize all the clients periodically. I can understand that design for Real Time Strategy games with a fixed number of players once a match is configured, but, why in MMORPGs? Is it a strategy to reduce server load?"} {"_id": 17, "text": "Appropriate MMORPG battle system for Android oriented MMORPG? I need a tip for a game I'm making. Because of many issues I want to make a 2D mmorpg A 2D game is easier to code (I'm using ActionScript3 Starling). I can more likely find preexistent graphics, and handling them is easier. Fundamentally I don't want to eat the device's memory!! Common devices here have at most 1GB RAM memory. But when I think about battle systems, I imagine stuff like Argentum Online and Tibia. Those battle systems were OK on mouse keyboard based systems. AO's battle system will be really hard to use (specially by any spellcaster class) in devices like Samsung S3 mini. OTOH when I think in systems like Pokemon or Golden Sun, both of them being turn based, I ask myself about the interation battles would be locked (they have a protocol, you cannot suddenly leave a fight, you can take as long as you want in each turn,...) which is not acceptable in a mmorpg for many reason (mmorpg users do not expect a protocol, they expect to leave a fight as they'd like, they would HATE users who suddenly go AFK on the middle of a battle without having opportunity to act). What battle interaction would be a good balance between mobile device friendliness and not being a pain in the ass for game dynamics? Suggestions are accepted here (we cannot expect game design have absolute decisions at all)."} {"_id": 17, "text": "Should I assign a unique ID to individual units of game currency? I am currently making a MMORPG. At the moment, I am working on the currency part of the game but I'm confused whether I should assign a unique serial number for every unit of the currency generated. I'm hoping to use this system to trace any misuse of the virtual currency but is this a common practice and if not, would this be a good idea on operational and or performance point of view?"} {"_id": 17, "text": "Is it a legal thing to do to sell fabricated accounts of your game? For example, say I create an online mass multiplayer game with in game purchasing system and with randomness factors as well (the point is that game accounts have actual value and there is a somehow proportional relationship with playing time plus the luck of the player and the account's value) and the game appears to become popular. Is it legal to, for example, insert cheated accounts into the database (without even spend a second of legitimate playing) and sell those accounts with extremely high price?"} {"_id": 17, "text": "MMORPG Representing Money in a DB table Where to begin... I'm currently busy with a few Udemy courses on game development using Unreal Engine 4. My end goal is to develop an MMORPG that I've always wanted to play, but never found online. Q How would I represent in game money in a database table? I've thought of adding it as a field in the \"character\" table, but then I struggle to see how I can implement it as a field in the \"bank\" table... Bank already has a quantity field, so I though about adding the money values as \"items\", but I just can't get myself to approve that... Some information on the table fields Each players bank will have a size limit (upgrade able) on how many items they can place in it. I was thinking of moving it out to the \"character\" table as it doesn't really have anything to do with the bank table... As for the rest of the tables, I'm still working on them. For now I just wanted to get the communities opinion on how to represent money in an mmorpg database."} {"_id": 17, "text": "How do we attract more developers and other Volunteers to our Open Source MMO Emulation Project? I am on a small development team that is tasked with completing the server side programming for an Open Source MMO project that has been in progress for about 5 years now. Approximately a year ago we Open Sourced the project hoping to draw in new developers, this was without much success and in fact we haven't gained even one active developer in our project. The Project Star Wars Galaxies A New Hope, is something near and dear to myself and the other few people working on the project. It is a quest to bring back one of the golden eras in gaming, Patch 14.1 for Star Wars galaxies. The progress as of this summer was extremely slow and it seemed as if we were taking two steps forward and one back every change we made. The codebase wasn't designed very well and we looked into completely rewriting it from scratch. After a couple of weeks we realized this couldn't be done in a timely manner and perhaps we should take another look at the old core to see if we couldn't revive it. We found it was worth just revamping the old core and continuing to push forward, we've made some really good changes that will help with the future of development. One reason we didn't really want to push heavy developer recruiting was the state of the existing codebase. Now that it is somewhat cleaned up, how do we go about recruiting quality individuals that are interested in finishing up this Open Source MMO project and delivering what we promised to the community? Github Project"} {"_id": 17, "text": "What legal matters do I need to consider when releasing an MMO? Let's say I've finished programming an indie MMO game similiar to Tibia. I've got a stable server application ready to launch a tested, bug free, working client application ready to play the game's official website (ready to host), with a payment system and freely downloadable game client. No matter how impossible it sounds, let's also assume none of these break copyright laws. My game divides accounts into free and premium groups. Premium accounts can access all game features, requiring server authorisation to work properly. Let's say that the \"premium account\" can be bought on the website for a fixed monthly rate. Free accounts can play for free, but with limited access. This is what the mentioned payment system will be for. If I've correctly understood, this is the freemium model. I'm completely novice to business entity issues, so in short what steps, in legal terms, do I have to take from here so my game can legally earn me money? For example, is there something like verification that the game gives the user what it actually offers when paying on its website? If relevant, I live in Europe."} {"_id": 17, "text": "game state update structure and distribution in MMO? I'm developing an MMO, which has to maintain a global game state. Now I want to distribute the updates, which the players make to this state, to players which can see those updates (area of interest etc.) Is there a common structure format for these updates and for a global game state? Like, every action a player sends to the server has to include a type, the coordinates etc. And are the updates, which gets distributed from the server to the players in the same format or are they different? Also should I include timestamps or use the receive time from the server to check which action came first and which sencond etc.? And what should I send back to the player if he send an invalid action?"} {"_id": 17, "text": "Bandwidth cost hour for one MMORPG player I am trying to calculate guesstimate the costs of running an MMORPG for a client. And now I need a pretty accurate estimate for the monthly bandwidth cost so I can calculate the possible revenue of the investor client. So what is a pretty reasonable bandwidth cost for each player per hour? The MMORPG I'm trying to make is a virtual conference with gamification. We can go to booths, see other people, make a transaction in the booths. And we will also have a quest and mini game system for the gamification. We will be making it using Unity Forge. We were thinking of using Photon before, but when I reached out to them, they said I need to subscribe for Photon Industries since it's not a game, per se, which is like 2.5x the cost of PUN. We will split the server into two the game server and the REST API server. I'm in charge of the game side of the project so the REST API and backend is not my jurisdiction. I this is the specs of the game that I had in mind The event will be held for 10 days, possibly running 24 hours straight. Max customer that we have anticipated is around 1000 2000 CCU There will be multiple scenes rooms that the customer can go to (e.g. Commerce area, Lobby area, Mini Game area, etc) The quest system, booth transactions, and other features that doesn't need real time update will be handled by the backend. So that leaves these data that needed to be synced Player position 4 bytes 3 (X, Y , Z) 12 bytes currentScene 1 byte avatarModel 4 bytes (will use bitmasking to handle the current type of clothing and accessories of the player model) playerAction 4 bytes (player's enumerated action type) playerActionTarget 4 bytes (player's action's target) Scene sceneStatus 16 bytes (any status of the current scene e.g. the current quest. Still unsure how many bytes I need to sync) So, this is what I have calculated so far using AWS EC2 (possibly wrong)"} {"_id": 17, "text": "How can I synchronize state in my Asteroids game with many networked players? Wondering how state synchronization works in games with lots of players like MMOs. It seems like a hard problem to solve and I am not aware if there are standard solutions. Specifically, synchronizing game clients (users playing game) with an array of centralized servers, and then broadcasting and merging the state with all the same connected clients. How it is done (and how efficiencies are implemented) typically, and what the structure of the game state is like. To simplify this question, I am thinking in terms of a simple asteroids game You have n number of players, and the asteroids, players, and bullets are synchronized across clients. I am not familiar with how the game state should be modeled (if it's some quadtree thing you are sending around, or just a vector of patch updates, etc.). There could be players all over the world, so latency is a factor."} {"_id": 17, "text": "What kind of databases are usually used in an MMORPG? Do people write their own DB for some reason?"} {"_id": 17, "text": "What languages are used to develop MMORPGs like EVE Online and WOW? As I understand it, MMORPGs are games that run on your computer like any other normal 3d video game but, with each action that happens with in the game, changes are made to the universe via HTTP calls to the server. So the players computer does all the heavy lifting in terms of rendering the graphics and animations but, web frameworks do the online communication. So I am wondering what web frameworks, web servers and databases are being used to create MMORPGs like EVE Online and W.O.W.? Also, what programming languages and 3d game engines are being used to make the client side (3d graphics animation sounds) part of the game?"} {"_id": 17, "text": "How should chat be transmitted and stored in an MMO? Players in MMO games can usually send messages over different channels (private, public, guilds, et cetera). How would I transmit and store this data so as to prevent outside users from being able to access somebody's private chat messages? Should I store the data in a temporary game log, or a database?"} {"_id": 17, "text": "Is it a legal thing to do to sell fabricated accounts of your game? For example, say I create an online mass multiplayer game with in game purchasing system and with randomness factors as well (the point is that game accounts have actual value and there is a somehow proportional relationship with playing time plus the luck of the player and the account's value) and the game appears to become popular. Is it legal to, for example, insert cheated accounts into the database (without even spend a second of legitimate playing) and sell those accounts with extremely high price?"} {"_id": 17, "text": "How do I create a big multiplayer world in UDK? I want to create a big multiplayer world in UDK and I'm having a few difficulties. I created the biggest terrain possible but then any terrain related action I do takes forever. However, I've seen videos of people make same size terrain and working without a problem. My pc is strong enough, so maybe someone can tell me what I'm doing wrong. I want to make it even bigger then the biggest terrain size, so I was thinking of doing level streaming but then I read that streaming is working server side which means if I have a player on every terrain all terrains will still be loaded and I want to save as much memory possible so it will work well online. Thanks for any help you can give."} {"_id": 17, "text": "Code reuse for a CRPG data model on the server side I'm working on a turn based game with CRPG (Computer RPG) elements in HTML5. It has to support 10K CCUs (Concurrently Connected Users). The CRPG elements in the game are item and character systems The game has characters, characters have items. Items may be worn or used as consumables. Items may be crafted and upgraded. Characters gain experience and get new levels. Characters and items have characteristics (like health, attack strength etc.). Characters may have buffs and debuffs placed on them that affects characteristics. Characters have talents that acts like permanent buffs or debuffs. Items worn and consumables used may affect character characteristics. Characters may strike each other, and strike outcome is calculated based on the effective characteristics of the attacker and target. All of the above has to be stored and handled on the server side. To avoid developing everything from scratch for the 100th time, I'd like to maximize my reuse of existing code original, free, or commercial. I can adapt the CRPG model requirements to the implementation limitations to a certain (considerable) extent. Technology stack does not matter much either as long as it is reasonably scalable. How can I author my server side solution to maximize code reuse?"} {"_id": 17, "text": "How many database connection should use in a MMO game server? Game server links to database, how many database connection should use? The data update works like this update role object to database every X minutes, commit all updates every Y minutes. There are 3 ways Only one database connection One worker thread one database connection and set transaction level to \"Read Uncommitted\". Worker thread loop all roles in it to do update amp commit periodically One game session one database connection and set transaction level to \"Read Uncommitted\". A dedicated thread to loop all connections to do update amp commit periodically Method 1 has a problem which database connection object needs shared by multiple worker threads, for JDBC, connection class is thread safe, but I don't know what about C such as MySql driver. If it have to use mutex to make thread safe, there will be a performance degrade all worker threads have to synchronize their data frequently. Method 2 has a problem to update old data. One map in game server run in dedicated worker thread. For example, role A in map 1 which compute by thread 1. role A transport to map 2 which compute by thread 2. This might cause thread 1's commit call after thread 2's commit call, so the older update which already executed in thread 1 commit after thread 2's commit. Method 3 seems is a waste of system resource. Because in MMO there is no need to be transaction isolation, any change in a game session should be immediately seen by other sessions. In contrast with web app, so many connections has litte meaning. However the \"Read Uncommitted\" isolation level can let other session read data which has not committed yet. I forget there is a thing called connection pool. Generally it is thread safe implemented so I do not need to care synchronization problem anymore. And the connection number is dynamic so I can leave problem of how many connection number to it. Only I do is get a connection from it. So, method 1 amp 3 both practical."} {"_id": 17, "text": "Best approach to develop a mobile version of existing browser mmo game? our team has developed a MMO browser game (HTML5, Javascript amp PHP). The game is similar to Empire GG, Clash of Kings, Game of War etc. We want to develop a mobile version and the question is which would be the most efficient way process we can take advantage of?"} {"_id": 17, "text": "How to implement server side auto attack? I'm writing a basic MMORPG and im trying to implement auto attack. At client side I send an AutoAttackMessage to the server. Should I send this message every X ms to the server, or juste one time and then server handle this himself ? How to handle delay between 2 auto attack at server side ? (timer, special thread)..."} {"_id": 17, "text": "Why would an online MMO throttle actions per day? I started playing Die2Nite and was surprised that it has such a strict limit on the number of actions per day. After a while, I figured it was just part of the charm. I also started playing Magic Duel and it has a similar mechanic that limits the amount of actions per day. Is there a game design principle behind a decision to limit actions per day in an MMO?"} {"_id": 17, "text": "List of Anti Cheat Packages for MMOs? i would like to start this topic for programs to counter attack link text. I am not aware of a big list but with everyone's help i hope to make this a fine topic. Posting format NAME nProtect GameGuard GAME TYPE any type of game Website http global.nprotect.com product gg.php FEATURES? Protect the users' PC from fast evolving hacking technologies and viruses. Real time protection, diagnose various patterns latest hacking tools that can harm games, but also memory debugging prevention technology will be applied, completely blocking hacking tools through real time hacking tool monitoring and blocking function. Blocks hacking attacks through memory scan Blocks online outflow of personal information"} {"_id": 17, "text": "How do you design a record replay system for a frequently changing game? I'm working in a free MMORPG and I have a problem. I'm (with other people) developing a video recording system for the game. The idea is basically we record all the packages sent amp received with timestamps, plus some local data from the client, and then dump it in a file. For playing the video, we just emulate everything that's on the file. We also have an option to export the video to avi with ffmpeg. The problem is when we change between versions of the game, it is hard to maintain backwards compatibility for the video (commands added removed, function changes, etc). Is there a good way to handle this problem? instead of having a bunch of different players and choose the right one for each version of the video file? It would be helpful to know how does other games handle this situation. Thanks for the help, sorry for my english."} {"_id": 17, "text": "How to make sure user is running the newest version of mmo client? In typical mmorpg game, you have a launcher and a client. You first run the launcher to update the client, then you run the client. In every mmo I tried if you run a client without updating first (if update is available), it automatically closes and (usually) starts launcher. My question is, how can you check if user has the proper version of client? I though about server asking client about its md5 however it's so easy to cheat. I think that there is no safe way of handling it yet every mmorpg I know uses such a system. So how do mmorpg games handle this problem? To make sure that the client is at the newest version?"} {"_id": 17, "text": "How is load balancing achieved in MMOs? I believe it's a common requirement of MMOs that processing for a single shard or realm can be done over several servers to ease the load. I'm curious as to how this can be done whilst maintaining a unified consistent world where all the players, and all the NPCs can interact. My question is how is load balancing achieved in MMOs? Any links, books or general information on how to improve my knowledge on this subject is also appreciated."} {"_id": 17, "text": "Store temporary state in DB or not Background I'm trying to implement a little MMORPG. I'm planning to use Cassandra DB for the database. Question I don't really understand which data should be store in DB and which one should be just kept in memory. For example the friend list. Friend list will be stored in DB, but what about connected disconnected friends ? Should I keep in memory all connected account and access it directly ? Or should I store this information in the DB (therefore writing reading quite often for something that could be kept in the memory) ?"} {"_id": 17, "text": "Is there a way to make a dynamic world such as a MMORPG horizontally scalable? Imagine a open world of 500 players with data changing as fast as 20 updates player second. Last time I worked in a similar MMORPG, it used SQL, so obvioulsy it couldn't query the DB all the time. Instead, it loaded all players from the DB to memory as C objects and used them. That is, it scaled vertically. Would it be possible to make that server horizontally scalable instead? Is there a database designed to support that amount of updates concurrently?"} {"_id": 17, "text": "What are some alternative options for saving level data for a game like Hurtworld? For a multiplayer building crafting game like Hurtworld (where the player can build structures on the map), what are some alternative options or example data structures for saving the world data on the server? Level data including Grid of squares that foundations can be built on, with a flag to indicate whether the square is empty or already has a foundation Walls etc which have been built on the foundations, and multiple floors above Windows doors which can be built on window frames door frames Furniture machines which can be placed on foundations floors Other dynamic world data such as trees, animals, chests with items, etc I feel like it's too much data to store in a database. Am I wrong? If it can be stored in a database, how can I get my head around the data structure I would need to set up? Is there some simplified example? Can each square in the world grid be represented by 1 row in the database? And should there be a new row for each structure built on a square, with that row referencing the square structure that it was built on?"} {"_id": 17, "text": "List of Anti Cheat Packages for MMOs? i would like to start this topic for programs to counter attack link text. I am not aware of a big list but with everyone's help i hope to make this a fine topic. Posting format NAME nProtect GameGuard GAME TYPE any type of game Website http global.nprotect.com product gg.php FEATURES? Protect the users' PC from fast evolving hacking technologies and viruses. Real time protection, diagnose various patterns latest hacking tools that can harm games, but also memory debugging prevention technology will be applied, completely blocking hacking tools through real time hacking tool monitoring and blocking function. Blocks hacking attacks through memory scan Blocks online outflow of personal information"} {"_id": 17, "text": "How many database connection should use in a MMO game server? Game server links to database, how many database connection should use? The data update works like this update role object to database every X minutes, commit all updates every Y minutes. There are 3 ways Only one database connection One worker thread one database connection and set transaction level to \"Read Uncommitted\". Worker thread loop all roles in it to do update amp commit periodically One game session one database connection and set transaction level to \"Read Uncommitted\". A dedicated thread to loop all connections to do update amp commit periodically Method 1 has a problem which database connection object needs shared by multiple worker threads, for JDBC, connection class is thread safe, but I don't know what about C such as MySql driver. If it have to use mutex to make thread safe, there will be a performance degrade all worker threads have to synchronize their data frequently. Method 2 has a problem to update old data. One map in game server run in dedicated worker thread. For example, role A in map 1 which compute by thread 1. role A transport to map 2 which compute by thread 2. This might cause thread 1's commit call after thread 2's commit call, so the older update which already executed in thread 1 commit after thread 2's commit. Method 3 seems is a waste of system resource. Because in MMO there is no need to be transaction isolation, any change in a game session should be immediately seen by other sessions. In contrast with web app, so many connections has litte meaning. However the \"Read Uncommitted\" isolation level can let other session read data which has not committed yet. I forget there is a thing called connection pool. Generally it is thread safe implemented so I do not need to care synchronization problem anymore. And the connection number is dynamic so I can leave problem of how many connection number to it. Only I do is get a connection from it. So, method 1 amp 3 both practical."} {"_id": 17, "text": "game state update structure and distribution in MMO? I'm developing an MMO, which has to maintain a global game state. Now I want to distribute the updates, which the players make to this state, to players which can see those updates (area of interest etc.) Is there a common structure format for these updates and for a global game state? Like, every action a player sends to the server has to include a type, the coordinates etc. And are the updates, which gets distributed from the server to the players in the same format or are they different? Also should I include timestamps or use the receive time from the server to check which action came first and which sencond etc.? And what should I send back to the player if he send an invalid action?"} {"_id": 17, "text": "Should I keep login server apart from game server? I'm thinking of making a MMO server, and I've been looking at how other games structure their network. One of the things I've noticed is that there's always a Login server and then the game server(s). I'm still deciding if I should do this, but I would like to hear some opinions first. What are the advantages of this, and how does the login server communicates with game server to handle logins?"} {"_id": 17, "text": "List of Anti Cheat Packages for MMOs? i would like to start this topic for programs to counter attack link text. I am not aware of a big list but with everyone's help i hope to make this a fine topic. Posting format NAME nProtect GameGuard GAME TYPE any type of game Website http global.nprotect.com product gg.php FEATURES? Protect the users' PC from fast evolving hacking technologies and viruses. Real time protection, diagnose various patterns latest hacking tools that can harm games, but also memory debugging prevention technology will be applied, completely blocking hacking tools through real time hacking tool monitoring and blocking function. Blocks hacking attacks through memory scan Blocks online outflow of personal information"} {"_id": 17, "text": "is it possible to make a MMO starting with scalable hosting? I made a really basic 2D RPG. I want to know whether I can turn it into a free to play MMO. I cannot afford to rent a server with enough capacity to serve a big number of players but I'm wondering whether I could get a hosting plan that starts cheap but scales enough to eventually handle a big numer of users so I have minimum fixed costs and I can cover expenses on the go with ads or whatever. Is there such a thing? Thanks"} {"_id": 17, "text": "Why are so many games not fully voiced? I'm wondering why so many MMOs are only partially voiced? I asked makers of games (Thimbleweed Park, in their Q amp A) how expensive voiceover is, and they said it wasn't especially expensive unless you hire A list stars. So why would so much game dialogue be only present as text to be read onscreen? The only reason I can think of is the same that exists for localization in all software You can't record VO until all the dialogue is finished and frozen, so it is another fixed delay between finishing the rest of the game and shipping. So it doesn't seem like it's not manageable. To be clear I'm not looking for opinions or theories (that would only make the mods close this question) but actual reasons and experiences from people who have shipped games with partial voiceover."} {"_id": 17, "text": "Fair monetization of a MMO with a simulated economy I am in the design phase of a MMO game based around flying age of sail airships. Players will be able to captain their own ship (owned by their in game nation or faction or themselves if they become sufficiently wealthy), or play as a crewmember on their own or another ship in battle , or as ground defence personnel when their own ship becomes too boring. The players might also design or redesign the flying sailing ships (and later, as technology progresses, flying steam or diesel ships), and test new ship design, or plan ground defences. All of this would be based around a simulated economy, where resources are produced, shipped and either consumed or lost to make value added foods, commodities, communities or vessels. In a war, commerce raiding should eventually have an impact as much as direct military action against enemy troops and vessels. Players could be merchants, pirates, smugglers, privateers, naval captains, or just another member of a ship's crew. Players could also design airships and ground defences, and contribute to the governance of their province. So, for all of this, how can I monetize this game? I need to consider startup capital, but more importantly, it needs to make a profit. However... I don't want to fall into the ways of many games with micro transactions. That means no pay to win a paying player must have only their own skills and equipment to help them win against a free to play player... if I go with that method. The economy is simulated, and I would like the method of monetization to have a minimal impact on that, but not necessarily no impact. Players must know exactly what they are spending their in game currency upon, an must be able to sell for in game or possibly even real currency any 'physical' game object with a cut to the broker (i.e. the developer). I have considered an up front cost, but that alone does not guarantee an income stream as the player base becomes saturated. I have considered instant IAP of objects that would otherwise take time to produce the player buys them from the developer's nation. I have considered allowing a certain amount of free screen time per month, extendable by a purchase. What methods would guarantee continual income for a number of years at least, without unduly upsetting players who may be wary of traps such as loot chests or pay to win? Can a game such as this be funded prior to the commencement of development?"} {"_id": 17, "text": "what is the most popular mmorpg game that has an out of game api? World of Warcraft is off the table, because of the \"WOW Glider Lawsuit\" of 2008. Also see Where is Blizzards official World of Warcraft API? Eve Online has an API But, what is the MOST popular (in terms of usership) MMO Game that does allow programmers to develop out of game things (like an Android app)."} {"_id": 17, "text": "How is load balancing achieved in MMOs? I believe it's a common requirement of MMOs that processing for a single shard or realm can be done over several servers to ease the load. I'm curious as to how this can be done whilst maintaining a unified consistent world where all the players, and all the NPCs can interact. My question is how is load balancing achieved in MMOs? Any links, books or general information on how to improve my knowledge on this subject is also appreciated."} {"_id": 17, "text": "Low traffic client synchronization with server in MMO I am implementing MMO where player flies in space on his starship controlling it with arrow keys and cooperate with other players. I want to implement it so that player will be able to dodge his ship from rocket or something else, so I am trying to predict whole game state on client side using the same world simulating algorithm as server use. That game world is written on C and will be called within client directly (it's written on Unity3D) and through CLR on C server (under Linux). Connection through UDP. Problem is how to maintain, for example, 1000 players within single map (exclusing all other game objects, mobs...) Let's say I will synchronize server with clients 50 times per second send to each client states of just that game objects (and players) which he is able to see (within some radius) have to send 100 objects to each player within his view radius must send averagely 50 bytes per game object (it's id, x,y coords, rotation, state...) so, it will need to have such network bandwidth 1000 (clients) 50 (times per second) 100 (objects to send to each player) 50 (bytes per object) 250 000 000 bytes per second! It's impossible! Is it possible to reduce this value somehow? For example let clients to fully simulate their game worlds (for a long period of time) and send them just inputs of other clients and synchronize game worlds, let's say, each several seconds but it will cause weird desynchronization issues at leash because of float computations. Anyway, how such games are programmed in common way? Thank you."} {"_id": 17, "text": "Integer vs String for \"type\" data in data driven games I've been developing a few mobile games, in which those games fetch their data from a server database. I'm used to storing \"type\" values as an integer identifier, and an enum in the client to identify the data coming from the server. I'm under the impression that games like MMOs or PC games that get patches model their data to identify \"types\" as integers. As an example On the database table Monsters Table MonsterId(int), Name(string), MonsterType(int) On the client sided code typedef enum MonsterTypeGround 1, MonsterTypeAquatic 2, MonsterTypeAmphibious 3, MonsterTypeAerial 4 MonsterType Is there an objectively correct answer on what to use (int vs string) for these types of data? Do I have the correct impression that MMO's usually use integers for this, or it highly depends on the developers as well?"} {"_id": 17, "text": "How to implement server side auto attack? I'm writing a basic MMORPG and im trying to implement auto attack. At client side I send an AutoAttackMessage to the server. Should I send this message every X ms to the server, or juste one time and then server handle this himself ? How to handle delay between 2 auto attack at server side ? (timer, special thread)..."} {"_id": 18, "text": "What is the best way to check for intersection of two bounding boxes, given a minimum and maximum Vector3 for each one I have a BoundingBox object which holds two Vector3's (x, y, z), one for the minimum point and one for the maximum point. ( 1.5 0 9 1.5 3 10) What is the best way to check for any intersection or overlap of two BoundingBoxes? The test for intersection will happen more often than not when there are no points actually intersecting, just faces. The code that I currently am using is bb1.max .x gt bb2.min .x amp amp bb1.min .x lt bb2.max .x amp amp bb1.max .y gt bb2.min .y amp amp bb1.min .y lt bb2.max .y amp amp bb1.max .z gt bb2.min .z amp amp bb1.min .z lt bb2.max .z However this leads to problems when points are, for example 1.5 0 9 1.5 3 10 intersecting with 0.5 0 8.5 0.5 1.8 10.5... The Z minimum and maximum points for the second object laying entirely outside of the Z min and max for the first object."} {"_id": 18, "text": "Am I implimenting a sweep and prune broadphase correctly? The code that I am using is std vector lt PhysicsBody gt physicsChildren containing all objects ... std sort(physicsChildren.begin(), physicsChildren.end(), sortByLeft) std vector lt PhysicsBody gt activeList unsigned int one unsigned int two for(one 0 one lt physicsChildren.size() one) activeList.push back(physicsChildren one ) for(two 0 two lt activeList.size() two) if (physicsChildren one gt m position.x physicsChildren one gt m radius gt activeList two gt m position.x activeList two gt m radius) CheckIntersectionBetween(physicsChildren one , activeList two ) else activeList.pop back() I think something is wrong because for 800 objects 309169 calls to CheckIntersectionBetween. A bruteforce would use 640000 calls, I didn't think this was much improvement (considering only objects close in the x axis should test). I wrote the code from reading Jitter Physics article about SAP Create a new temporary list called activeList . You begin on the left of your axisList, adding the first item to the activeList. Now you have a look at the next item in the axisList and compare it with all items currently in the activeList (at the moment just one) If the new item s left is greater then the current activeList item right, then remove the activeList item from the activeList otherwise report a possible collision between the new axisList item and the current activeList item. Add the new item itself to the activeList and continue with the next item in the axisList. What have I done wrong?"} {"_id": 18, "text": "Pygame collision detection less frequent when objects are increased I currently experiencing an issue in pygame where whenever i increase the number of objects e.g. platforms, rocks for a in range(150) rock Rock(0,0) OR incresing the range which they spawn in rock.rect.x random.randrange( 200,30000) rock.rect.y random.randrange(80,500) rock list.add(rock) all sprites list.add(rock) LINE 232 (which i really need to do for an ENDLESS mode) collision detection between the player and all the objects that have have been changed will become less frequent, so the character will just go through th objects as they weren't even there... you can see the character fall through the objects, it falls through in front of the object and not behind. All game code is below, I have tried a number of different techniques and values but I have found that these numbers and ranges work best. Collision Detection code FOR PLATFORM medium collide pygame.sprite.spritecollide(player, medium list, False) if medium collide player.rect.y 2 FOR ROCK rock collide pygame.sprite.spritecollide(player, rock list, True) if rock collide lives 1 if rock collide player.rect.y 100 player.rect.x 50 !!!!!GAME CODE BELOW!!!!! GAME CODE"} {"_id": 18, "text": "physics.addBody() with custom shapes in Corona SDK Does the physics.addBody() only work with Circles and Rectangles? Or is it possible to physics.addBody() on vector shapes or sprites or with masks or something?"} {"_id": 18, "text": "How do I detect the intersection of a curve with itself? I'm developing a game in which the player can draw a line. I want to detect if that line intersects with itself. How would I do this?"} {"_id": 18, "text": "How can I determine the direction of the balls after collision in billiards game? I'm making a billiard game and I have two questions How do I find the velocity of two balls when they collide with each other and how do I apply it to both balls? I already know the angles that they're gonna move, I just need to find the velocity that they'll move in those directions. My game is in 3D, and I'm using Unity. I don't want to use Unity's built in physics to compute the result in this case, I'd like to know how to compute it myself."} {"_id": 18, "text": "Weird issue in collision resolution of non static bodies I'm a bit of a beginner in engine development, so I decided to write my own engine from scratch so I could learn more about what happens under everything. I've been progressing fairly well, except the physics engine side of things have been giving me a bit of a headache. Here's a gif of what I mean Essentially, the engine works just fine as long as the player is not colliding with another non static body from either above, or from right to left. Here's my collision resolution code written in go package resources import ( \"game pidgeot socket ecs\" \"github.com bxcodec saint\" ) type PhysicsSystem struct Hub Hub func (system PhysicsSystem) Loop() entities, err system.Hub.World.AllEntitiesWithComponent(ecs.CollisionComponent) if err ! nil return for e, range entities apply impulse c p, system.Hub.World.GetComponent(e, ecs.CollisionComponent) c ( c p).( ecs.Collision) p p, system.Hub.World.GetComponent(e, ecs.PositionComponent) p ( p p).( ecs.Position) if c.WithGravity Add gravity c.ImpulseY saint.Min(c.ImpulseY 1, c.MaxSpeedY) apply impulse p.NextY p.Y c.ImpulseY p.NextX p.X c.ImpulseX resolving collisions for e1, range entities c1 p, system.Hub.World.GetComponent(e1, ecs.CollisionComponent) c1 ( c1 p).( ecs.Collision) if c1.IsStatic continue for e2, range entities if e1 e2 continue system.ResolveCollision(entities, e1, e2) moving entities for e, range entities p p, system.Hub.World.GetComponent(e, ecs.PositionComponent) p ( p p).( ecs.Position) if (p.X ! p.NextX p.Y ! p.NextY) p.X p.NextX p.Y p.NextY system.Hub.broadcast lt system.Hub.World.GetComponentMessage(e, p p) func (system PhysicsSystem) ResolveCollision(entities map ecs.EID ecs.Component, e1 ecs.EID, e2 ecs.EID) c1 p, system.Hub.World.GetComponent(e1, ecs.CollisionComponent) p1 p, system.Hub.World.GetComponent(e1, ecs.PositionComponent) c1 ( c1 p).( ecs.Collision) p1 ( p1 p).( ecs.Position) c2 p, system.Hub.World.GetComponent(e2, ecs.CollisionComponent) p2 p, system.Hub.World.GetComponent(e2, ecs.PositionComponent) c2 ( c2 p).( ecs.Collision) p2 ( p2 p).( ecs.Position) resolve y axis collidingX IsOverlapping(p1.X, p1.X c1.W, p2.X, p2.X c2.W) collidingY IsOverlapping(p1.NextY, p1.NextY c1.H, p2.NextY, p2.NextY c2.H) colliding collidingX amp amp collidingY if colliding direction func (impulse int) int if impulse lt 0 return 1 else return 1 (c1.ImpulseY) overlap CalculateOverlap(p1.NextY, p1.NextY c1.H, p2.NextY, p2.NextY c2.H) p1.NextY (direction overlap) c1.ImpulseY 0 c1.IsJumping false resolve x axis collidingX IsOverlapping(p1.NextX, p1.NextX c1.W, p2.NextX, p2.NextX c2.W) collidingY IsOverlapping(p1.Y, p1.Y c1.H, p2.Y, p2.Y c2.H) colliding collidingX amp amp collidingY if colliding direction func (impulse int) int if impulse lt 0 return 1 else return 1 (c1.ImpulseX) overlap CalculateOverlap(p1.NextX, p1.NextX c1.W, p2.NextX, p2.NextX c2.W) p1.NextX (direction overlap) for e3, range entities if e1 e3 continue c3 p, system.Hub.World.GetComponent(e3, ecs.CollisionComponent) p3 p, system.Hub.World.GetComponent(e3, ecs.PositionComponent) c3 ( c3 p).( ecs.Collision) p3 ( p3 p).( ecs.Position) collidingX IsOverlapping(p1.NextX, p1.NextX c1.W, p3.NextX, p3.NextX c3.W) collidingY IsOverlapping(p1.NextY, p1.NextY c1.H, p3.NextY, p3.NextY c3.H) colliding collidingX amp amp collidingY if colliding system.ResolveCollision(entities, e1, e3) Anything I could do to solve that issue?"} {"_id": 18, "text": "Libgdx collision detection and response I am trying to create a simple platformer game with libgdx. I implemented a collision detection for the player's bounding box with the map's tiles using the Rectangle.overlaps method. In response I am trying to find out at what edge the player hits the tile and then react accordingly. Somehow it happens that when the player collides on the X axis, the response of a collision on the Y axes happens (player gets moved to the top of the tile). I was looking into the SAT (Seperating Axis Theorem), but I don't feel like it's applicable here, since I am not trying to draw any line betwen the Rectangles. In fact, since Rectangle.overlaps() is used I am only reacting to a collision already happening. Here the source private void resolveCollision() setUpPlayerRec(allObjects.get(0)) for (Rectangle r2 tiles) if (!playerRec.overlaps(r2)) continue else onCollisionWithTile(r2) private void onCollisionWithTile(Rectangle r2) Gdx.app.log(\"Collision Detected\", \"Player collided with tile\") float diff if (playerRec.x playerRec.width lt r2.x) LEFT EDGE OF TILE controlledPlayer.getPosition().x (r2.x playerRec.width) controlledPlayer.getVelocity().x 0 else if (playerRec.x gt r2.x r2.width) RIGHT EDGE OF TILE controlledPlayer.getPosition().x (r2.x r2.width) controlledPlayer.getVelocity().x 0 if (playerRec.y lt r2.y) HIT TOP OF TILE diff (playerRec.y playerRec.height) r2.y controlledPlayer.getPosition().y Math.abs(diff) jumptime MAXJUMP controlledPlayer.setJumpState(JUMP STATE.GROUNDED) else if (playerRec.y lt r2.y r2.height) HIT BOTTOM OF TILE controlledPlayer.setJumpState(JUMP STATE.GROUNDED) jumptime 0 diff playerRec.y (r2.y r2.height) controlledPlayer.getPosition().y r2.y r2.height"} {"_id": 18, "text": "Different collision effects on different objects I'm a beginner to Corona and game development. I am using a variety of objects in my game. On collision, they all perform the same function. I want them to do different things, and also want some objects to only collide with certain other objects. How would I go about doing this?"} {"_id": 18, "text": "Separation of axis theorem implementation at normals This might be more of a math question, but it relates to the development of a simple physics engine I am trying to create. I have been stumped on this for about a week now, and have been unable to find an answer in any of the SAT tutorials. (http www.metanetsoftware.com technique tutorialA.html toc, http gamedevelopment.tutsplus.com tutorials collision detection using the separating axis theorem gamedev 169, etc.) I understand how SAT is supposed to work, however I am little confused on the math. First, I am finding my normals like so Block.prototype.findNormals function () var axisVectors new Array() var vertices this.Properties.Vertices var keys Object.keys(vertices) for( var i 0 i lt keys.length i ) var last x 0, y 0 axisVectors.push( xComponent (vertices keys i .y last.y), yComponent (vertices keys i .x last.x) ) last x this.x, y this.y return axisVectors I am then precede to project each vertex of the shapes I am testing on those normals. The problem occurs, and the part of the math that I am not fully understanding, is when I have a situation like so axis ( 5, 6) vertex (6, 5) math.dot(vertex, axis) This results in 0. Thus my min value for shape1 is always 0. And this results in a false collision. Can anyone explain the math a little better?"} {"_id": 18, "text": "Collision detection Swinging bat racket and ball I am programming a side view tennis game, inspired by an old arcade game, using Javscript and HTML5 canvas elements. The player can move left and right and holds a racket at arms length which can be rotated 360 degrees around the shoulder joint. I am quite happy with the collision detection and resulting deflection angle between the racket and the ball in the case where the player stands still and the racket does not move. I use a ray casting approach for this collision detection between the vector that represents the racket and the trajectory vector for the ball as proposed here. However, I am having trouble implementing the collision detection between the rotating racket and the ball. When the racket is swung, the area in which a collision would apply has a shape similar to a circular segment , but the racket rotates rotates to fast and the collision detection does not pick it up in most cases. The image bellow illustrates the problem, the red arrow indicates the direction of the swinging racket. The following code snippet from the player entity's update function shows how the racket is updated. arcmx and armcy is the location of the shoulder joint, rstart and rend are the beginning and end of the racket. if(KEY STATUS.rleft KEY STATUS.rright) if(KEY STATUS.rright) this.rangle this.rspeed else if (KEY STATUS.rleft) this.rangle this.rspeed this.armcx this.x this.width 2 this.armcy this.y 46 this.rstartx this.armcx Math.cos(this.rangle) 40 this.rstarty this.armcy Math.sin(this.rangle) 40 this.rendx this.armcx Math.cos(this.rangle) 71 this.rendy this.armcy Math.sin(this.rangle) 71 I am pretty lost on this problem and appreciate any hints on how to approach it."} {"_id": 18, "text": "RK4 integration and Continuous Collision Detection I'm using this method to detect collision between two AABBs. The algorithm is simple, fast and works great. It uses the relative velocity between the two objects to calculate TOI. This works fine with Euler, but now i'm trying to switch to RK4, which makes it hard for me to determine the TOI since i can't just divide the distance between the two AABBs by their relative velocity. Since RK4 is so popular, how do people deal with this issue? How to calculate a TOI for a swept AABB with RK4?"} {"_id": 18, "text": "How do I detect the intersection of a curve with itself? I'm developing a game in which the player can draw a line. I want to detect if that line intersects with itself. How would I do this?"} {"_id": 18, "text": "Delaying certain actions functions in libgdx using Timer? Hello I am trying to delay a part of the processes in my game, but it happend that I use one of my variables in an inner class so I have to make it final, but by making it final I can't assign new value when I find it. All I am asking for is to explain me how to do the delay without making my variable final. Here is my code public class TomatoScript implements IActorScript private CompositeActor tomato private static final int speed 100 private BitmapFont bFont private Batch bch ArrayList lt FruitScript gt fruits private final int dmg 10 private int hp 50 private Rectangle bounds private int state 0 private FruitScript collidetFruit private boolean dead() return hp lt 0 private void setHp(int dmg) hp hp dmg public TomatoScript(Batch b, BitmapFont bf, ArrayList lt FruitScript gt fruits) this.bch b this.bFont bf this.fruits fruits Override public void init(CompositeActor entity) this.tomato entity tomato.setPosition(200, 129) bounds new Rectangle(tomato.getX(), tomato.getY(), tomato.getWidth(), tomato.getHeight()) bch.begin() bFont.draw(bch, Integer.toString(hp), tomato.getX() 20, tomato.getY() 95) bch.end() Override public void act(float delta) switch (state) case 0 tomato.setX(tomato.getX() speed delta) bounds.setX(tomato.getX()) bch.begin() bFont.draw(bch, Integer.toString(hp), tomato.getX() 20, tomato.getY() 95) bch.end() if (tomato.getX() gt 1090) tomato.remove() if (collisionFound()) state break case 1 if (collisionAct(collidetFruit)) state 0 break private boolean collisionFound() for (FruitScript f fruits) if (f.getBounds().overlaps(bounds)) collidetFruit f return true return false private boolean collisionAct(FruitScript f) com.badlogic.gdx.utils.Timer.schedule(new com.badlogic.gdx.utils.Timer.Task() Override public void run() f.setCol(true) here it says I should make the \"f\" final. f.setHp(dmg) here also. setHp(f.getDmg()) ,2) if (f.dead()) fruits.remove(f) return true if (dead()) if (!f.dead()) f.setCol(false) tomato.getScripts().remove(this) tomato.remove() return false return false Override public void dispose() I've tried to make it final, but it ruins everything it's supposed to stop the actors do the damage taking and then the one alive to continue, but it was doing it too fast in a blink of an eye. When you make the f final, it can't get the new item it should collide with. I hope someone can help )"} {"_id": 18, "text": "2D collision rectangles can glitch into each other I have implemented a simple rectangle based collsion detection where you can \"slide\" around the edges on diagonal movement. Works fine but the thing is, it is somehow possible that e.g. the player (rectangle) glitches into the one of a collision object. It seems, that it appears only when the player \"slides\" around the corners. I suspect that if the player walks around the corners that the movement direction (Vector2) cuts off the corner and at some point glitches into the collision rectangle. I hope I've explained the problem somehow understandable? The code looks like this The UpdateCall recieves the playerMovement from the keyboard input public void UpdatePlayer(GameTime gameTime, Vector2 playerMovement) ... playerMovement CalculatePlayerMovement(Vector2.Normalize(playerMovement) movementspeed) if (playerMovement.Length() ! 0) MoveBy(playerMovement) ... The CalculatePlayerMovement Method checks world bounds, collision objects and so on. Depending on what side the collsion happens, the x or y movement will be zeroed. private Vector2 CalculatePlayerMovement(Vector2 movement) Rectangle destRect new Rectangle(BoundingBox.X (int)movement.X, BoundingBox.Y (int)movement.Y, Width, Height) Vector2 returnValue movement ... foreach (Rectangle r in TileMap.collisionObjects) if (destRect.Intersects(r)) string collsionSide GetCollisionSide(destRect, r) if (collsionSide \"top\" collsionSide \"bottom\") returnValue.Y 0 if (collsionSide \"left\" collsionSide \"right\") returnValue.X 0 ... Finally the check itself. I took this part from HERE since I was not sure what the best way would be. private string GetCollisionSide(Rectangle destRect, Rectangle r) float w (destRect.Width r.Width) 2 float h (destRect.Height r.Height) 2 float dx destRect.Center.X r.Center.X float dy destRect.Center.Y r.Center.Y if (Math.Abs(dx) lt w amp amp Math.Abs(dy) lt h) float wy w dy float hx h dx if (wy gt hx) if (wy gt hx) return \"top\" else return \"right\" else if (wy lt hx) if (wy gt hx) return \"left\" else return \"bottom\" return \"\" I am not sure where the problem is, but it is probably something I don't see myself."} {"_id": 18, "text": "How to build bullet (hit) damage detection in Augmented Reality to a real life person acting as an opponent? I am building an Android AR game using ARcore 1.18 in Unity 2019.4.5f1 (LTS). Now I want to create something like bullet damage detection just like it is built in a normal Unity 3D game. Of course, the biggest problem is how can I even detect the real person's hitbox like it is done in a normal game? I need to somehow be able to attach the bullet damage script to the body of the real life person in real time. Has anyone tried this before? How can we achieve this? I understand if I might not get a spoonfed tutorial but some help towards what should I be doing to achieve this will be greatly appreciated. I see some other FPS Augmented Reality games which either uses Laser Tag (Father.io) or Barcodes to scan the opponents. These are definitely some great ideas to create an FPS game experience but still, if possible, I want to try it with just the mobile camera without any external support. I am ready to bear some accuracy loss )"} {"_id": 18, "text": "Unity OnTriggerEnter2D does not get called when using Raycast In a previous post I talked about creating wires (using B zier curve) using LineRenderer. I am using a PolygonCollider2D to wrap the wire (see below) GameObject wire new GameObject () LineRenderer lineRenderer wire.AddComponent lt LineRenderer gt () PolygonCollider2D wireCollider wire.AddComponent lt PolygonCollider2D gt () After drawing the curve and attaching the collider (as described in previous post), I added a new component to my gameObject (a WireController) WireController wireController wire.AddComponent lt WireController gt () The WireController currently has only one method void OnTriggerEnter2D(Collider2D other) Debug.Log (\"I'm hit!\") I use a Physics2D.Raycast to check if my mouse pointer is at any point interacting with the wire void CastRay() Ray ray Camera.main.ScreenPointToRay (Input.mousePosition) RaycastHit2D hit Physics2D.Raycast (ray.origin, ray.direction, 100) if (hit) Debug.Log (hit.collider.gameObject.name) If I call CastRay() inside a Update() loop, if (hit) returns true (if the mouse pointer is over the gameObject, in this case, the wire), but the OnTriggerEnter2D method never gets called. A few observations collider.isTrigger true The WireController is attached to the newly created gameObject (it's visible in the Unity editor at runtime) Any help is much appreciated!"} {"_id": 18, "text": "What's the fastest collision detection (Game Maker) I want to build a simulator using Game Maker in which there are many (up to hundreds) of obj Cell, each has a radius of 10, (they don't have sprites, they just draw a circle with radius 10). Each step, I want the cells to check around itself for obj A to see if any obj A is \"touching\" it, (has a distance less than 10 from the cell). However, since I have so many obj Cell and so many obj A, the most straight forward code (below) will have to be executed tens of thousands of times (number of obj A number of obj Cell) In obj Cell (with obj A) if distance to object(other) lt 10 do stuff Is there any possible way to make this faster?"} {"_id": 18, "text": "What's the fastest collision detection (Game Maker) I want to build a simulator using Game Maker in which there are many (up to hundreds) of obj Cell, each has a radius of 10, (they don't have sprites, they just draw a circle with radius 10). Each step, I want the cells to check around itself for obj A to see if any obj A is \"touching\" it, (has a distance less than 10 from the cell). However, since I have so many obj Cell and so many obj A, the most straight forward code (below) will have to be executed tens of thousands of times (number of obj A number of obj Cell) In obj Cell (with obj A) if distance to object(other) lt 10 do stuff Is there any possible way to make this faster?"} {"_id": 18, "text": "Python collision problem I have a hero character with jumping physics that I am trying to figure out the collision detection for. Right now, the problem that I am running into is as soon as the character hits the floor (while I'm pressing left on the left side of the screen) the rect that it recognizes that it is colliding with is the ground. Which is to be expected. However, based on the checks that I have, for sprite in self.group.sprites() wall collide sprite.feet.collidelist(self.walls) if wall collide gt 1 print wall collide if self.col ground(sprite, wall collide) self.hero.jumping False sprite.move back y(dt) if self.col left(sprite, wall collide) sprite.move back x(dt) if self.col right(sprite, wall collide) sprite.move back x(dt) print quot quot since the character is colliding with the ground, the check to see if the character's rect is inside the colliding rect fails for 2 reasons 1 The current collision rect is the ground which the character is above, so the test fails 2 Because of 1, the character will keep moving left until it realizes it's colliding with the left side, at which point it will have already gone too far into the wall. What's the best collision solution? Note the character starts to the right of the left wall, on the ground but isn't colliding with the ground since the start position is right above it. Also, I realize that my code is a bit jumbled and I'm not taking care of every sprite in the group. I'll fix that once I have this fixed. I can provide more code pictures if necessary Edit More code def col ground(self, sprite, wall) if self.walls wall .collidepoint(sprite.feet.midbottom) return True return False def col left(self, sprite, wall) if self.walls wall .collidepoint(sprite.feet.midleft) return True return False def col right(self, sprite, wall) if self.walls wall .collidepoint(sprite.feet.midright) return True return False"} {"_id": 18, "text": "When is a quadtree preferable over spatial hashing? I'm making a 2d platformer with lots of objects at the same time. They're all AABB collision detected. I first tried a quadtree to decrease the number of of objects to check, tried a few different configurations, but it didn't prove as effective as I needed. I implemented a spatial hash and it's way more efficient, the number of objects to check for each collision went down drastically. Is there a case when doing 2d collision detection using a quadtree is preferable over spatial hashing? According to my tests, it seems spatial hashing always ends up with less objects to be tested for collision? I haven't done timing over the algorithms, but is hashing simply very expensive or difficult to implement when you're, for example, coding in C? Worth noting is that I'm writing the game in javascript, where you have hashing \"for free\". Here's the comparison, did I overlook something? http zufallsgenerator.github.io 2014 01 26 visually comparing algorithms"} {"_id": 18, "text": "Is an extra collision mesh for level data worth the hassle? What is the optimal approach for collision detection with the environment in an 3D engine (with triangle mesh based geometry, no bsp)? A) Use the render mesh no need for additional work for artists to fiddle with collision detection high detail is harder for physics calculation maybe use collidable flags for materials compute the collision mesh from the render mesh B) Use an additional collision mesh faster more optimal collision detection additional work (either by the artist or by the programmer who has to develop an algorithm to compute it from the render mesh) more memory useage How do AAA title handle this? And what are the indie dev's approaches?"} {"_id": 18, "text": "Exact collision time of two axis aligned bounding boxes I am trying to calculate the exact collision time of two axis aligned bounding boxes (aabb) as fast as possible (in the sense of CPU time). I have all the required information (aabb min, max, center, etc., velocity vector, and so on) My aabbs are not rotating, so they have linear velocity The aabbs can be both moving, only one of them might be moving, or they both might be steady My current approach creates lines from one of the boxes' corners and checks the collision among the planes of the other box (you can see the algorithm below) however it takes 6 times longer than I can afford. So, I am trying to find a faster algorithm however, I couldn't have managed, yet. My current quot slow quot algorithm Add velocity of Aaabb to Baabb and assume Aaabb is steady and Baabb is moving Calculate the corner positions of Baabb For each corner of Baabb, perform the line plane intersection with Aaabb's each 6 planes (I use the line intersection formulate (algebraic form) on Wikipedia) to check if there is an intersection. If a corner of Baabb intersects with a plane of Aaabb, verify the intersection point is behind the other 5 planes of Aaabb Keep the smallest value of d and return"} {"_id": 18, "text": "Collision detection Swinging bat racket and ball I am programming a side view tennis game, inspired by an old arcade game, using Javscript and HTML5 canvas elements. The player can move left and right and holds a racket at arms length which can be rotated 360 degrees around the shoulder joint. I am quite happy with the collision detection and resulting deflection angle between the racket and the ball in the case where the player stands still and the racket does not move. I use a ray casting approach for this collision detection between the vector that represents the racket and the trajectory vector for the ball as proposed here. However, I am having trouble implementing the collision detection between the rotating racket and the ball. When the racket is swung, the area in which a collision would apply has a shape similar to a circular segment , but the racket rotates rotates to fast and the collision detection does not pick it up in most cases. The image bellow illustrates the problem, the red arrow indicates the direction of the swinging racket. The following code snippet from the player entity's update function shows how the racket is updated. arcmx and armcy is the location of the shoulder joint, rstart and rend are the beginning and end of the racket. if(KEY STATUS.rleft KEY STATUS.rright) if(KEY STATUS.rright) this.rangle this.rspeed else if (KEY STATUS.rleft) this.rangle this.rspeed this.armcx this.x this.width 2 this.armcy this.y 46 this.rstartx this.armcx Math.cos(this.rangle) 40 this.rstarty this.armcy Math.sin(this.rangle) 40 this.rendx this.armcx Math.cos(this.rangle) 71 this.rendy this.armcy Math.sin(this.rangle) 71 I am pretty lost on this problem and appreciate any hints on how to approach it."} {"_id": 18, "text": "Godot raycast colliding too high I am making an fps that uses a raycast for shooting. I used some suggestions taken from a few reddit pages, but it's mostly my own code. It was working properly, until I noticed that when you shot up above the enemy, it still registered as a hit. Does anyone know why this might be happening? code func use weapon() Raycast.force raycast update() if Raycast.is colliding() var collider Raycast.get collider() if collider if collider.has method( quot takedamage quot ) collider.takedamage(10)"} {"_id": 18, "text": "How do I compute the angle between a pixel on an irregular curve and a circle colliding with it? I'm building a custom physics engine to accompany a level editor. This image shows how the level editor outputs levels Now, some explanation is in order. The curve is defined by the red points. After they are connected in threes by circles (yellow lines show these circles), a system connects them in a 'streamlined' way as shown by the blue lines. This makes the curves flow seamlessly. Now, these curves are 'irregular,' so to say. For the accompanying physics engine how do I detect the angle made between a pixel on the curve and a colliding circle (per pixel collision check)?"} {"_id": 18, "text": "Tiles and a walkable path My game a sidescrolling platformer. I've created my own Tile app which in the end export an xml file detailing what each 32x32 space (in the entire image) contains (environment, platform, etc.). I get how to use it for static things collision detection and quad trees and so forth but still have no clue how to use this map xml file for keeping my character on a path in my background image which in my case is a hill with lots of odd curves. Also, yes, there are tutorials on tile movement, but they are mostly movement from a top down view which is slightly more trivial to implement. 80 of the image in my game is just a pure background and the very bottom are bricks covered with grass with some weirder angles. The thing is, I can have mixed tiles of empty space and grass which contains a part of a curve so I don't know how I would want the player leg to interact with this. Can anyone give me an idea or an example?"} {"_id": 18, "text": "IntersectMovingAABBAABB weird behavior I'm using the IntersectMovingAABBAABB implementation from the book Realtime Collision Detection and I'm having a little bit of an issue. When I have two AABBs next to each other (not touching), A being stationnary and B moving up or down, I'm getting a result saying there's a collision. Obviously this is wrong. A B B moving up down I've rechecked my code multiple times to make sure I had the same thing as in the book. Stepping through the code, I realized that the check for v i lt 0 and v i gt 0 will never be true for either X or Z axis when moving straight up or down. Therefor, no checks for intersections on these axis will be done. I find that quite weird, and I was wondering if I was missing something, or if this code is simply bad. Here's my implementation for reference public static bool IntersectMovingAABBAABB(AABB a, AABB b, Vector3 va, Vector3 vb, out float first, out float last, out BlockFace face) face BlockFace.None if (TestAABB(a, b)) first last 0 return true Vector3 v vb va float current first 0 last 1 for (int i 0 i lt 3 i ) if (v i lt 0) if (b.Max i lt a.Min i ) return false if (a.Max i lt b.Min i ) if ((first Math.Max(current (a.Max i b.Min i ) v i , first)) current) face (BlockFace)(1 lt lt (i)) if (b.Max i gt a.Min i ) last Math.Min((a.Min i b.Max i ) v i , last) if (v i gt 0) if (a.Max i lt b.Min i ) return false if (b.Max i lt a.Min i ) if ((first Math.Max(current (a.Min i b.Max i ) v i , first)) current) face (BlockFace)(1 lt lt (i 3)) if (a.Max i gt b.Min i ) last Math.Min((a.Max i b.Min i ) v i , last) if (first gt last) return false return true"} {"_id": 18, "text": "Understanding unknown mesh data structure I have a large number of old mesh files in a custom, undocumented binary format. I have managed to parse almost everything but am left with one group of structures, described below, that I don't understand. I hope an experienced graphics programmer can explain what is happening. Here are the structures concerned These types are defined below. We're trying to understand what these three arrays are used to achieve. VertexRef vertexRefs Triangle triangles Unknown unknowns struct VertexRef Earlier in the file, there are several vertex buffers. The file can contain multiple meshes, either as components of a larger mesh, or as multiple LODs. This value group picks out one of these buffers. uint8 t group Index into the vertex buffer picked out by group . uint16 t vertexIndex struct TriangleVertex Index into the array vertexRefs uint16 t vertexRef Index into the array unknowns uint16 t unknownIndex struct Triangle TriangleVertex verts 3 struct Unknown Index into the array vertexRefs uint16 t vertexRef1 Index into the array triangles uint16 t triangleIndex1 Another index into the array vertexRefs uint16 t vertexRef2 triangleIndex2 can be 0xffff, while triangleIndex1 never is uint16 t triangleIndex2 The array of VertexRef is straightforward. It picks vertices, potentially from multiple meshes, to form a composite mesh. The array of Triangle is formed by vertices from the array of VertexRef. Each vertex is also associated with an Unknown. I am out of my depth in understanding what Unknown is doing. Member triangleIndex2 sometimes being 0xffff (or invalid, or nonexistent?) might indicate it is a leaf node of a tree? Perhaps the structure comprising the arrays vertexRefs, triangles and unknowns is some kind of collision detection tree? I'd be very grateful for any hints. Please ask questions if I've failed to be clear enough about something. Edit In answer to a request in comments, I am attaching a sample file and code to load it. The code should run on any likely system. The file is a mesh of a pair of boots. The file is hosted at uploadfiles.io https ufile.io w66mh"} {"_id": 18, "text": "How to do collision detection on marching cubes terrain? I'm writing the physics part of my game engine. The world uses the marching cubes algorithm on a 3d perlin noise to make the terrain. How do I do collision detection on the resulting mesh? I can't use SAT since the terrain is not convex and subdividing it into smaller convex parts seems to be nearly impossible. What is the best collision detection algorithm for such a mesh? The objects that are supposed to collide with the terrain can be any convex polyhedron. EDIT The terrain is not \"cubed\" (like minecracft). The terrain is smooth with slopes. This is pretty close to what my terrain looks like (this is NOT my video) https www.youtube.com watch?v 4rA3fdKWQA I am looking for a general collision detection here. I need the point(s) of contact and the normals so that I can put these into my collision resolver. Example of usage is throwing a box onto the terrain and it should roll and bounce approximately like it would in the real world."} {"_id": 18, "text": "Meaning of offset in pygame Mask.overlap methods I have a situation in which two rectangles collide, and I have to detect how much did they collide so I can redraw the objects in a way that they are only touching each other's edges. It's a situation in which a moving ball should hit a completely unmovable wall and instantly stop moving. Since the ball sometimes moves multiple pixels per screen refresh, it is possible that it enters the wall with more than half its surface when the collision is detected, in which case I want to shift its position back to the point where it only touches the edges of the wall. Here is the conceptual image it I decided to implement this with masks, and thought that I could supply the masks of both objects (wall and ball) and get the surface (as a square) of their intersection. However, there is also the offset parameter which I don't understand. Here are the docs for the method Mask.overlap Returns the point of intersection if the masks overlap with the given offset or None if it does not overlap. Mask.overlap(othermask, offset) gt x,y The overlap tests uses the following offsets (which may be negative) .. A yoffset .. B xoffset"} {"_id": 18, "text": "Allowing one sprite to move through another in Quintus I have a Bumper class extended from Sprite Q.Sprite.extend(\"Bumper\", init function(p) this. super(p, gravity 0 ) this.add(\"2d, ... etc. I have an Enemy class that should trigger a function when the center of the Bumper and of the Enemy collide. I was thinking about doing something like this in my Enemy class this.on(\"bump.top, bump.bottom, bump.left, bump.right\", function(collision) if(collision.obj.isA(\"Bumper\")) if (this.p.x collision.obj.p.x amp amp this.p.y collision.obj.p.y) Do something ) But for that I need the two sprites to move through one another. Is there a way to do that while still checking for collision ?"} {"_id": 18, "text": "Calculating contact points with SAT After detecting a collision between two convex shapes by using separating axis theorem and calculating MTV. How can I calculate the contact points?(for applying torque to the rigid body)."} {"_id": 18, "text": "Area attack collision resolving I'm planning to write little 2D go right and swing your sword game. When i started to write my ideas on paper i've come across a little problem. Let's say i'm using magic spell, ex. fireball which technically is a signle projectile flying slowly in a specified direction. As it's defined to be a piercing projectile, I want it to hit every enemy only once, no matter how big their sprites are. And how I do it? I know i can use the array of already hit enemies and check every frame if projectile collides something new, but is it a correct way? Are there any tried and true ways of resolving problems like this?"} {"_id": 18, "text": "Can Bullet Physics (or another 3d physics engine) use callbacks in my engine to check static geometry? I'm wondering if it's possible to use or hack Bullet 3d Physics (or another free 3D physics engine) so that I don't need to \"import\" my static geometry into Bullet instead I want to do it the other way, so Bullet uses some sort of callback system to check geometry properties of my mesh polygons. Sort of like that Bullet would expect a method in my static geometry classes \"checkRayIntersection\" or similar, and I take care of the details and optimizations myself. The meshes are immovable, so the only thing that I expect Bullet to care about is intersections and their normals, but I might be missing something.. EDIT as an example, consider a 10 million polygon terrain mesh which is changing all the time. You probably don't want to keep parallel data structures in the render engine and in the physics engine for this. You don't want to use an approximation for the physics either. Bullet uses something called MotionStates to solve this problem for its output I was hoping there was a similar design pattern for passing geometry input."} {"_id": 18, "text": "Rotated Sprites collision detection I am trying to implement checkCollision function in my game, I used AABB method but the problem is that my sprites are rotated so it's not really precise. I could finely describe my Sprites with rotated ellipses. Is there any more precise way of detecting the collision if I have the following attributes of entities entity.x entity.y entity.width entity.height entity.angle Here is what I have coded so far (x and y are in the middle of my sprite) this.checkCollision function(entity1, entity2) return (entity1.x (entity1.width this.COLLISION EPSILON WIDTH) 2 lt entity2.x (entity2.width this.COLLISION EPSILON WIDTH) 2 amp amp entity1.x (entity1.width this.COLLISION EPSILON WIDTH) 2 gt entity2.x (entity2.width this.COLLISION EPSILON WIDTH) 2 amp amp entity1.y (entity1.height this.COLLISION EPSILON HEIGHT) 2 lt entity2.y (entity2.height this.COLLISION EPSILON HEIGHT) 2 amp amp (entity1.height this.COLLISION EPSILON HEIGHT) 2 entity1.y gt entity2.y (entity2.height this.COLLISION EPSILON HEIGHT) 2) PS my cousin told me to do it with three circles (which creates a shape very similar to the ellipse) but I do not really know how to do it."} {"_id": 18, "text": "Custom Tile Collision Detection Has Trouble With Edges So, I'm writing my own game to expand on my abilities as a programmer. However, I have come to a writer's block of sorts. The game I am building uses tile collision, but allows the player to be in an unaligned space (like at the edge of a tile rather than directly above it). The code I have written to determine which tile the player is standing on is failing. On certain edges, when standing on top of the tile, the player will fall through the tile. Here is an example of this occurrence http i.imgur.com CACfhIP.gifv I have narrowed this down to this specific segment of code (Please note that SPRITE WIDTH is 20, which also means 20 pixels) BOOL changePos(Player player, Level level, int newX, int newY) int roundedY int roundedX if (newX lt player gt pos.x) roundedX roundDownTo(newX, SPRITE WIDTH) round down to a multiple of SPRITE WIDTH else if (newX gt player gt pos.x) roundedX roundUpTo(newX, SPRITE WIDTH) ditto but up The problem seems to be that both parts of the if...else if... statement require the equality symbol to work correctly. Meaning that in the provided example, the fall through glitch will happen to the tile on the left instead if I move the equality symbol to the else if portion. I attempted to fix this issue by adding an else clause and removing the equality from the if...else if... parts. My method was to determine which half of the tile the player was on and determine if it required them to fall. So, my code became this BOOL changePos(Player player, Level level, int newX, int newY) int roundedY int roundedX if (newX lt player gt pos.x) roundedX roundDownTo(newX, SPRITE WIDTH) else if (newX gt player gt pos.x) roundedX roundUpTo(newX, SPRITE WIDTH) else if (newX SPRITE WIDTH gt SPRITE WIDTH 2) roundedX roundDownTo(newX, SPRITE WIDTH) else roundedX roundUpTo(newX, SPRITE WIDTH) But this created an even stranger case where the middle part of the tile would cause a fall through but the edges would work correctly on both the left and the right tile. This can be seen here http i.imgur.com lTaUuzh.gifv I've been at this all day (literally), I appreciate any help you can provide. If I have not provided enough information, please let me know and I will do my best to provide it."} {"_id": 18, "text": "How do I determine wall direction, with information of normal and incoming direction? What is formula and theorys used to determine wall direction, with only knowing the normal of the wall and the direction of the incoming object? This answer has already stated a formula, but I don't know where it came from, and I am in need of understanding."} {"_id": 18, "text": "3D line segment AABB collision, with hit normal? I'm embarrassed I can't find this, but I'm wanting to detect intersection with a 3D line segment (not an infinite ray) with a 3D AABB, the AABB being defined as two Vec3f's which represent the Min and Max extents. So the AABB can be arbitrarily sized. I also need the surface normal of the AABB, if there was a hit. From looking at similar algorithms I at least know it seems good to calculate the inverse direction of the line beforehand, at least, if you're needing to check against multiple AABBs per frame. I have struct AABB VEC3F min VEC3F max a and b representing start end points of the line segment returns true if intersects, also fills out \"normal\" if true bool LineIntersectsAABB(const VEC3F amp a, const VEC3F amp b, const VEC3F amp inv dir, const AABB amp aabb, VEC3F normal) The implementations I've found either do not find the hit normal, and or they're intended for boxes cubes where the three dimensions of the box are always equal length, which doesn't work for me. Implementations seem to vary greatly, which is confusing for me (since I'm still trying to learn it), and, considering that I need the hit normal, I'd imagine that that may rule out certain implementations."} {"_id": 18, "text": "How to implement 2d collision detection that is immune to low framerate and fast movement? I am trying to implement my own collision detection for a 2.5d voxel style platformer using Three.js. I have a problem with my implementation if the framerate is too low or the character is moving too fast (usually when falling from high places) it falls right through. Is there a way to improve collision detection to be immune to problems like this? This is how I detect collisions function render() requestAnimationFrame(render) setVelocity() animate() manageCollisions() renderer.render(scene, camera) function manageCollisions() Check every game object for collision gt TODO implement broad phase when dealing with many objects for(i 0 i lt world.length i ) Check for bottom collision lt ALWAYS check (unless moving up) if(velocityY lt 0) if( (character.position.y character.height 2) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log(\"bottom collision \" i) velocityY 0 jumped false grounded true character.position.y world i .position.y world i .height 2 character.height 2 0.1 0.1 prevents shaking else grounded false Check for right collision lt ONLY if moving right (velocityX is positive) if(velocityX gt 0) if( (character.position.y) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log(\"right collision\" i) velocityX 0 character.position.x world i .position.x world i .width 2 character.width 2 check for left collision lt ONLY if moving left (velocityX is negative) if(velocityX lt 0) if( (character.position.y) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2)) console.log(\"left collision\" i) velocityX 0 character.position.x world i .position.x world i .width 2 character.width 2 check for top collision lt ONLY if moving up (velocityY is positive) if(velocityY gt 0) if( (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) lt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log(\"top collision\" i) velocityY 0 character.position.y world i .position.y world i .height 2 character.height 2"} {"_id": 18, "text": "Collision detection recommendations I am currently developing a prototype game for mobile devices in which the user will see several objects on the screen and will have to touch them one by one in the correct order to win. I guess it that you can say that it is similiar to a Whack a Mole game, but instead of having moles popping up on the screen, I will have several objects moving around. I am having some difficulties in implementing a collision detection algorithm for this game, thefore I would like your recommendation on what is the best method to use. For example suppose an object is moving in a given direction, then I could use the SAT to check if it collides with other objects. If it does collides, then it will stop and move in another direction which is randomly chosen. Another option would be to divide my screen into square or hexagonal tiles. This way I could just check if the tiles are free or occupied before moving the objects. My game be 2D and will use a top down ortographic projection and I am developing it using Cocos2d X and Marmalade SDK. I am not using any physics engine, because my game does not require them (the objects just have to move around, they don't bounce or need any sort of physics behavior)."} {"_id": 18, "text": "Tile based collision detection errors if player is smaller than tiles I have implemented a tilemap where each tile is at a non negative x and y position. (So at the moment think like chess) At the moment a tile is 16, 16 pixels in size Tile 0,0 is at the left bottom corner Some tiles should be collidable. I've never implemented something like that and during research stumbled upon https jonathanwhiting.com tutorial collision The general idea collision response handling let mut new pos Point2 new(curr pos.x x offset, curr pos.y) let collision on x collide with world( amp new pos, amp world) if !collision on x transform.translate x(x offset) new pos.y curr pos.y y offset let collision on y collide with world( amp new pos, amp world) if !collision on y transform.translate y(y offset) The collision detection fn collide with world(new pos amp Point2 lt f32 gt , world amp World) gt bool TODO make these sizes i16 instead so we can grow in any direction! let mut left tile u16 (new pos.x TILE SIZE IN PIXELS as f32) as u16 1 so that we do not collide until we are exactly at the thing let mut right tile u16 ((new pos.x PLAYER WIDTH 1.0) TILE SIZE IN PIXELS as f32) as u16 let mut top tile u16 ((new pos.y PLAYER HEIGHT 1.0) TILE SIZE IN PIXELS as f32) as u16 let mut bottom tile u16 (new pos.y TILE SIZE IN PIXELS as f32) as u16 println!(\"new pos ? , left , right , top , bottom \", (new pos.x, new pos.y), left tile, right tile, top tile, bottom tile) Useless as long as we use unsigned coordinates if left tile lt 0 left tile 0 if right tile gt WORLD WIDTH IN TILES right tile WORLD WIDTH IN TILES Useless as long as we use unsigned coordinates if bottom tile lt 0 bottom tile 0 if top tile gt WORLD HEIGHT IN TILES top tile WORLD HEIGHT IN TILES let mut any collision false for i in left tile.. right tile for j in bottom tile.. top tile let tile world.get tile(i, j) println!(\"tile at ? is ? \", (i, j), tile) match tile Some(tile) gt if tile WALL println!(\"hit a wall at ? !\", (i, j)) any collision true None gt (), return any collision I basically took (or tried to take) the optimised version of the linked blog entry. Now to the problems If PLAYER WIDTH and PLAYER HEIGHT are both 16.0 collision works fine But note that I had to put 1.0 in the calculation of the right tile and top tile, else the collision for UP and RIGHT would occur one pixel to early (so the player would never touch walls to their top or right) This change alone makes me a bit suspicious looks like I made an error there. The real problems start if the player is smaller than a tile In the following screenshots the following rules apply ) the PLAYER WIDTH and PLAYER HEIGHT are both 8 ) Greenish tiles are the only walls! ) All the screenshots were taken in ONE run no parameters were changed during this run! 1) Trying to collide with right tile overlapping 2) Trying to collide with top tile cannot go any nearer than 4 pixels (half the height of the player) 3) Trying to collide with left tile cannot go any nearer than 4 pixels (half the width of the player) 4) Trying to collide with top tile suddenly overlapping although different tile didn't collide? 5) Trying to collide with bottom tile cannot go any nearer than 4 pixels I cannot grasp 2 and 4 at the moment."} {"_id": 18, "text": "How to calculate max region area of 2d circles? I have some 2d circles on a plane, each has its own minRadius and maxRadius. When two circles collides, both of them will shrink their radius, so the actual radius of a circle is in range minRadius, maxRadius . I need to calculate the max possible radius of each circle. See below image for an example. Currently, I use the following algorithm to calculate the radius of each circle. I try to increase each circle's radius a little each steps, then check and solve if there is any collisions. foreach c in circles c.radius c.minRadius for (int i 0 i lt 10000 i) foreach c in circles c.radius c.radius 1 foreach c in circles calculate radius(c) function calculate radius(c) collides find all circles which radius is overlap with c() foreach x in collides x.radius somevalue c.radius somevalue end For now, the result looks fine, but the algorithm costs too much time. So I wonder if there exists other ways to solve it? wondra counterexample(maybe) The image below illustrates the problem. From my understanding of your algorithm, the final radius of circle A is 1.6, the calculation sequence is (BC, AB, AD) But if using my algorithm(increase radius by a small amount each step), the final radius of circle A is 1.5. I don't think recalculate the dist matrix after each selection will solve the problem, as stated in my question, each circle may have its own minRadius and max Radius."} {"_id": 18, "text": "How do I detect collision between movie clips? I know there are some methods you can use, like hittestPoint and so on, but I want to see where my movie clip collides with another another movie clip. Are there any other methods I can use? I have had trouble finding a good introduction to game physics, and I would like to know how to something like this, properly."} {"_id": 18, "text": "What are the advantages and disadvantages of overlap testing and intersection testing? I have been looking for the advantages and disadvantages of both overlap testing and intersection testing, but I was only able to find a few disadvantages overlap testing may fail for objects moving very fast, and intersection testing makes assumptions that may lead to wrong predictions, such as a constant speed and zero accelerations. What are the advantages and disadvantages of overlap testing and intersection testing?"} {"_id": 18, "text": "Collision Managers and bitmaps I am rewriting a game I made to use a (custom) collision manager that uses the minimum displacement method. As of now, my simple manager can only recognize and act on a couple of shapes Circles and AABB's. Those were pretty simple to implement, but I've run into a problem My game also needs to be able to have bitmaps that the player (represented by an AABB) can interact with, such as the one below I have a couple of questions 1) Does it make sense to have a shape BitmapShape, which does collision detection at the pixel level and searches outward in the bitmap for a place to move intersecting objects to? In the image above, it would make sense to check the players bottom center coordinates against the bitmap of the hill, but you can imagine that this would provide odd results for an intersection from the top of the player. 2) How could any system like this allow for a rectangle to move up a hill? Wouldn't an minimum displacement based method always move the rectangle backwards down a hill? Thanks"} {"_id": 18, "text": "How to move towards a point in 2D, stopping at obstacles I want to do a 2D game, where you can mouse click anywhere on the map and the player will go there. If there is obstacle in the way, the player will go as close as possible to where you clicked without going into the non walkable area. What would be the optimal way to accomplish this?"} {"_id": 18, "text": "Typical collision detection I would like to know how is the typical collision detection of most games. For example, you control a character which can move in 2 dimensional directions (except up and down). Now lets asume he walks into a wall, most of the games depending on character angle and the BB normal face will only stop the player in one axis, but will continue moving in the other along the wall axis. How is that done? I've only managed to stop the character from going through the wall by seting the position to the last one in the past frame if the new position colllisions the bounding box. But this just makes the player stop sharply and unrealisticly."} {"_id": 18, "text": "When there are multiple objects of the same type, how do I know which one I am colliding with? I'm working on a platformer game using Gamemaker Studio 2. , and currently I'm dealing with implementing platforms (Platforms are able to pass through from the bottom, but remains solid when landing on) It's all working good and well for a single platform, but when I add multiple, then only the lowest placed platforms will work properly. I'm already aware that the problem lies on the second if statement in the code below. if (place meeting(x, y mySpeed 1 , o platform) amp amp If the player collides with a platform mySpeed 1 gt 0 ) if the player is falling if ((y 29) lt o platform.y) if the player's feets are located higher than a platform while !place meeting(x, y sign(mySpeed 1 ), o platform) y sign(mySpeed 1 ) mySpeed 1 0 The problem is likely because it's reading information from any platform. but not the higher platform I'm colliding with. So I should need a check to make sure I'm talking about the same object I'm colliding with. If it was a build in collision event, I could use the other statement to get the right instance, but currently I'm using place meeting in a step method to collide, and other would be too broad to use properly. So how would I be able to archieve this?"} {"_id": 18, "text": "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... In 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. Let'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). So, 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?) Again, 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."} {"_id": 19, "text": "Polling events with SDL results in stuttering response when dealing with multiple objects I'm new to SDL programming and I'm not quite sure I got how it handles events. Given an instance like this defined in quot game.c quot static struct SDL Window window SDL Renderer renderer BinaryTree objects game NULL, NULL, NULL (Which of course gets properly initialized) My game loop is defined in the same file as follows void game run() bool closeRequested false while(closeRequested false) SDL RenderClear(game.renderer) binaryTree startIteration(game.objects) while(binaryTree hasNext(game.objects)) GameObject gameObject (GameObject ) binaryTree getNext(game.objects) SDL Event event while(SDL PollEvent( amp event)) if(event.type SDL QUIT) closeRequested true else if(event.type SDL KEYDOWN) gameObject onKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE UP) gameObject onUpKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE DOWN) gameObject onDownKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE LEFT) gameObject onLeftKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE RIGHT) gameObject onRightKeyPressed(gameObject) if(event.type SDL KEYUP) gameObject onRendering(gameObject) SDL RenderCopy(renderer, gameObject getTexture(gameObject), NULL, gameObject getDestination(gameObject)) SDL RenderPresent(game.renderer) game.objects contains every object which has to be rendered (via game.renderer) onto the the window (game.window). So, on each frame game.objects gets iterated on and for each element various functions get executed, before its texture is loaded to the renderer. Of course gameObject onRightKeyPressed() is called only if the right key was pressed, so if this function is defined as void gameObject onRightKeyPressed(GameObject gameObject) gameObject gt destination.x 1, On each frame that the right key is pressed, gameObject's texture will move by 1 pixel to the right. This works perfectly if game.objects contains only one element, but if a second element gets added, only the first one will smoothly respond to my input, while the other will move by 1 or 2 pixels just once in a while by keeping the right key pressed. It's like the first element contained in game.objects quot steals quot the input, so that when the second element's turn comes, there's no input for it to respond to. What did I do wrong?"} {"_id": 19, "text": "Best way to distribute graphics, audio and levels with an SDL game? I'm working on finishing up a game written in C with SDL I've been working on for awhile, and I'm starting to ponder how I'm going to distribute it. It has hundreds of images that are loaded and used throughout the game, as well as a couple dozen .wav files for audio effects. What is the best way to distribute these? Should I just include the folders with all the files? Or is there a way I can package them into a single file, then open and extract them in my application? What's the best way to go about this?"} {"_id": 19, "text": "SDL Multiple keyboard support I am making a game with multiplayer split screen mode using SDL. Basically, I like the idea of having each player plug in his own keyboard to the PC, set custom controls via options and being able to play it with controls that he likes. However, there's a problem. This code gets the keyboard event SDL Event event SDL PollEvent( amp event) SDL Event has member SDL KeyboardEvent key, which has member Uint8 which. In short event.key.which According to this, it should represent keyboard device index, however, I've tried connecting three keyboards to my PC and press the buttons at the same time and the result wasn't satisfying they all had same keyboard indexes. Is there a solution to this? Or am I missing something?"} {"_id": 19, "text": "Should I cull off screen objects in SDL2 My game will have a large number of objects moving offscreen at any given time, can i just render them all with SDL RenderCopy even though they are off screen or should I only render them if they are on screen? I will probably have many hundreds or throusands of objects loaded at a time. My dev machine is quite overpowered for what I'm trying to do but I am conserned that I just won't notice a preformance drop that may affect players with less powerful computers. So, will checking if each object is on screen before drawing increase performance lower CPU load, or can I safely let SDL handle this with clipping?"} {"_id": 19, "text": "Scaling an SDL Surface I want to create a button for a game's UI. The background uses a gradient and then I blit a surface on top of the gradient and use SDL SetColorKey to delete the unwanted pixels. The surfaces are not the same size the clipping mask is 200 x 50 and the gradient 1 x 50, so I need to stretch the gradient to the same width of the cliping mask, I can't use a wider image because the purpose of doing this is to save memory and storage and using the same gradient image on multiple clipping masks of different widths. I found I can use SDL BlitScaled but I need to blit the surface to itself and it appears to be useless because the surface remains the same size, am I doing something wrong? Is there a way to do it without blitting the surface to itself? SDL Rect final size final size.w 200 final size.h 50 final size.x 0 final size.y 0 SDL BlitScaled(gradient surface, NULL, gradient surface, amp final size) do some stuff with those textures SDL CreateTextureFromSurface(renderer, final button surface)"} {"_id": 19, "text": "SDL2 jagged staircase edges I am using SDL2 and SDL2 Image to render png images. When I rotate the textures, they turn out very ugly, like this This is the code responsible for the rotation and alpha mod. SDL Rect srcRect SDL Rect destRect srcRect.x width currentFrame srcRect.y height currentRow srcRect.w destRect.w width srcRect.h destRect.h height destRect.x x destRect.y y SDL SetTextureAlphaMod(m textureMap id , alpha) SDL RenderCopyEx(pRenderer, m textureMap id , amp srcRect, amp destRect, 10.0, 0, flip) Do I need to set a blendmode too?"} {"_id": 19, "text": "Is there a way how to handle multiple SDL PollEvent loops without clearing the event queue? Is there a way how can I handle more SDL PollEvent while loops for one SDL Event, without taking the events off from the event queue? Let us say I have something like this void Game processInput() SDL Event event SDL PollEvent( amp e) Engine InputManager processInput( amp e) GUI Library InputManager processInput( amp e) And then the engine processes the input in function like this void Engine InputManager processInput(SDL Event e) mainEvent e while (SDL PollEvent( amp mainEvent)) switch ( mainEvent.type) case SDL KEYDOWN Engine InputManager pressKey( mainEvent.key.keysym.sym) break case SDL KEYUP Engine InputManager releaseKey( mainEvent.key.keysym.sym) break However, this while loop clears the whole event queue, and another input manager (my GUI, for example) does nothing because it no longer has events in the queue. Is there a possible way to handle this situation?"} {"_id": 19, "text": "Errors in Xcode using SDL I am using Lazy Foo's Production tutorials for making an SDL game in C in Xcode 6.1 http lazyfoo.net tutorials SDL index.php Hello 20SDL. I'm using Xcode 7 but I don't think they are very different. In the second tutorial (http lazyfoo.net tutorials SDL 02 getting an image on the screen index.php). I cannot seem to compile properly without an error regarding one of the functions. The function prototype Frees media and shuts down SDL void close() Then the function declaration void close() Deallocate surface SDL FreeSurface( gHelloWorld ) gHelloWorld NULL Destroy window SDL DestroyWindow( gWindow ) gWindow NULL Quit SDL subsystems SDL Quit() And then the function call at the end close() I am getting these errors and am not quite sure how to fix them. Other solutions online are for problems that are not quite the same as mine. SDL Tutorial SDL Tutorial using image.c 28 6 Conflicting types for 'close' SDL Tutorial SDL Tutorial using image.c 28 6 Conflicting types for 'close' SDL Tutorial SDL Tutorial using image.c 127 5 Implicit declaration of function 'close' is invalid in C99 SDL Tutorial SDL Tutorial using image.c 127 11 Too few arguments to function call, expected 1, have 0 clang error linker command failed with exit code 1 (use v to see invocation) Any help would be much appreciated, as I am struggling to make progress with learning SDL game programming at the moment. Thank you."} {"_id": 19, "text": "SDL 1.2 reports wrong screen size I have a multi monitor setup with two displays, both 1920x1200. In games, I can only select resolutions 1920x1200 (like 2560x1200) which makes games unusable. Full screen doesn't work either because it switches one display to 800x600 which means I can't reach the close button... I have to kill the game and then, I have to restore my desktop because all windows are moved resized. How can I force SDL to use any resolution that I want?"} {"_id": 19, "text": "SDL PollEvent very slow on SDL2, but works fine on SDL1.2 I have this simple app that displays a screen and handles the quit event while( SDL PollEvent( amp e ) ! 0 ) User requests quit if( e.type SDL QUIT ) quit true If I compile this with SDL1.2 it runs fine, the quit event is handled immediately. However if I compile it for SDL2, then it takes 5 seconds to get that event. And not just quit, but other events also, like mouse. With sdl2 it takes 95 of the cpu, while with sdl1.2 it's 30 40 . The cpu is dual core, 1.2 ghz (pandaboard). I suspect something, but I'm not 100 sure I'm running this on ubuntu 12.04 which natively supports only sdl1.2. So I had to compile sdl2 from source code, as it's not available in that ubuntu. Could this be the reason? Or any other clues what might be wrong? Thanks!"} {"_id": 19, "text": "How do I modify textures in SDL with direct pixel access? I'm trying to use SDL LockTexture and SDL UnlockTexture for directly editing pixels in a texture. I'm using SDL 2.0. Setting the pixel value using the following code doesn't modify the texture void pixels int pitch SDL LockTexture(mytexture, NULL, amp pixels, amp pitch) Set pixel 100,100 to blue ((uint32 t )pixels) 100 100 255 SDL UnlockTexture(mytexture)"} {"_id": 19, "text": "Setting Square to Dim in Color on MOUSEUP I'm trying to create a simple recreation of the popular memory game \"Simon\" using C and SDL2. The idea is that the game is a small window with four squares of different colors that are purposefully dim. When the player clicks on a square, I want it to \"light up\" until the player let's go of their mouse button, in which it returns to it's original dim color. I have this working to an extent, but the problem is that it only works if the player let's go of the mouse button while the pointer is over the square. If they let go anywhere else, the square stays lit up. Here is the example code if(e.type SDL MOUSEBUTTONDOWN amp amp mouseX gt 10 amp amp mouseX lt 110 amp amp mouseY gt 10 amp amp mouseY lt 110) if(e.button.button SDL BUTTON LEFT) SDL SetRenderDrawColor(renderer, 0, 255, 0, 255) SDL RenderFillRect(renderer, amp squareOne) SDL RenderPresent(renderer) if(e.type SDL MOUSEBUTTONUP amp amp mouseX gt 10 amp amp mouseX lt 110 amp amp mouseY gt 10 amp amp mouseY lt 110) if(e.button.button SDL BUTTON LEFT) SDL SetRenderDrawColor(renderer, 0, 50, 0, 255) SDL RenderFillRect(renderer, amp squareOne) SDL RenderPresent(renderer) As you can see, I'm looking for the user to be clicking in a very specific area, and waiting for them to \"unclick\" in that same specific area. There has got to be a better way to do this. Would anyone do me the pleasure of offering a few hints?"} {"_id": 19, "text": "Should I cap the frame rate in SDL? I know this question has been asked a lot, but I never found an answer suitable for me. I have a game with a fairly big logic system and the movement system I am currently using is calling SDL GetTicks() and measuring the delta time between the frames. I multiply the delta with the speed and I get the pixel movement. The problem with this is that the CPU usage is quite high. I didn't really mind it until my friend started going on about how it was \"the end of the world\". The question I really want an answer to is if I should cap the framerate, and if a high CPU usage is unwanted (or even dangerous!)."} {"_id": 19, "text": "Setting Square to Dim in Color on MOUSEUP I'm trying to create a simple recreation of the popular memory game \"Simon\" using C and SDL2. The idea is that the game is a small window with four squares of different colors that are purposefully dim. When the player clicks on a square, I want it to \"light up\" until the player let's go of their mouse button, in which it returns to it's original dim color. I have this working to an extent, but the problem is that it only works if the player let's go of the mouse button while the pointer is over the square. If they let go anywhere else, the square stays lit up. Here is the example code if(e.type SDL MOUSEBUTTONDOWN amp amp mouseX gt 10 amp amp mouseX lt 110 amp amp mouseY gt 10 amp amp mouseY lt 110) if(e.button.button SDL BUTTON LEFT) SDL SetRenderDrawColor(renderer, 0, 255, 0, 255) SDL RenderFillRect(renderer, amp squareOne) SDL RenderPresent(renderer) if(e.type SDL MOUSEBUTTONUP amp amp mouseX gt 10 amp amp mouseX lt 110 amp amp mouseY gt 10 amp amp mouseY lt 110) if(e.button.button SDL BUTTON LEFT) SDL SetRenderDrawColor(renderer, 0, 50, 0, 255) SDL RenderFillRect(renderer, amp squareOne) SDL RenderPresent(renderer) As you can see, I'm looking for the user to be clicking in a very specific area, and waiting for them to \"unclick\" in that same specific area. There has got to be a better way to do this. Would anyone do me the pleasure of offering a few hints?"} {"_id": 19, "text": "Unable to detect continuous keypress event in SDL I am developing a game using SDL, and am unable to do continuous motion for my object when a key is held down. I'm calling SDL PollEvent() to retrieve all events during a frame, and passing each resulting SDL Event structure into this function void Avatar handle input(SDL Event keyInput) if( keyInput.type SDL KEYDOWN ) Adjust the velocity switch( keyInput.key.keysym.sym ) case SDLK LEFT Move(1) break case SDLK RIGHT Move(2) break The problem is that when I hold down the right or left arrow keys, the avatar only moves once instead of moving continuously for as long as I hold down the key. How can I make the motion continue for as long as the key is held down?"} {"_id": 19, "text": "SDL gray scale image from a a color image? I am new to sdl. I have basically have the following codes which can load the images. I know how to access the pixel as below. What I need it to convert the image to 8 bit grey level and 1 bit monochrome separately. I know it got to do with pixel manipulation. Any hint or idea how to to this? I am not too sure what to set for SDL CreateRGBSurface and also once I get the pixel what manipulation to be done?"} {"_id": 19, "text": "Background color gradient with SDL I want to create a menu for a game using a color gradient as the background. Is there a way to create a gradient background instead of using an image for it (since I don't know what size the window will be, using an image is no option). Please note I need to achieve this using only the C standard library and the SDL, no other library and no C ."} {"_id": 19, "text": "How do I modify textures in SDL with direct pixel access? I'm trying to use SDL LockTexture and SDL UnlockTexture for directly editing pixels in a texture. I'm using SDL 2.0. Setting the pixel value using the following code doesn't modify the texture void pixels int pitch SDL LockTexture(mytexture, NULL, amp pixels, amp pitch) Set pixel 100,100 to blue ((uint32 t )pixels) 100 100 255 SDL UnlockTexture(mytexture)"} {"_id": 19, "text": "In SDL, what is the difference between using a Surfaces and a Renderer? I am new to SDL and I've been following some tutorials in one tutorial he used Surfaces (a window surface and image surface) and a BlitSurface function to draw images without using any renderer (used SDL Image library for JPG, PNG etc.). And in another tutorial, he used a Renderer. What's the difference between those two? It seemed to me they do the same thing but I'm assuming if they were the same, one wouldn't exist."} {"_id": 19, "text": "SDL Multiple keyboard support I am making a game with multiplayer split screen mode using SDL. Basically, I like the idea of having each player plug in his own keyboard to the PC, set custom controls via options and being able to play it with controls that he likes. However, there's a problem. This code gets the keyboard event SDL Event event SDL PollEvent( amp event) SDL Event has member SDL KeyboardEvent key, which has member Uint8 which. In short event.key.which According to this, it should represent keyboard device index, however, I've tried connecting three keyboards to my PC and press the buttons at the same time and the result wasn't satisfying they all had same keyboard indexes. Is there a solution to this? Or am I missing something?"} {"_id": 19, "text": "Background color gradient with SDL I want to create a menu for a game using a color gradient as the background. Is there a way to create a gradient background instead of using an image for it (since I don't know what size the window will be, using an image is no option). Please note I need to achieve this using only the C standard library and the SDL, no other library and no C ."} {"_id": 19, "text": "Can I create relative filepaths to images in an XCode SDL project? Can I create relative filepaths to images in an XCode SDL project? I have to use absolute filepaths as it is, but it would be much easier if I could make the filepaths relative."} {"_id": 19, "text": "SDL 1.2 reports wrong screen size I have a multi monitor setup with two displays, both 1920x1200. In games, I can only select resolutions 1920x1200 (like 2560x1200) which makes games unusable. Full screen doesn't work either because it switches one display to 800x600 which means I can't reach the close button... I have to kill the game and then, I have to restore my desktop because all windows are moved resized. How can I force SDL to use any resolution that I want?"} {"_id": 19, "text": "SDL surface inside another GUI component? Is there a way to host an SDL surface inside another GUI component so that SDL is not at the top level? For instance, could I put an SDL surface inside a Java JPanel or other widget?"} {"_id": 19, "text": "Can Simple Direct Media Layer be used with WebGL? I have read that on desktop OpenGL SDL is a great way to learn. In looking at WebGL I couldn't find a Web version of SDL. On their site I see bindings for all sorts of languages, but no JavaScript. It seems obvious that this gives an answer of 'no' to my question, but I also came upon code snips while googling around that seemed to be doing it. Whatever the missing piece is I'm not getting it..."} {"_id": 19, "text": "Problem getting mouse events while keys held down in SDL2 I'm attempting to write input capturing code using SDL2 on Windows. However, I'm running into a problem. Whenever a key is held down, the SDL event queue has no mouse movement, nor will the mouse move on my screen. Instead, The SDL event queue continually returns the key I am holding down as an SDL KEYDOWN event. Here is a simple example program which reproduces the problem exactly include lt SDL2 SDL.h gt include lt iostream gt int main(int argc, char argv) SDL Init(SDL INIT EVERYTHING) SDL Window window SDL CreateWindow(\"Moust Input Test\", SDL WINDOWPOS UNDEFINED, SDL WINDOWPOS UNDEFINED, 640, 480, SDL WINDOW SHOWN) SDL Event event for( ) while (SDL PollEvent( amp event)) if (event.type SDL QUIT) SDL DestroyWindow(window) return 0 else if (event.type SDL MOUSEMOTION) int x, y SDL GetMouseState( amp x, amp y ) std cout lt lt \"Mouse moved to \" lt lt x lt lt \" \" lt lt y lt lt std endl else if (event.type SDL KEYDOWN) std cout lt lt \"Code of key pressed \" lt lt event.key.keysym.sym lt lt std endl return 0 What I would expect to happen is that, when I hold down a key (for example, 'a'), it prints exactly once Code of key pressed 97 And then, while they key is held down, if the mouse is moved, it prints every time the mouse is moved Mouse moved to wherever Instead, I'll keep seeing over and over again Code of key pressed 97 And I will not get any mouse movement whatsoever on the screen, nor will I get my mouse movement log printed, until I release whatever keys I am holding down. Anybody know how I can capture mouse movement while I have a key held down? The only thing I can think of which could possibly be relevant is I am compiling with MinGW using g Dmain SDL main test.cpp o test.exe L. lib SDL2 lmingw32 lSDL2main lSDL2 mwindows mconsole Thanks. Edit I've also just noticed that the problem persists even when the window is minimized if I am holding a key down in this text window while my program is minimized in another Window, the mouse stops working, though my program is not printing out the key code."} {"_id": 19, "text": "SDL RenderDrawLines isn't drawing complete geometry So I am trying to draw hexagons with SDL RenderDrawLines . It looks to be working fairly well, however, it fails to draw some of the lines. So each of the hexagons in the screenshot is a hex object. They each have a center x y , and an array of SDL Points for the six corners of the hex. Here is the hex object draw call SDL RenderDrawLines( TheGame Instance() gt getRenderer(), corners, HEX NUMBER OF CORNERS) There is some reoccurring condition that causes a vertical line to not be rendered, and I can't seem to figure out why. The two obvious things that stand out don't explain why there is no line The draw order of the objects shouldn't matter since all of the borders for each hex are being drawn. The horizontal distance between adjacent hexes' centers can be 1 because of rounding would lead to a double thick border and not a missing border. If anyone has any insight, I welcome the input. EDIT I have been over suggestions you have mentioned prior to this question, increasing the array of points to 7 is correct, I tested it on a triangle before I tried with hexagons. When you don't close of the shape, you typically get drawn lines that shoot off the edge of the screen. The part on three lines is also something else I discovered while messing around. I included some of my code to show the two ways that I preformed the very thing you mentioned render the hexagon to on screen void Hex draw() draw order of points rotate ccw 90 degrees for actual postion 2 3 1 4 0 5 draw the hex with a fill color 0XAABBGGRR is the bit order for the color param filledPolygonColor( TheGame Instance() gt getRenderer(), vx, vy, HEX NUMBER OF CORNERS, r order(CLEAR)) set outline color to black SDL SetRenderDrawColor( TheGame Instance() gt getRenderer(), 0, 0, 0, 255) draw the hex outline SDL RenderDrawLines( TheGame Instance() gt getRenderer(), corners 2, HEX NUMBER OF CORNERS 2) or SDL RenderDrawLine( TheGame Instance() gt getRenderer(), corners 2 .x, corners 2 .y, corners 3 .x, corners 3 .y) SDL RenderDrawLine( TheGame Instance() gt getRenderer(), corners 3 .x, corners 3 .y, corners 4 .x, corners 4 .y) SDL RenderDrawLine( TheGame Instance() gt getRenderer(), corners 4 .x, corners 4 .y, corners 5 .x, corners 5 .y) Just for clarity, it still occurs in spots where there should be a drawn line. This is a shot with the above code"} {"_id": 19, "text": "In SDL, what is the difference between using a Surfaces and a Renderer? I am new to SDL and I've been following some tutorials in one tutorial he used Surfaces (a window surface and image surface) and a BlitSurface function to draw images without using any renderer (used SDL Image library for JPG, PNG etc.). And in another tutorial, he used a Renderer. What's the difference between those two? It seemed to me they do the same thing but I'm assuming if they were the same, one wouldn't exist."} {"_id": 19, "text": "How can I perform a masked erase in SDL2? I'm trying to implement some shadow lighting effects in my 2D project, and I've concluded that if there is an easy way to perform a masked erase on an SDL Texture, it would make the drawing operations quite cheap. Let's say I have a texture of the part of the level where light is not meant to be rendered. I also have a texture with my \"light map\" I want to use this to just draw omni lights from my light sources. Then I want to use the first image to 'subtract' the portions of the light map that are not to be rendered on the final scene. Then I draw my \"light map\" texture on top of my scene, with additive blending enabled. This sounds like a good theory in my head, but I can't see any functions in the SDL2 API that let me do masked erase from a texture. Am I overlooking something? Does anything like this exist?"} {"_id": 19, "text": "SDL2 for hardware accelerated graphics? I am attempting to make a 3d game using SDL2 just to learn and have a bit of fun. I was wondering if there is any way to get SDL2 do calculations on GPU. I have read that SDL2 Textures uses GPU for calculation, but is there any way to get it to do calculations from my functions using GPU? For example, if I have a function multiplyVectorWithMatrix, and there is a bunch of additions going on in that function, how would I get SDL2 to do those additions using GPU rather than CPU?"} {"_id": 19, "text": "Luminance increase in SDL We have managed to create grayscale picture using the following snippet of codes in SDL. What we need to do now is how to first convert into YUV or YCrCb for it be able to set the luminance value and thereafter back into RGB? const unsigned int gray (component1 component2 component3) 3 const int gray rgb SDL MapRGB(original gt format, gray, gray, gray)"} {"_id": 19, "text": "State machine in C for SDL game I want to create a state machine for menu in my SDL game. So this is my code without the SDL I just want to ask if this is a good way to create it. here is a code include lt stdio.h gt include lt windows.h gt enum states Menu, Game, Game over, Exit int main() int game is running 1 enum states state Menu while(game is running 1) switch(state) case Menu state Game printf( quot menu screen with play and exit button. n quot ) need to add if exit or play is pressed if exit then exit program if play than you know... break case Game state Game over printf( quot after play button is pressed game screen will show up. n quot ) after this i will come back to menu. break case Game over state Exit printf( quot screen after game. n quot ) break case Exit printf( quot turn game off. n quot ) this will be in the if function with a game. game is running 0 break Sleep(1000) sleep for a second just for test return 0"} {"_id": 19, "text": "SDL Detect change score I have this in my loop , it works but I get verry low fps and game is working in slow motion while (!done) Check for events done processEvents(window, amp player) updateLogic( amp player) sprintf(buffer, \"SCORE d\", player.currentScore) textSurface TTF RenderText Solid(font, buffer, color) text SDL CreateTextureFromSurface(renderer, textSurface) SDL QueryTexture(text, NULL, NULL, amp textW, amp textH) SDL FreeSurface(textSurface) doRender(renderer, amp player) SDL DestroyTexture(text) I think I need to update those 2 only when score is changing , not every frame..and I don't know how to do it. textSurface TTF RenderText Solid(font, buffer, color) text SDL CreateTextureFromSurface(renderer, textSurface)"} {"_id": 19, "text": "SDL TTF render variable This is the way I render the score in my main game , and I made this new project to understand how to use it... It works , the score is updated and it display on the screen but the problem is memory... it increase forever , from 20mb when I start untill it runs out of memory..it nevers stop. And in the main game it's working at 2fps... I hate TTF I just can't understand how it works and how should I do it... every tutorial is in c and I have to make the game in pure C for college...Help. include lt stdlib.h gt include lt stdio.h gt include lt conio.h gt include lt SDL.h gt include lt SDL ttf.h gt include lt SDL image.h gt int main(int argc, char argv) bool quit false SDL Event event SDL Init(SDL INIT VIDEO) TTF Init() SDL Window window SDL CreateWindow(\"Example\",SDL WINDOWPOS UNDEFINED, SDL WINDOWPOS UNDEFINED, 640,480, 0) SDL Renderer renderer SDL CreateRenderer(window, 1, 0) SDL Surface surface SDL Texture texture int score 0 char buffer 50 int texW 0 int texH 0 TTF Font font TTF OpenFont(\"font3.ttf\", 25) SDL Color color 255, 255, 255 while (!quit) SDL RenderClear(renderer) SDL WaitEvent( amp event) switch (event.type) case SDL QUIT quit true break score 100 sprintf(buffer, \"SCORE d\", score) surface TTF RenderText Solid(font, buffer, color) texture SDL CreateTextureFromSurface(renderer, surface) SDL QueryTexture(texture, NULL, NULL, amp texW, amp texH) SDL FreeSurface(surface) SDL Rect dstrect 0, 0, texW,texH SDL RenderCopy(renderer, texture, NULL, amp dstrect) SDL RenderPresent(renderer) SDL DestroyRenderer(renderer) SDL DestroyWindow(window) SDL DestroyTexture(texture) TTF CloseFont(font) TTF Quit() SDL Quit() return 0"} {"_id": 19, "text": "How to alter image pixels of a wild life bird? Hello so I was hoping someone knew how to move or change color and position actual image pixels and could explain and show the code to do so. I know how to write pixels on a surface or screen surface usigned int ptr static cast lt unsigned int gt (screen pixels) int offset y (screen gt pitch sizeof(unsigned int)) ptr offset x color But I don't know how to alter or manipulate a image pixel of a png image my thoughts on this was How do I get the values and locations of pixels and what do I have to write to make it happen? Then how do I actually change the values or locations of those gotten pixels and how do I make that happen? any ideas tip suggestions are also welcome! int main(int argc , char argv ) SDL Surface Screen SDL SetVideoMode(640,480,32,SDL SWSURFACE) SDL Surface Image Image IMG Load(\"image.png\") bool done false SDL Event event while(!done) SDL FillRect(Screen,NULL,(0,0,0)) SDL BlitSurface(Image,NULL,Screen,NULL) while(SDL PollEvent( amp event)) switch(event.type) case SDL QUIT return 0 break SDL Flip(Screen) return 0"} {"_id": 19, "text": "Multiple keypresses causing wierd results in SDL I have been building a pong clone. I've been using a mixture of peoples different code to understand the way they structure their games as well as reading on game patterns. Currently I've gotten to draw a paddle on the screen and the player can move it with the keyboard no problem. The issue comes when a player presses a button that is not 'Up' or 'Down'. For instance when the player holds the 'Up' key the paddle travels upwards, but if they simultaneously hold the 'Right' key it causes the paddle to fly downwards at a much greater speed. My keyboard checking code is void GameLoop Input(SDL Event amp ev) if (ev.type SDL KEYDOWN) if (ev.key.keysym.scancode SDL SCANCODE DOWN) player1 gt IsMoving(true) player1 gt velocity 10 if (ev.key.keysym.scancode SDL SCANCODE UP) player1 gt IsMoving(true) player1 gt velocity 10 else if (ev.type SDL KEYUP) if (ev.key.keysym.scancode SDL SCANCODE DOWN) player1 gt IsMoving(false) player1 gt velocity 0 if (ev.key.keysym.scancode SDL SCANCODE UP) player1 gt IsMoving(false) player1 gt velocity 0 The GameLoop is ran within loop that is configured to run at 60FPS. You can see this in this code block here int main(int argc, char argv) Initialise the app and SDL App app(SDL INIT VIDEO) GameLoop game double lastTime 0.0, currentTime SDL Event e while (app.isRunning()) if (SDL PollEvent( amp e)) if (e.type SDL QUIT) app.exit() currentTime SDL GetTicks() 1000.0 if (currentTime gt lastTime 0.01666667) game.Input(e) game.Update() game.Render() lastTime currentTime return 0 This is the paddles update code void Paddle Update() if(moving true) rect.y velocity velocity 50 X rect.x Y rect.y I'm unsure of what is causing the paddle to behave so strangely. Any insight given into this problem or even just the way I've approached this problem would be appreciated."} {"_id": 19, "text": "What exactly does SDL RenderSetClipRect do? I assumed that this function would move the area which is clipped out of conceptual space and copied onto the renderer (and subsequently drawn to the window) i.e. change the origin of rendering but it doesn't seem to do this. Anybody know how it works?"} {"_id": 19, "text": "How to make texture for text displaying using SDL ttf with good performance? In my game, there are many units and for each units there's an information widget attached next to them. I use SDL as the game rendering engine. I currently want to display their ID for debugging purposes. However, for each unit, I create a texture with their ID, I render it, then I destroy it. Needless to say that when there are about 40 units on my screen, the game gets pretty laggy (if its any indication, my game currenly weights 25 MB) How can I get over this?"} {"_id": 19, "text": "Memory leak around SDL FreeSurface When I call my tile engine function, the amount of memory my program uses begins to spike at about 80 90 megabytes per second. The memory use continues to go up until the program crashes. The function is below. After tinkering with it, I figured out that I could reduce this bricking to about 15 megabytes per second if I called SDL FreeSurface every time I ran the function. But this confused me, because I thought that you are only supposed to use SDL FreeSurface when the program exits so that the images don't continue to occupy the memory. if I don't call SDL FreeSurface before I blit the tiles, do the previously blitted tiles continue to exist? If I don't how do I fix the aforementioned bug? The edit I made to bring the memory bricking down to 15 megabytes per second is commented out. SDL Surface loadedTile NULL SDL Surface modelIMAGE NULL void enviroment blitTiles(SDL Surface windowENVIRO, int tileAmount, int tileType , int tileXenviro, int tileYenviro, bool quitTiles) HDcounter 1 if(loadedTile ! NULL) SDL FreeSurface(loadedTile) loadedTile IBFobjectENVIRO.loadIMG(\"tileClipSheet.png\") for(int tiles 0 tiles lt tileAmount tiles ) switch(tileType tiles ) Black square (unpassable) case 1 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 0, 0, 75, 75) HDcounter 1 forbiddenX HDcounter tileXenviro 75 forbiddenY HDcounter tileYenviro forbiddenSpriteWidth HDcounter 75 forbiddenSpriteHeight HDcounter 75 forbiddenSpriteDepth HDcounter 75 break Grey square case 2 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 75, 0, 75, 75) break Brown square case 3 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 150, 0, 75, 75) break Invisible square (unpassable) case 4 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 225, 0, 75, 75) HDcounter 1 forbiddenX HDcounter tileXenviro 75 forbiddenY HDcounter tileYenviro forbiddenSpriteWidth HDcounter 75 forbiddenSpriteHeight HDcounter 75 forbiddenSpriteDepth HDcounter 75 break tileXenviro 75 if(tileXenviro gt level1ObjectENVIRO.level1Width) tileYenviro 75 tileXenviro tileXenviro level1ObjectENVIRO.level1Width if(quitTiles true) SDL FreeSurface(loadedTile)"} {"_id": 19, "text": "What does FPSManager.lastticks stand for in SDL gfx? I'm having trouble finding documentation on SDL gfx, and I can't figure this out. I've managed to use SDL gfx to automatically cap the framerate, and I it's working a lot better than my manual attempt (combining SDL Delay and SDL Getticks). Now I've been trying to learn more about it, and I stumbled onto something. Here's the whole struct typedef struct Uint32 framecount float rateticks Uint32 lastticks Uint32 rate FPSmanager Most variables in this struct are pretty straightforward, but I have no idea of what lastticks stands for. Does anyone know?"} {"_id": 19, "text": "Multiple keypresses causing wierd results in SDL I have been building a pong clone. I've been using a mixture of peoples different code to understand the way they structure their games as well as reading on game patterns. Currently I've gotten to draw a paddle on the screen and the player can move it with the keyboard no problem. The issue comes when a player presses a button that is not 'Up' or 'Down'. For instance when the player holds the 'Up' key the paddle travels upwards, but if they simultaneously hold the 'Right' key it causes the paddle to fly downwards at a much greater speed. My keyboard checking code is void GameLoop Input(SDL Event amp ev) if (ev.type SDL KEYDOWN) if (ev.key.keysym.scancode SDL SCANCODE DOWN) player1 gt IsMoving(true) player1 gt velocity 10 if (ev.key.keysym.scancode SDL SCANCODE UP) player1 gt IsMoving(true) player1 gt velocity 10 else if (ev.type SDL KEYUP) if (ev.key.keysym.scancode SDL SCANCODE DOWN) player1 gt IsMoving(false) player1 gt velocity 0 if (ev.key.keysym.scancode SDL SCANCODE UP) player1 gt IsMoving(false) player1 gt velocity 0 The GameLoop is ran within loop that is configured to run at 60FPS. You can see this in this code block here int main(int argc, char argv) Initialise the app and SDL App app(SDL INIT VIDEO) GameLoop game double lastTime 0.0, currentTime SDL Event e while (app.isRunning()) if (SDL PollEvent( amp e)) if (e.type SDL QUIT) app.exit() currentTime SDL GetTicks() 1000.0 if (currentTime gt lastTime 0.01666667) game.Input(e) game.Update() game.Render() lastTime currentTime return 0 This is the paddles update code void Paddle Update() if(moving true) rect.y velocity velocity 50 X rect.x Y rect.y I'm unsure of what is causing the paddle to behave so strangely. Any insight given into this problem or even just the way I've approached this problem would be appreciated."} {"_id": 19, "text": "Background color gradient with SDL I want to create a menu for a game using a color gradient as the background. Is there a way to create a gradient background instead of using an image for it (since I don't know what size the window will be, using an image is no option). Please note I need to achieve this using only the C standard library and the SDL, no other library and no C ."} {"_id": 19, "text": "Separating logic update from render drawing code in a single thread using sleep I've read that the speed of game objects should not be hindered by FPS but instead should be based on time. How can I seperate the update draw code to maximize performance without limiting the drawing rate and provide a constant logic update rate based on time? My current pseudo code is as follows loop draw() if (ticksElapsed() gt 100) update() ticks ticksElapsed() The problem is the drawing code hinders the performance of the update() rate. And it consumes 100 cpu because if sleep is thrown in, it throws off both drawing logic functions. I am also using SDL and it doesn't seem to have a vsync option. I've also heard of the terms fixed and variable time stepping however I'm not sure how that can be done with sleep()"} {"_id": 19, "text": "Update and Render logic with interpolation I am working with C and SDL2 and just wanted some insight as to how to properly apply interpolation to the rendering. EDIT some clarification, update() input() and render() are just hypothetical stubs, the real code is messy and long as I learn SDL2. while (!quit) current SDL GetTicks() elapsed current previous previous current lag elapsed input() while (lag gt ms per update) update() lag ms per update interpolation (float)lag (float)ms per update printf(\"Interploation f r n\", interpolation) render(interpolation) This is something that has always kind of baffled me lets say that in update() if SPACE pressed we start a jump animation and movement. So sprite.y 2 to move it. Where does that movement of one pixel happen? Does it happen in update()? If the movement happens in update() then how do i properly apply the interpolation in render() since my item has already been moved (during the update)? Lets say i have a bullet at (x 10, y 10) It's velocity is 10 pixels per update. use clicks button to shoot first update bullet is moved to (x 20, y 10) render(interpolation) lets say it is 0.5) lots of on screen lag from awesome effects second update bullet is moved to (x 30, y 10) third update bullet is moved to (x 40, y 10) render(interpolation) lets say it is .09 from lots of lag How is the interpolation value applied to the bullet so that it appears to pass smoothly across the screen. What information is known during render to apply the interpolation? Would a struct containing the origin point, current velocity (or amount moved since last render), and current location suffice?"} {"_id": 19, "text": "Redefining the SDL rect struct Upon checking the docs of SDL (1.2) I saw that the SDL Rect struct defines the x and y as Sint16. I'm making a bitmap font text scroller and I need those specifically to be unsigned ints because the text does need to go offscreen, yet still using the same struct because the SDLBlit method needs it. I tried creating my own and typecasting it as an SDL Rect but that didn't work. Any ideas? Also, to be more clear. The string of text scrolls to the left, therefore the first letter of my text does indeed go off screen but the rest doesn't. I assumed this was the problem. for(int i 0 i lt strlen(string) i ) SDL Blitsurface(bitmapsurface, rects chars i , screen, destrect) destrect.x 8"} {"_id": 19, "text": "How to alter image pixels of a wild life bird? Hello so I was hoping someone knew how to move or change color and position actual image pixels and could explain and show the code to do so. I know how to write pixels on a surface or screen surface usigned int ptr static cast lt unsigned int gt (screen pixels) int offset y (screen gt pitch sizeof(unsigned int)) ptr offset x color But I don't know how to alter or manipulate a image pixel of a png image my thoughts on this was How do I get the values and locations of pixels and what do I have to write to make it happen? Then how do I actually change the values or locations of those gotten pixels and how do I make that happen? any ideas tip suggestions are also welcome! int main(int argc , char argv ) SDL Surface Screen SDL SetVideoMode(640,480,32,SDL SWSURFACE) SDL Surface Image Image IMG Load(\"image.png\") bool done false SDL Event event while(!done) SDL FillRect(Screen,NULL,(0,0,0)) SDL BlitSurface(Image,NULL,Screen,NULL) while(SDL PollEvent( amp event)) switch(event.type) case SDL QUIT return 0 break SDL Flip(Screen) return 0"} {"_id": 19, "text": "SDL2 jagged staircase edges I am using SDL2 and SDL2 Image to render png images. When I rotate the textures, they turn out very ugly, like this This is the code responsible for the rotation and alpha mod. SDL Rect srcRect SDL Rect destRect srcRect.x width currentFrame srcRect.y height currentRow srcRect.w destRect.w width srcRect.h destRect.h height destRect.x x destRect.y y SDL SetTextureAlphaMod(m textureMap id , alpha) SDL RenderCopyEx(pRenderer, m textureMap id , amp srcRect, amp destRect, 10.0, 0, flip) Do I need to set a blendmode too?"} {"_id": 19, "text": "What does FPSManager.lastticks stand for in SDL gfx? I'm having trouble finding documentation on SDL gfx, and I can't figure this out. I've managed to use SDL gfx to automatically cap the framerate, and I it's working a lot better than my manual attempt (combining SDL Delay and SDL Getticks). Now I've been trying to learn more about it, and I stumbled onto something. Here's the whole struct typedef struct Uint32 framecount float rateticks Uint32 lastticks Uint32 rate FPSmanager Most variables in this struct are pretty straightforward, but I have no idea of what lastticks stands for. Does anyone know?"} {"_id": 19, "text": "How to simply print (write) text on a Surface in SDL.NET? as i told in previous question, i'm using SDL.NET (wrapper in C of SDL). Unfortunately the API website is down so i'm trying to learn it by myself. I would like simply to print text on my screen surface ... i don't know how to do! My goal is to print variable status values, to \"debug\" directly on the run and on the screen (in the lower corner for example). Can somebody help me ? Thank you"} {"_id": 19, "text": "SDL mouse wheel not picking up Running Ubuntu 11.04, SDL 1.2 trying to pickup mouse wheel up down movement with this (stripped down) code int main( int argc, char argv ) SDL MouseButtonEvent mousebutton NULL while ( !done ) if(mousebutton ! NULL amp amp mousebutton gt button SDL BUTTON LEFT) yrot 0.75f else if(mousebutton ! NULL amp amp mousebutton gt button SDL BUTTON RIGHT) yrot 0.75f else if(mousebutton ! NULL amp amp mousebutton gt button SDL BUTTON WHEELUP) xrot 0.75f else if(mousebutton ! NULL amp amp mousebutton gt button SDL BUTTON WHEELDOWN) xrot 0.75f while ( SDL PollEvent( amp event ) ) switch( event.type ) case SDL MOUSEBUTTONDOWN mousebutton amp event.button break case SDL MOUSEBUTTONUP mousebutton NULL break default break return 0 strange thing is, scrolling with the mouse button does nothing, but if I hold down a mouse button or two and then move the mouse it hits the SDL BUTTON WHEEL code occasionally. This honestly reeks of a pointer issue, which would make sense since I've been spoiled with C for the past couple years, but I am just not seeing it. How do i correctly find mouse scroll events in SDL?"} {"_id": 20, "text": "Getting .mesh .skeleton from Blender2Ogre export I have downloaded the add on blender2ogre from this source http code.google.com p blender2ogre And I have created a simple mesh, with walking animation (similar to the gingerbreadman tutorial). My question is, whenever I want to export the project, I can only see the .scene export format. There is no option whatsoever to export as .mesh and .skeleton. Also, how can I export the walking animation separately, in other words, if my project have couple more animation, how can i separate those during export?"} {"_id": 20, "text": "How do you combine multiple meshes into one in Blender? I need to combine multiple meshes into one in Blender 2.8 (Just make them into a single mesh that looks like all of them in their normal positions). I am doing this mostly for performance improvement in my game, since the teeth are all separate. Does anyone know how to do this?"} {"_id": 20, "text": "Importing materials from blender to UE4 So my problem is that I have a nice green glass material in blender which I imported to UE4 (4.8.1) but in the editor the material was just a simple green colour. I have no idea what I should do to fix this problem. I appreciate any help. If you need any more details or pictures, let me know. Thank you Glass in blender Material in blender Glass in UE4 Material in UE4"} {"_id": 20, "text": "frustum culling and exporting a big scene model Let's assume that I created in Blender a race track with landscape. I can export it to single wavefront obj file and then load in my graphics engine using assimp but it doesn't allow to use frustum culling. Should I split such big scene too seperate objects or some model formats allow to split object within single file. How graphics engines load such big scenes ? Do you know some useful techniques articles ?"} {"_id": 20, "text": "Best way to do headshot decapitation? I'm using UE4 and blender. I was wondering what the process is of preparing in the 3D software and then making a head burst animation upon headshot. I don't want to do destructible meshes because they are sharp jagged fragments... I want it to literally burst and splash blood. How can I do this? Any support is appreciated."} {"_id": 20, "text": "Importing a File Containing Two Objects from Blender into Unity Leads to a Single GameObject Not Two I have two separate objects in a Blender file (say a cube and a sphere). Unity import this file (OBJ type) as a single gameObject which is not want I want. I want cube and sphere to be two separate gameObjects."} {"_id": 20, "text": "Blender baking normal map weird colors I have a metal drum mesh, and when I bake its normal map, I get the weird colors (see attached pic). I'm talking about the horizontal gradient shift of color. There's no deformation like that on my mesh, how come the colors are like that? I've tried various spaces (camera, world, etc) but it's still bad (though the horizonal gradient changes with each one). Also tangent space returns a blocky blue color all over. Can someone please tell me how to get a good normal map out of my mesh? UPDATE Solved, thank you very much Luke B. There's still the question of scaling one of the two overlapping versions a bit (the low res one for example) in order to get really good results, but that's how it's supposed to be done. UPDATE 2 After further following the advices of Luke B, I've used multiresolution modifier on my low res mesh, and baked from there. It looks much better than before, the color artifacting are down to a minimum, really, with some corrections in GIMP it's quite usable"} {"_id": 20, "text": "Can't move bone on blender. \"Location\" transform grayed out I'm trying to move a bone on Blender. I can't do anything with it at all. I've searched through the menus and noticed the Location transform is grayed out."} {"_id": 20, "text": "Stretched textures in Blender First of all I'm relatively new to Blender. I discovered a weird bug in Blender 2.78c. On my object some textures are stretched although they are UV mapped. Since I have no clue why this is happening I took some screenshots which hopefully explain the problem. I tried various things, but found no way to solve this. Things I tried Unwrap again Apply Rotation and scale Manually adjusting verts in UV map Looking for \"dead\" verts somewhere in the model Does anyone know this strange behavior? Edit I uploaded my .blend file http pasteall.org blend index.php?id 47124 merged screenshots due to low reputation P"} {"_id": 20, "text": "I followed a youtube timelapse video to make same 3d model in blender, Can I use this in my game? I saw a youtube timelapse video about making a car 3d model, I liked it and followed the same, I design almost same looking model (90 same), Can I use this in my game? There is no license mentioned on video, the creator of video has just written 'Just for fun' in description of youtube video. Update As per my understanding if we download or copy paste a copyrights protected asset, we will need permission of its author, but I am neither downloading nor copy pasting anything, I am simply just seeing a video and making something similar asset, so do I really need a permission of the video creator and however he hasn't mentioned any license term also in the video."} {"_id": 20, "text": "Why is my model exported from Blender vanishing when using it in UE4 mobile? My 3D models and animation vanishes when I preview it using the mobile view port. However they work just fine for the desktop viewport. I usually model the characters using MakeHuman and import them into Blender. In Blender I animate them and then I import the model animation into UE4. The problem is that my model animation works when I preview it using the shader meant for desktop amp consoles. When I preview my animation using the openGLES2 shader, my model vanishes. Anything I import form belnder vanishes when I view it in a mobile viewport. I cant figure out why this is so? Have any of you experienced this before ? Can you guys let me know how I can correct this issue? Also, if I upload the models from MakeHuman into UE directly, I can upload the files properly in UE. But, when I try the workflow MakeHuman Blender UE with not much modifications to the models in Blender, the models are not visible in the openGLES2 shader. I am not sure why this is happening in Blender and why the models coming out if it is affected. Any help would be appreciated."} {"_id": 20, "text": "Correct way to export from blender to ogre format? When I export from blender to ogre using the blender2ogre add on, I'm not getting anything besides a scene most of the time and when I get a mesh I never get a material. Is there something wrong with my export procedure or what else could I be doing wrong? Update I can export the basic cube from blender to ogre but when I download a model and try to export it I don't get the meshes. Update 2 I tried again and selecting the model in Blender does the difference like the answer here says. I can export an alien and get the mesh and material I rename the files ls workspace DungeonWorld2 assets objects creatures alien Cube.001.mesh Material.002.material Material.005.material Cube.001.mesh.xml Material.003.material Cube.001.skeleton.xml Material.004.material dev dev OptiPlex 745 ls workspace DungeonWorld2 assets objects creatures alien alien.mesh Material.002.material Material.005.material alien.mesh.xml Material.003.material alien.skeleton.xml Material.004.material dev dev OptiPlex 745 But how do I actually load the material since the alien now turns up in the game with no material but it does render the mesh Spatial model3 assetManager .loadModel(\"objects creatures alien alien.mesh.xml\") model3.scale(0.3f, 0.3f, 0.3f) model3.setLocalTranslation( 40.0f, 3.5f, 20.0f) rootNode.attachChild(model3)"} {"_id": 20, "text": "Blender modelling for a C game? I want to know if it were possible to integrate models created with Blender into a game written in solely C ."} {"_id": 20, "text": "What's the rationale for different coordinates systems? Could someone explain to me why Blender and other 3D modeling apps switch axes? If I export model with Blender, then exporters do following things for the same model The 3DS format applies this transform matrix 1.0, 0.0, 0.0, 0.0 , 0.0, 0.0, 1.0, 0.0 , 0.0, 1.0, 0.0, 0.0 , 0.0, 0.0, 0.0, 1.0 The Collada format applies this transform matrix 1.0, 0.0, 0.0, 0.0 , 0.0, 0.0, 1.0, 0.0 , 0.0, 1.0, 0.0, 0.0 , 0.0, 0.0, 0.0, 1.0 The OBJ format (default) transforms axes just like a transform matrix was applied, but OBJ format (Forward Y, Up Z) gives the original values that I see in Blender. The PLY format also does nothing and I get same values I see in Blender. PS Question was edited. I do not ask why there are different coordinate systems. I understand that. I do not understand why Blender and other switch axis silently when model is exported. People in comments say It is easy to fix model after export There are people who needs that. Actually I never seen these people and if it easy to fix then it is more easy to switch axis for those who really need that switch. I would love to hear someone who say that axis switch is important and he she needs in real work (not in theory)"} {"_id": 20, "text": "Where is the \"Scripts Window\" menu in Blender 2.59? I'm trying to import a script into Blender, and I have the script in my directory and I pushed F8 to reload scripts, but the instructions for running this script say In the \"Scripts Window\" run \"Scripts Export OGRE Meshes\". I've seen other similar instructions for other scripts. But the toolbar only contains \"File Add Render Help.\" Changing the \"screen layout\" to Scripting doesn't reveal any additional options, either. I'm sure I'm just missing something obvious. Please help!"} {"_id": 20, "text": "How are 3D game levels built? I am wondering what is the best most common practice in 3D games (mostly shooters) like Quake or Doom. How are the levels built? With larger, open spaces the answer is probably some kind of terrain editor, that is what I understand. But what about things like houses or closed areas? I see two main solutions. One is to make a whole house, factory, dungeon (or generally a level) in other tool, like Blender, and then put it in the game. Other is to make the most simple elements like walls, floor, doorways and make the level from them (like Lego blocks). Is one of the ways more common? More \"industry standard\"? Are there some obvious advantages or disadvantages?"} {"_id": 20, "text": "What's the rationale for different coordinates systems? Could someone explain to me why Blender and other 3D modeling apps switch axes? If I export model with Blender, then exporters do following things for the same model The 3DS format applies this transform matrix 1.0, 0.0, 0.0, 0.0 , 0.0, 0.0, 1.0, 0.0 , 0.0, 1.0, 0.0, 0.0 , 0.0, 0.0, 0.0, 1.0 The Collada format applies this transform matrix 1.0, 0.0, 0.0, 0.0 , 0.0, 0.0, 1.0, 0.0 , 0.0, 1.0, 0.0, 0.0 , 0.0, 0.0, 0.0, 1.0 The OBJ format (default) transforms axes just like a transform matrix was applied, but OBJ format (Forward Y, Up Z) gives the original values that I see in Blender. The PLY format also does nothing and I get same values I see in Blender. PS Question was edited. I do not ask why there are different coordinate systems. I understand that. I do not understand why Blender and other switch axis silently when model is exported. People in comments say It is easy to fix model after export There are people who needs that. Actually I never seen these people and if it easy to fix then it is more easy to switch axis for those who really need that switch. I would love to hear someone who say that axis switch is important and he she needs in real work (not in theory)"} {"_id": 20, "text": "Blender wont export textures (materials) to OGRE3D .mesh i am exporting a model from BLENDER to OGRE3D using the blender2ogre script. the desigre output is a single .mesh file but i know there should be also materials scripts that i should copy to my ogre path. the problem is that blender does not export those files for me it export only 1 mesh file (after i joined all objects) this is the model. in blender it looks fine but in my demo Ogre app it looks like i can use a little help here."} {"_id": 20, "text": "Blender modelling for a C game? I want to know if it were possible to integrate models created with Blender into a game written in solely C ."} {"_id": 20, "text": "Stretched textures in Blender First of all I'm relatively new to Blender. I discovered a weird bug in Blender 2.78c. On my object some textures are stretched although they are UV mapped. Since I have no clue why this is happening I took some screenshots which hopefully explain the problem. I tried various things, but found no way to solve this. Things I tried Unwrap again Apply Rotation and scale Manually adjusting verts in UV map Looking for \"dead\" verts somewhere in the model Does anyone know this strange behavior? Edit I uploaded my .blend file http pasteall.org blend index.php?id 47124 merged screenshots due to low reputation P"} {"_id": 20, "text": "How are 3D game levels built? I am wondering what is the best most common practice in 3D games (mostly shooters) like Quake or Doom. How are the levels built? With larger, open spaces the answer is probably some kind of terrain editor, that is what I understand. But what about things like houses or closed areas? I see two main solutions. One is to make a whole house, factory, dungeon (or generally a level) in other tool, like Blender, and then put it in the game. Other is to make the most simple elements like walls, floor, doorways and make the level from them (like Lego blocks). Is one of the ways more common? More \"industry standard\"? Are there some obvious advantages or disadvantages?"} {"_id": 20, "text": "What's the rationale for different coordinates systems? Could someone explain to me why Blender and other 3D modeling apps switch axes? If I export model with Blender, then exporters do following things for the same model The 3DS format applies this transform matrix 1.0, 0.0, 0.0, 0.0 , 0.0, 0.0, 1.0, 0.0 , 0.0, 1.0, 0.0, 0.0 , 0.0, 0.0, 0.0, 1.0 The Collada format applies this transform matrix 1.0, 0.0, 0.0, 0.0 , 0.0, 0.0, 1.0, 0.0 , 0.0, 1.0, 0.0, 0.0 , 0.0, 0.0, 0.0, 1.0 The OBJ format (default) transforms axes just like a transform matrix was applied, but OBJ format (Forward Y, Up Z) gives the original values that I see in Blender. The PLY format also does nothing and I get same values I see in Blender. PS Question was edited. I do not ask why there are different coordinate systems. I understand that. I do not understand why Blender and other switch axis silently when model is exported. People in comments say It is easy to fix model after export There are people who needs that. Actually I never seen these people and if it easy to fix then it is more easy to switch axis for those who really need that switch. I would love to hear someone who say that axis switch is important and he she needs in real work (not in theory)"} {"_id": 20, "text": "I have problems for export from Blender to Ogre3D I don't speak good english, but I will try.. I need to make a game for my University. Exists lot of models in blendswap but, I have problem for export. Many of these models have extra objects, such as a floor, I need to remove those extra objects and export the weapon and hand. My idea is Import a weapon model with hand with 2 actions, reload and shoot. How can I do it? I love this models http www.blendswap.com blends view 85257 or 67870 or 70607 (change number in link, because I don't can put more 1 link, because I'm level noob)"} {"_id": 20, "text": "Blender Bones get enlarged in export import process I have a rig in blender that I want to export into a different blender project. For some reason, when I do that, some of the bones get enlarged. All the scales are applied. Why might this be happening? I've no clue why this might be happening, as this problem seems exclusive to this project and one other project, where one bone out of the whole armature gets enlarges, but here is the information I can provide Some differences between the projects where this happens and the others is that the ones where this does happen have animations, and a pose library. However, this does not seem to cause the problem, as deleting the animations and poses doesn't change anything. This problem happens when I export import the project as an FBX. I usually export the project to unity and in order to compensate for the unity blender rotation, I follow this guide 1. I rotate the armature 90 on the x axis, apply rotation. Then rotate the armature 90 on the x axis but only apply the rotation to the mesh. I export the project as a FBX, with unity unit scale, no leaf bones, and the 3rd and 4th box under animations checked off. This also does not seem to cause the problem, as not rotating the armature and such doe not change anything."} {"_id": 20, "text": "How can I create a mesh with Blender which changes mid game? Take a situation where on the first half the player fights an enemy and after a cutscene, the player cuts off the hand of the enemy. How can I show him without his hand after this moment (when modeling it with the hands in Blender in a single skeletal mesh)? Do I have to make another skeletal mesh but without the hand? Similar to how in Assassin's Creed Origins where at the end of the snake quest after the cutscene Bayek losses his ring finger and remains without it all game. But in my case, the entire hand is removed."} {"_id": 20, "text": "Importing materials from blender to UE4 So my problem is that I have a nice green glass material in blender which I imported to UE4 (4.8.1) but in the editor the material was just a simple green colour. I have no idea what I should do to fix this problem. I appreciate any help. If you need any more details or pictures, let me know. Thank you Glass in blender Material in blender Glass in UE4 Material in UE4"} {"_id": 20, "text": "Blender Cycles materials not showing in Second Life I ran into a problem after trying to import my own creation into second life. While I am not new to 3D modelling with Blender and other programs, I have always only created things for fun. Now I have decided to import few of those creations into Second Life but the materials I have used do not display in the preview at all. I have used the Cycles Render. How do I solve my issue with Materials not displaying in Second Life after Exporting a Collada file from Blender Rendered in Cycles?"} {"_id": 20, "text": "Attempting to remove extra \"edges\" from truncated icosahedron lead to excessively global concequences I need a truncated icosahedron. Blender lets me do that with add gt mesh gt math function gt regular solid (assuming the extra plugin is installed.) So far so good. However, the mesh that is created does not use ngons. This means that each hexagon or pentagon face is cut by an unusable edge approximately through the middle. These extra quot lines quot destroy the visual symmetry I need for the wireframe. I have tried deleting the extra edges. This results in the in the removal of far more than just the offending edge. It blows a huge hole in the whole object. I have tried merging the two faces (which compose the pentagon or hexagon) into an ngon. Somehow this again ends up doing far more than just merge the two parts of the face. No matter what I try I get unintended effects that are far to global. I have also considered drawing fresh lines over only the desired edges. I cannot figure out how to do this either. I have also extracted the faces and edges with python, but those are too cumbersome to edit... and then what? How do I get a nice clean geometric wire Frame without distracting extra edges?"} {"_id": 20, "text": "Stretched textures in Blender First of all I'm relatively new to Blender. I discovered a weird bug in Blender 2.78c. On my object some textures are stretched although they are UV mapped. Since I have no clue why this is happening I took some screenshots which hopefully explain the problem. I tried various things, but found no way to solve this. Things I tried Unwrap again Apply Rotation and scale Manually adjusting verts in UV map Looking for \"dead\" verts somewhere in the model Does anyone know this strange behavior? Edit I uploaded my .blend file http pasteall.org blend index.php?id 47124 merged screenshots due to low reputation P"} {"_id": 20, "text": "How to edit WoW models with Blender? My situation is following, I am into role play, mostly me and my friends are using World of Warcraft. Since I am a bit into Blender too, I would like to try to edit some models(armor and weapon) for private use only(!). Problem is I have no idea how to import and export them. So far I have found only this forums.runicgames, but it looks very outdated, and I am not sure if it will work with Warlords of Dreanor extension. How would I go about exporting the models from WoW and importing them into Blender?"} {"_id": 20, "text": "To what platforms can the blender game engine build to? I used to use the BGE until I found that unity can build to lots of different platforms. What platforms does the BGE support?"} {"_id": 20, "text": "Blender to UDK 3 How to smooth Static Mesh I've created a bed cover model for my small game and here is how it looks like in blender http imgur.com T88Mnbs but whenever I import it to UDK it looks like this http imgur.com OMXBno3 it looks smooth in Blender but when I import to the Udk it doesn't Why is this happening? And I use .fbx to export from blender..."} {"_id": 20, "text": "How to edit WoW models with Blender? My situation is following, I am into role play, mostly me and my friends are using World of Warcraft. Since I am a bit into Blender too, I would like to try to edit some models(armor and weapon) for private use only(!). Problem is I have no idea how to import and export them. So far I have found only this forums.runicgames, but it looks very outdated, and I am not sure if it will work with Warlords of Dreanor extension. How would I go about exporting the models from WoW and importing them into Blender?"} {"_id": 20, "text": "How can I prevent resizing of an Ogre3D object once imported into jMonkeyEngine? I created an object in Blender Then I exported it as a mesh.xml file and attached it to the game scene Note The gray color is the ground. In the game I end up with have a smaller, horizontal tower. Any suggestions? Note I exported the file with \"Force Camera\", \"Force Lamps\" and \"Export Scene\" unchecked and \"Swap Axis x,y,z\"."} {"_id": 20, "text": "independent lighting per mesh in blender In Blender, is it possible to assign lighting objects effects exclusively to a single mesh? For instance, if I place two meshes next to each other, and two lights (one shining on each mesh), I would want each mesh to not cast a cast any shadow on the other. For example, in the following rendered image from a \"test\" star system view The rings are casting shadows on the right most planets. I want the rings to only cast shadows on their own planet. Is this possible?"} {"_id": 20, "text": "Getting .mesh .skeleton from Blender2Ogre export I have downloaded the add on blender2ogre from this source http code.google.com p blender2ogre And I have created a simple mesh, with walking animation (similar to the gingerbreadman tutorial). My question is, whenever I want to export the project, I can only see the .scene export format. There is no option whatsoever to export as .mesh and .skeleton. Also, how can I export the walking animation separately, in other words, if my project have couple more animation, how can i separate those during export?"} {"_id": 20, "text": "Best format for model with double UV sets I'd like to use first UV set as wrapping (or when some faces cover another on UV) diffuse color map and second UV set as baked ambient occlusion (packed to islands) map. It is possibly to use FBX or Collada .dae or other (what?) in this case? I read scene by Assimp library."} {"_id": 20, "text": "Regarding BGE (Blender Game Engine), is it possible to generate a single .exe file from multiple files linked together? Would any of you guys or gals know the answer, please? I know one can generate a .exe (windows executable) file from a single blend file. My question is very simple Can anyone generate a single .exe file from multiple blender files of a same project? For instance, say I have a project folder with several subfolders and files from my project game. Each folder has specific elements like scenes, models, textures, etc. They are all linked together to form the final game. Now I want to generate a single .exe file for my game. Is this possible? Or, rather, should I make an entire game inside a single .blend file? (It seems like a very unlikely arrangement, maybe even impossible, but I rather ask). Or maybe even create a master .blend file from where to link all data and when project is finished pack everything before generating the executable (.exe)?"} {"_id": 20, "text": "Locating different models in a single scene I have a curiosity. Say I wanted to create a big forest using Blender, in this forest I'd like to have a campfire or several campfires. What I could do is create the entire scene in Blender with campfires included and of course in engine I would add a fire effect to it. Now what I do not understand is how can I actually find the fireplaces' locations in the engine? Since it's all in one scene, I can't just say getLocation on the model. I guess what I'm asking isn't how to do it per say, but what the \"professional\" way is. Do professional game developers fiddle around with coordinates until they find it? Do they load the campfire on top of the scene as a separate model and move it until it fits the scene? Just in case it is important, I am using jMonkeyEngine."} {"_id": 20, "text": "Stitching terrain tiles made in Blender at runtime Background I'm making several individual terrain tiles inside of blender for use within a Unity 3D 5 game. Each tile is square and is made to represent a segment of a world. In game the tiles are randomly chosen and placed between each other. However these tiles do not always have matching sides. Why the tiles To allow for greater terrain sculpting possibilities such as caves, precision placed landmarks e.t.c. but still allow for a procedurally generated feeling randomly placed static tiles are used. There are mountain tiles and there are plane tiles. Mountain tiles have a more extreme terrain and are mostly next to other mountain tiles so that bigger mountains can be formed. Plane tiles are similarity placed next to other plane tiles. The game is \"low poly\" and so is the terrain. This makes it hard to have flat sides on every tile at the same height for easy \"stitching\". Concrete question How can I match these edges runtime to ensure that there are no visible tile edges?"} {"_id": 20, "text": "what are texcoord tags in mesh.xml file in Ogrexml format? I exported a 3d model from blender 2.79 and using ogrexml import export plugin. but the texture will crash and UV map not working in that format. I made the model by four parts head body hands shoes and they have 4 material and 4 textures, so I made a texture atlas for it and join them in a mesh to More optimization. I think removing other UV maps has a problem because when I check the model.mesh.xml in a note editor and every vertex has 3 texture coordinate tags and I compared it with a normal correct model that looks good in the blender and in ogrexml format, it has one texcoord tag inside of vertex tag. 1 what are texcoord tags? are they using for UV maps in ogrexml format? 2 how can I clear blend files from other unused uvMaps to avoid exporting them with the model?"} {"_id": 20, "text": "Stitching terrain tiles made in Blender at runtime Background I'm making several individual terrain tiles inside of blender for use within a Unity 3D 5 game. Each tile is square and is made to represent a segment of a world. In game the tiles are randomly chosen and placed between each other. However these tiles do not always have matching sides. Why the tiles To allow for greater terrain sculpting possibilities such as caves, precision placed landmarks e.t.c. but still allow for a procedurally generated feeling randomly placed static tiles are used. There are mountain tiles and there are plane tiles. Mountain tiles have a more extreme terrain and are mostly next to other mountain tiles so that bigger mountains can be formed. Plane tiles are similarity placed next to other plane tiles. The game is \"low poly\" and so is the terrain. This makes it hard to have flat sides on every tile at the same height for easy \"stitching\". Concrete question How can I match these edges runtime to ensure that there are no visible tile edges?"} {"_id": 20, "text": "Blender Edge Split Alternative What other options alternatives are there to \"edge split\" for smooth shading low poly game models. As I understand it, edge split does what it say's, its splits the mesh therefore increasing the vert count. I have considered manually marking the edges as sharp however I would imagine this leaves artifacts on the model(in game) ? Cheers."} {"_id": 20, "text": "Where is the \"Scripts Window\" menu in Blender 2.59? I'm trying to import a script into Blender, and I have the script in my directory and I pushed F8 to reload scripts, but the instructions for running this script say In the \"Scripts Window\" run \"Scripts Export OGRE Meshes\". I've seen other similar instructions for other scripts. But the toolbar only contains \"File Add Render Help.\" Changing the \"screen layout\" to Scripting doesn't reveal any additional options, either. I'm sure I'm just missing something obvious. Please help!"} {"_id": 20, "text": "what are texcoord tags in mesh.xml file in Ogrexml format? I exported a 3d model from blender 2.79 and using ogrexml import export plugin. but the texture will crash and UV map not working in that format. I made the model by four parts head body hands shoes and they have 4 material and 4 textures, so I made a texture atlas for it and join them in a mesh to More optimization. I think removing other UV maps has a problem because when I check the model.mesh.xml in a note editor and every vertex has 3 texture coordinate tags and I compared it with a normal correct model that looks good in the blender and in ogrexml format, it has one texcoord tag inside of vertex tag. 1 what are texcoord tags? are they using for UV maps in ogrexml format? 2 how can I clear blend files from other unused uvMaps to avoid exporting them with the model?"} {"_id": 20, "text": "Locating different models in a single scene I have a curiosity. Say I wanted to create a big forest using Blender, in this forest I'd like to have a campfire or several campfires. What I could do is create the entire scene in Blender with campfires included and of course in engine I would add a fire effect to it. Now what I do not understand is how can I actually find the fireplaces' locations in the engine? Since it's all in one scene, I can't just say getLocation on the model. I guess what I'm asking isn't how to do it per say, but what the \"professional\" way is. Do professional game developers fiddle around with coordinates until they find it? Do they load the campfire on top of the scene as a separate model and move it until it fits the scene? Just in case it is important, I am using jMonkeyEngine."} {"_id": 20, "text": "Exporting UV coords from Blender So I have searched on google and various other websites but I've not found an answer. The only ones I did find did not work. So my question is how do I get UV coords from blender (2.63)? Currently I'm writing my own custom file exporter, and so far have managed to export vertices and their normals. Is there a way to export the UV coords? N.B. I'm currently try to figure it out using a simple cube that is unwrapped and has a texture applied to it."} {"_id": 20, "text": "Blender arm rig not working the way it should I just bought a pair of arms from the unity asset store and imported them into blender, the IK seems to work just fine untill i use a Child of constraint on another bone(which is supposed to be a weapon) on the arm's wrist bone the bone rotates but it wont move. I'll leave a video of it right here, https www.youtube.com watch?v jfLmG2sQ 10 EDIT the wrist bone seems to follow the child WHEN i disconnect the wrists parent, but if i do that the IK doesnt work in general. Appreciate all help, thanks in advance )"} {"_id": 20, "text": "Blender modelling for a C game? I want to know if it were possible to integrate models created with Blender into a game written in solely C ."} {"_id": 20, "text": "What is the simplest way to export a bezier curve created in Blender to a text file? I have created a bezier curve in Blender. I'd like to export this curve to a text file. What I need is Control point handles, three points in total. Example 2.3333,4.3942, 55.333 , 0.3234, 2.4234, 4.0332 , 2.534, 6.S234, 12.0332 I have tried to export the scene in Collada format but it doesn't seems to include curves information. What is the easiest simplest way to export this curve to some readable text file format ?"} {"_id": 21, "text": "How should I manage multiple entities? Before I start making a game, I'm trying to figure out how I will manage things. One of the first things I'm not sure about is how to manage entities (enemy, player, projectile...) I'm going to be using either C, C , Java, or C One of the ideas I have is to use one array for projectiles and one for enemies. Each time I have a new entity, I grow my array. Here is the problem If player enemy is firing, that creates a new entity which means the projectile array is growing. Suppose its projectile 2053, when it hit something, I free it, then in my loop to check which projectiles are to do something, like getting closer to there target, I check if every of my array to see if its null, if not, check is trajectory. But the problem is that the array will grow each time a new projectile is fired, and I will get a memory problem at the end. So how should I manage my entities? I need an awnser that covers both object oriented and procedural, since I mainly do things in C."} {"_id": 21, "text": "What's the difference between a \"Gameplay Programmer\" and a \"Gameplay Engineer?\" I was reading some job descriptions from some AAA developers in the gaming industry, and I noticed there were jobs for \"Gameplay Programmers\" as well as \"Gameplay Engineers.\" Are those the same thing? Do they do the same thing?"} {"_id": 21, "text": "How to profile CPU and GPU performance if I have a monster PC? I'm going to upgrade my PC soon. I'm worried that I will no longer spot performance losses in my game because of the better specs. I can check memory usage easily, but how do I check and debug CPU and GPU usage? I used to rely on the framerate, but I guess that it is not accurate."} {"_id": 21, "text": "How should bots be recognised in a game? I'm interested in how bots are usually written. Here's my situation I plan to make an online 2D mecha game in HTML5, and the server side will be done with node. It is intended to be multiplayer, but I also want to make bots in case there aren't enough players. How does my game logic see them, as players or as bots? Is there a standard by which I should make them? Also, any general tips and hints will be OK."} {"_id": 21, "text": "What is an OO way for my input layer to act upon objects? I'm building a top down RPG specifically to practice Object Oriented thinking and design. I am keeping in mind coupling, single responsibility, and so forth. One design issue that's been bugging me is how to ultimately have objects talk while maintaining the loosest coupling possible. As an example, I'm designing the input class now, which will be made up of two layers, like so The conundrum is that I don't know how to bridge that gap between Input and HeroActor, which is initialized from the PlayState class, which is also where the hero.update() method is called. Let's say Keyboard has just executed public void keyPressed(KeyEvent e) switch(e.getKeyCode()) Some cases case KeyEvent.VK UP Assume InputEvent.INPUT1 is a defined enumeration in InputEvent inputHandler.passInput(InputEvent.INPUT1) break Some more cases I've basically landed here public class Input public void passInput(InputEvent e) switch(e) Some cases case InputEvent.INPUT1 ???????????????????? Some more cases My ideas have been Pass a reference to the instance of HeroActor to the Input object, then have Input directly call the moveUp() method on the HeroActor instance. case InputEvent.INPUT1 actor.moveUp() My instinct tells me this is bad OO design as it tightly couples the two classes. Make the instance of HeroActor global and basically do the same as above. Even worse OO design. Write a registerInput(Input inputHandler) function in the Actor class, like so public class HeroActor extends Actor Existing fields and methods private Input inputHandler public void registerInput(Input inputHandler) this.inputHandler inputHandler Still, then the HeroActor would have to poll the inputHandler every frame to find out if any actions have applied to it. I'm in the same situation trying to figure out how to write the collision engine without passing it specific references to the player's HeroActor instance or the dozens of EnemyActor instances in the PlayState constructor. Any help would be greatly appreciated. My request is not for specific code, but rather common techniques for handling the many objects in a game without ending up with a god object. I've seen some material suggesting an Observer pattern being applied for things like the input layer above, but before I go too far, I'd like some feedback from the community since I've got so many different answers among all of my Googling today."} {"_id": 21, "text": "Large game project, local variables I'm hoping that some experienced programmers can give me their point of view. I'm writing a large game in Windows with dx11. So far, I've got global objects of the class that interfaces with dx11, the class holding the position of the camera, the terrain data class, and a few other classes. In future, if I kept going with this way, I'd also have objects for all the game data, and so on. I'm thinking it might be best to rejig the code to only have local variables, because generally this is regarded as a Good Thing, but mainly because I personally have come to prefer using them. Here's some rough c ish pseudo code of how I imagine local variables would be implemented WinMain() cDirectX dx cCamera cam cTerrain terrain ... while (msg.message ! WM QUIT) ... gameLoop(dx, cam, terrain, ...) void gameLoop(cDirectX amp dx, cCamera amp cam, cTerrain amp terrain, ...) ... renderTerrain(dx, terrain) ... Is this (very roughly!) a good way to organise such a project? I suppose WinMain is the only function where the locals can be instantiated? The only disadvantage I can see is that top level function calls (by which I mean, functions like gameLoop(), functions at the bottom of the call stack) will have very long lists of arguments. Perhaps this doesn't matter. Thanks, Paul"} {"_id": 21, "text": "Should I use Game Engines to learn to make 3D games? HI i am a software engineering student in his second last year. I am proficient with C,C ,C and java programming languages, and being a student of engineering I have studied calculus, vectors etc in both 2D and 3D amp various other mathematical, probability and statistical topics. I have made several 2D games, my most recent being a Super Mario like game with side scrolling and multiple levels. Due to my these small game projects,i have become really interested in making games. So now i want to move ahead to learn to make games in 3D. Now I know that there are several game engines available which can take care of rendering details and other \"low level\" stuff for me... My Question is 1) Is it a good idea to learn to program everything yourself, from making 3D shapes, terrains (using polygons meshes) etc, to programming mechanism for collision detection, lighting etc, considering my motive is to learn how to make games in 3D (but am not too eager to get into the game industry quickly, want to build a solid foundation first) Or could I do without these details amp work on the abstraction level which the game engines (like UDK) provide ?? 3) If I should try to develop from scratch, then can anybody suggest which API to use Direct3D or OpenGL?? (which i would be more comfortable with, in light of my above mentioned skills) amp can anybody also give me references to some good books, reading materials, tutorials, etc to get me started?? (I wouldn't mind theory as long as it helps me make a sound foundation) Many Thanx in advance (for even reading my question, i know it's lengthy... but i need a DETAILED answer... D D )"} {"_id": 21, "text": "Game development Art vs Programming I'm a programmer and would like to get some perspective on the art content creation part of game development. Comparing a 2D platformer like Super Meat Boy and a high end game like Crysis 2, what do you think What is harder to do more likely to cause the project to fail Art or programming? Which will consume more time and take more people to work on?"} {"_id": 21, "text": "Random numbers inside instance (Game Maker) I've recently run into a weird problem. When I create instances through with(instance create) ... , I can always randomize their variables individually (inside ... ). However, when I try running randomize() random(...) inside their object (in one of the events), they are all synced. Please tell me this isn't a major Game Maker flaw and, most importantly, how do I fix this. Thank you!"} {"_id": 21, "text": "Are there cases where globals singletons are useful in game development? I know that having global variables or singleton classes creates cases that can be difficult to test manage and I have been busted in using those patterns in code but often times you gotta ship. So are there cases where global variables or singletons are actually useful in game development?"} {"_id": 21, "text": "How should I handle functions, where two classes have equal use? I'm working on a few features for a strategy engine I'm making. I'm trying to figure out the best spots to separate the components, as either option will provide the same amount of coupling, with the same effectiveness. For example, all players have a Damage component, a Player component, and a HealthBar component abstract class Damage protected abstract void sendDamage(Player targetPlayer, int rawDamage) public abstract int calculateRawDamage(Attack attackUsed) public abstract void receiveDamage(int rawDamage) class Player List lt Armor gt equippedArmor List lt Buffs gt currentBuffs public Damage damageComponent public List lt HealthBars gt healthBarComponents abstract class HealthBar can be inherited for mana or health bar protected Color color public float percent 0.0 1.0 When a player receives damage, I need to show a red number floating up from their head, indicating the amount of damage. This can either be implemented in HealthBar, or in Damage. It fits damage better, but then healing works in the same way, and wouldn't be called from damage. I could abstract damage into something like ChangeValue, which would change mana, health, etc in any direction, or I could use the abstract HealthBar class to show this number being changed. I'm trying to think of a general rule that would solve this and other problems, where two classes use the same function equally. This is an oversimplified version of my classes, but it makes more sense this way. How should I handle functions, where two classes have equal use?"} {"_id": 21, "text": "Looking for an elegant way to represent fixed parts of a randomly generated level map I'm coding from scratch a small experimental game on a medium sized random rectangular square tile map. (Say, a map of a dungeon.) There are several types of tiles (for example floor, wall, monster, boss, treasure, player etc.). There are no extra information stored in the map tiles, just tile type. Most parts of map are randomly generated. However there are several features that are to appear on every generated map in pre set places. Say, walls around the dungeon, boss locations, player spawn point and the treasure. Note Since the game is small, coded for fun, and the only game designer is a programmer (that is, me myself), I do not plan to spend resources on coding a level editor or supporting an existing one. Also, I do not plan to support existing tile map libraries as I want to dig into some of the related coding problems myself (see above about fun), but I be happy happily to look at relevant existing code as a reference. When I look at my map generation code, I find it rather ugly. Is there an elegant way to deal with the problem? If that matters, I'm writing this game in JavaScript, but I will be happy to see a relevant reference in any programming language. Here is a partial pseudocode to illustrate how my current tile generator solution looks like this.init function(w, h) this.w w this.h h this.tile presets var mid h Math.floor(h 2) var quarter w Math.floor(w 4) Here is the part I don't like a set of generator rules this.preset col (0, Tile.GRASS) this.preset tile (0, mid h, Tile.FLOOR) this.preset col (1, Tile.GRASS) this.preset tile (1, mid h, Tile.FLOOR) this.preset col (2, Tile.WALL) this.preset tile (2, mid h, Tile.FLOOR) this.preset tile (2, mid h, Tile.PLAYER) this.preset tile (1 quarter w, mid h, Tile.BOSS) this.preset tile (2 quarter w, mid h, Tile.BOSS) this.preset tile (3 quarter w, mid h , Tile.TREASURE) this.preset col (w 1, Tile.WALL) Implementation details that may help to understand the code above this.tile function(x, y) var preset this.tile presets x y this.w if (preset ! undefined) return preset return this.random tile () this.preset tile function(x, y, tile) this.tile presets x y this.w tile this.preset col function(x, tile) for (var y 0 y lt this.h y) this.preset tile (x, y, tile) Note that I shown a rather simple set of generator rules above. Actual thing is several times longer. I hate that the code looks imperative and it is hard to figure out what is going on from the first glance. I think that declarative approach could help. But so far I can't figure out a good solution. Any clues?"} {"_id": 21, "text": "What are the most commonly used programming languages? When I took my Java courses a year ago, I was told that Java is used mostly in the overseas gaming companies while C is used here in the US. What languages should I focus on learning in depth?"} {"_id": 21, "text": "What should I consider when evaluating libraries, engines and frameworks for making a game? I'm going to make a game. I've noticed that there are a lot of game engines, libraries, and frameworks available out there, and I'm having a little trouble deciding which one to use. I'm already pretty good with some programming languages, but there are others which I don't know at all. I'm not against learning new programming languages, if that'll help, but my real goal is just to make my game. What criteria should I use to compare engines, libraries, and frameworks against each other, so that I can decide which one will allow me to be the most productive to finish my game?"} {"_id": 21, "text": "Where does the game code fit into the engine? I was wondering if somebody could tell me how the game and the game engine fit into game development. What I specifically mean is, the game engine does not actually contain a game. Do game developers build an engine, then create a new class that inherits from the engine, which becomes the game? For example, class ShooterGame public Engine I'm not sure about where the game code fits into the engine."} {"_id": 21, "text": "Recursive dungeon maps as represented by an elastic 2d array I came up with a method for recursively generating simple dungeon maps by starting with one room and recursively connecting new adjacent rooms randomly to it. Maps are represented as two dimensional arrays where each cell contains a value of 0 15. 0 represents no room while each direction is represented by north 1, east 2, south 4, west 8. I wanted to start with a single non room ( 0 ) and then expand the 2d array as necessary to fit the generated map. The difficulty I face with this tree like recursion is that if the arrays have to be unshifted to add rows and columns to the left and top of the map, I have to adjust the current position of the function, what row and column it is at. This makes it so that separate branches are not aware of array index adjustments from other branches, only their child functions will know because they have the adjusted position passed to them as their row and column arguments. Is there a way to do this? I tried storing row and column offset values outside of the recursion, but it did not work for some reason."} {"_id": 21, "text": "How can I mock Google Play purchases? I would like to know what best practices should I do for testing the functionality when a user buy an item power ups via Google Play and purchased with real money? For example, basically, creating a simple test of purchasing and saving an item stored in the inventory during the game using a game money. (e.g. Gil from Final Fantasy series or Zenny from Tron Bonne for the PlayStation 1) I know how to make money purchase update only via game money when I'm programming in Unity3D or Eclipse w LibGDX library. Now, let say I have to create a program that checks the user if actually purchase a power up items using real money. Next, the system needs to check for online status. If connected, it will simply go to the Google Play dialog and asks the user if he she wanted to proceed purchasing of items. If yes and the credit card balance is sufficient, then goes back to the game app and check if the boolean returns true, then item that the user is bought will be saved. Another example is that the amount of real money will be calculated via programming and if insufficient, the user asks to add more real money value by purchasing it via Google Play. If return true, then, the real money value will be reloaded. This concept is basically needed for game developers. However, is there a safe way to test the real money purchase test stuff without using a credit card value or something before the actual publishing of the game app in Google Play along with this feature? Is there a tutorial, start up guide, recommendation or something for this? Please, I would like to know how will I start. Thank you."} {"_id": 21, "text": "What language was used to write Starcraft II? Total newbie question , but what language was used by blizzard to crate the Starcraft II game play? I've been playing it for the last couple of days , and I'm constantly astonished by the complexity and the performance of the game. Is it an in house language , or do they use some flavor of a know language?"} {"_id": 21, "text": "Is game software design the same as non game software design? Is the software design process for a game similar to a non game? Do developers create UML diagrams? I ask because of the iterative nature of game development, I wonder if creating a UML diagram would just be a waste."} {"_id": 21, "text": "Deep copying or cloning in actionscript 3 I would like to make a mirror reflection of an entity in Flashpunk. So I would like to copy a spritemap from one Entity to another (reflectionEntity). If i use something like this reflectionEntity.sprite otherEntity.sprite reflectionEntity.sprite.scaleY 1 to reflect then the graphic of the original entity is also scaled. Is there a simple way out of this? I have been searching for the solution for more than an hour and have not found a suitable one."} {"_id": 21, "text": "Picking college degree (want to be games programmer) Alright, so I know there's plenty of questions that have to do with college degrees on this site, but I don't feel that any of them really answer my question. I recently got accepted into Northeastern University. The thing that drew me to the university was not only that it appears to have a comprehensive computer science program, but that it offers combined majors with the other colleges. Since i'm interested in both game art and game programming, I applied to the Computer Science and Digital Art major. However, after looking at the other combined majors, I wondering if I picked the one that is right for me. The five majors I'm currently looking at right now Computer Science and Digital Art Pros Teaches both programming and art fundamentals. Cons The mathematics requirements are the weakest of the five majors (only require linear algebra). Computer Science and Game Design Pros Very comprehensive in both computer science and game design. Requires the most computer science courses out of the 5 majors (the extra courses are game design specific). I'd be the most likely to meet like minded peers in this major as well. Cons Doesn't really touch on subjects of game art at all. You are allowed to take two art design electives, that's it. Computer Engineering and Computer Science Pros Gives a comprehensive education on computing in general (hardware and software). The biggest benefit of this major, I feel, is that it would teach me how to think. By that, I mean it would teach me to think in such a way that it'd be very easy to dive into other aspects of both computer engineering and computer science (more so than the other majors). Cons It's a computer engineering major first, and a computer science major second. Some of the information I learn may be pretty much useless. Computer Science and mathematics Pros Naturally, it has the most math courses of any other major. Cons The only major con is that I'm not really crazy about math, and don't know if I really want to subject myself to a bunch of it. Computer Science and physics Pros It's actually pretty well split among math, physics, and computer science. Cons Like the computer engineering major, some of the information I learn may be pretty much useless. I don't want this post to be ridiculously long so forgive me if I'm not specific enough. I'm guess I'm torn between different beliefs. Computer Science and Digital Art Game Design would probably be the most fun majors for me, since they'd suit my personal interests. However, the other majors would give me information that would be useful in a broader sense (I could apply them outside the fields of game design interactive media). I don't think any one of these majors will prepare me completely for the games industry, not even the game design one. However, I do think that no matter which of these majors I pick, I'll still be able to get into the game industry."} {"_id": 21, "text": "Effective methods to continuously update movement in a tower defense game? We are four guys making a Tower Defense game as a project in first grade on a university. The game is going to be really simple! Three different towers Three different monsters One map (maybe add some more if we have time) The game has to be object oriented. The class structure is as following Game Drawing of graphic, etc. Level Every level is an object of this class. Each level has a finite number of wave objects (in a list) Wave Contains a list of monster objects. Monster This is a superclass. We make subclasses for the different type of monsters Tower Superclass to the towers. There are subclasses for each type of tower. We are thinking about how to solve the problem that many objects have to do stuff, at the same time, e.g. move one pixel in one direction. What we came up with is the idea of implementing av class Timer, to control when objects do things. I am not sure this is the best way to do it. Could someone give some good ideas about how to solve the continious update case?"} {"_id": 21, "text": "How to write \"Hello World\" for N64 purely from scratch? As an experiment I want to code a \"Hello World\" program for N64 using only assembly code, using no headers, tools, helper files, etc. I just want to write the assembly code bare bones from absolute scratch, assemble it and have it run through a demanding emulator that can show me the output. I can't find enough info on how to send the correct data to the RSP for video output though. Can anyone offer me a hand here? Not on helping me program, but with information regarding N64's RSP and how to program it to display text, etc."} {"_id": 21, "text": "Game Design Patterns ( think GOF ) literature? Possible Duplicate What are some programming design patterns that are useful in game development? Is there any literature on game design patterns? I'm taking a software design class and would like to learn how some of these design patterns would apply to game development."} {"_id": 21, "text": "Are there cases where globals singletons are useful in game development? I know that having global variables or singleton classes creates cases that can be difficult to test manage and I have been busted in using those patterns in code but often times you gotta ship. So are there cases where global variables or singletons are actually useful in game development?"} {"_id": 21, "text": "Quantity of dropped spawned items in container I'm having trouble figuring out how to spawn more than one item in to a container with a weight limit. What I'm having trouble with is the understanding, rather than what statements to write My items are composed of weight, type and foundIn, among other things. My containers are items, with some minor changes. foundIn is an array of strings which match \"container\" items, and should be either \"world\", \"container name\", or empty ( ). \"container\" items follow a similar structure, with slight deviance. Whenever I want to drop an item, I get a pool of items in a foundIn location, make a Math.random check against the commonRate, and if that item is a type \"container\", I try to fill the container. Here is where I have my problem I can not figure out how to decide if multiple items of the same type should be dropped inside the container, and if so, how many. If I can figure this out, I can have monsters carry their own drops, instead of having to write a whole monster drop table with levels and oddities. The following is my code. The last method, dropItem, glues the displayed methods together. placeExists(place) return this. itemPlaces.indexOf(place) gt 1 getItemsOfType(arrayOfTypes, inList) if (!Array.isArray(arrayOfTypes)) throw new Error('Index must be string') let pool this.list if (inList) pool inList return pool.map((item gt if (arrayOfTypes.indexOf(item.type) gt 1) return item )) populateContainer(container, pool) let chance Math.random() pool pool.map(item gt let canBeFound item.foundIn.indexOf(container.name) gt 1 item.foundIn.indexOf('world') gt 1 if (item.commonRate gt chance amp amp canBeFound) return item ) this.getItemsOfType(container.availableTypePool, pool).some(item gt if (container.capacity.freeSpace lt 0) return true if (item.commonRate gt Math.random() amp amp item.weight lt container.capacity.freeSpace) container.addItem(item) ) return container getItemsOfPlace(place) return this. LIST.map(item gt if (item.isFoundIn(place)) return item ) dropItem(fromPlace) if (this.placeExists(fromPlace)) return let foundItem let pool this.getItemsOfPlace(fromPlace) pool.some(item gt let chance Math.random() if (chance gt item.commonRate) if (item.type 'container') foundItem.push(this.populateContainer(item, pool)) else foundItem.push(item) return true ) return foundItem container abstracted method of adding an item container.addItem (item new Item()) if (item instanceof Item false) throw Error('item needs to be of type Item') if (item.type 'container') throw Error('Yo dawg, I heard you like containers...') this. contained.push(item.code) this.carryingWeight item.weight How do I decide if I should drop multiple items, and how do I randomly select that amount? Note that this.list and this. LIST are the same list. For some reason, WebStorm seems to lose track of one or the other when inside certain callbacks, so I switch to avoid losing autocomplete. For reference, this.list is get list() return this. LIST , and is obtained from extending a custom List class."} {"_id": 21, "text": "Should a server run all maps in one loop, or a thread game loop per map? I'm working on a real time multiplayer browser based game. The game is top down on variable size tile based maps. There is no central map where all players come together, the entire game plays out in multiple maps. (Player chooses one on login, but has the ability to switch whenever they want). Let's take the following loop that runs on the server side of things let tick time Duration from millis(500) e.g. Tick 2 times per second. let mut next tick Instant now() loop let now Instant now() if now gt next tick Parse user input Update state Update to state to users in map next tick tick time else let wait time next tick now sleep(wait time Duration from millis(1)).await In my 'map based' gameplay scenario, would it make sense to spawn a thread for every map where one of these loops runs? Or would it be recommended to have only a singular thread with a singular game loop that updates every map? Or is there perhaps a better, already existing, pattern for this?"} {"_id": 21, "text": "Tangible benefits to speed coding your personal game projects I noticed a few programmers setting time sensitive challenges for themselves, usually in the area of \"write game of type X in Y amount of time\" or \"write X number of games giving only Y time for each\". What are the tangible benefits for setting your workflow in this manner to speed code for a while? It feels like you have to trade off efficient code to get something done quick. And I suppose adding a final layer of polish isn't a big priority in these challenges, so it's okay to use programmer. I've made some simple 2D scrolling shooters and puzzle games a few years ago and out of stupidity I deleted most of my code. So now I'm curious about using the speed coding approach to get a couple simple things done again, and get myself more into game logic."} {"_id": 21, "text": "When or why would someone use a programming language (Swift, Java, C , Rust etc...) over an engine like Unity? Everytime I've read about people asking whether they should write their game in C or Unity, Unity is usually the default answer, unless they want to go through the hassle of creating an engine by themselves when Unity already does everything for you. If that's the case is there ever a case where writing a game in C , Java, Rust etc... is better than using Unity? If so what are these cases?"} {"_id": 21, "text": "How was is playback of music handled on consoles such as the NES, Master System, Gameboy, etc? So, I deliberately left out the SNES because AFAIK the music subsystem is basically entirely self contained. However, on systems like the NES and Gameboy, while there are sound chips, there isn't any sort of dedicated sound CPU. My question is how one reliably plays back music without putting too much of a burden on the CPU? Timing is clearly very critical music won't sound right if the notes aren't played at exact intervals. Naively, one might just continually update the registers of the sound chip. However, this leaves no time for programming game logic! You could plan to update the registers every cycle in the main loop, but then any interrupts triggered would throw everything off. I haven't been able to find any information on this, despite there seeming to be a clear conceptual gap! So basically, how does a game like say, Super Mario Bros on the NES manage to play back music consistently and reliably, regardless of what is happening on screen?"} {"_id": 21, "text": "Finding other programmers to help on a project As a semi FAQ question attempt Where can you find people to work with you on a project? Particularly programmers. One thing that is obvious is that all programmers have a project (or twenty), and the chances of a programmer just hanging around looking for something to do is a lot less likely than if it were an artist needed on the team. So, where do you post? Where do you search and follow people around until it looks like they are a viable team member? Is it really difficult to assemble a team that are not close friends or chat buddies? Are there sites with this sort of posting? To clarify I am referring to a team. Example 1 I am making gameEngineOfAwesomeness. I need help. Example 2 I am 70 complete on this game, and i need help. Example 3 I have an open source project idea, with a prototype. I need help. It doesn't necessarily mean open source, just programmers who can work with me on something (and where to find them ))"} {"_id": 21, "text": "Shortcut for NodeJS server I am tired of typing \"cd c socket nodejs\" \"node testserver.js\" Into the command promt.. How do I create a shortcut or bat for it?"} {"_id": 21, "text": "How should bots be recognised in a game? I'm interested in how bots are usually written. Here's my situation I plan to make an online 2D mecha game in HTML5, and the server side will be done with node. It is intended to be multiplayer, but I also want to make bots in case there aren't enough players. How does my game logic see them, as players or as bots? Is there a standard by which I should make them? Also, any general tips and hints will be OK."} {"_id": 21, "text": "Which programming language should I start with in game dev? I am a front end web developer and I've always been interested in building games. I work primarily with HTML, CSS, PHP, and JavaScript on a daily basis, so I'm not new to coding. I would like to know which language platform would be most useful for me to build a simple, 2D, art heavy game, like something you'd see on the Super Nintendo. Thanks."} {"_id": 21, "text": "Are there any advantages to different programming paradigms specifically releated to game programming? I have been researching three different programming paradigms namely procedural, object oriented and functional. So far I have been able to find a lot of good information regarding general differences and advantages disadvantages like readability, re usability, difference in learning curve, program size, etc. I am now looking for differences more related to game programming, but I am struggling to find good examples. Does anyone know of specific issues when programming games that these paradigms handle differently, that I could look into? This could include things like handling I O, rendering and programming AI, but other things related to game programming would also be appreciated."} {"_id": 21, "text": "Are techniques from Warioware D.I.Y actually useable in creating an actual game? In a game called Warioware D.I.Y, it teaches you how to create minigames with certain forms of AI. Can I use the techniques shown in this game to actually develop an advanced game?"} {"_id": 21, "text": "Why are there fewer glitches in current day games? I remember that almost every single game in the early 2000s had at least a few amusing glitches, mostly related to animations, that often produced funny situations. I also remember that game magazines used to dedicate a section with the funniest screenshots people sent in. As an example, I was just playing Far Cry from 2004 and out of nowhere, whenever I killed some bad guy, instead of dropping to the ground they'd start playing the running animation. This was getting me confused since I was trying to shoot them down from a large distance and didn't understand why they weren't dying. I've rarely seen stuff like this in current day games. Was there some change in the technique used to develop games that would make these programmer mistakes less likely? P.S. I'm not talking about RPGs and other inherently complex genres. I'm talking about games like Far Cry shooters like Battlefield 3, Modern Warfare 3, even Mass Effect. I've seen plenty of glitches in games like The Witcher 2, Skyrim, etc."} {"_id": 21, "text": "Time critical events based on framerate Problem Description Basically, I've made a \"programming game\" in which I've made my own scripting language. It is a completely standard Lunar Lander game, though instead of directly controlling the lander using keyboard input, it instead fires a sequence of commands you have provided through the scripting language I made. This all works, and I've hit a critical problem. So essentially, using the scripting language, you specify something like After 5 seconds, activate thrust for 10 seconds, and then after 2 seconds, rotate the lander for 4 seconds. The goal is then to chain together a sequence of commands which will get you to land the lander safely. Of course, this comes with one problem. If you repeat the sequence of commands, each command will have to be fired at exactly the same spot in the level, that is, after x amount of seconds, but also with the lander being in the exact same spot. If you did not use timer based movement, sure you could indicate that a command should activate after 5 seconds, but the lander moving at 60 FPS would have moved way further than a lander moving at 30 FPS. Why of course, I thought I would simple just make the lander use timer based movement so it is independent of FPS (I am using the very standard approach of taking the amount of time passed last frame, and multiplying it to a constant move speed). Then I would count seconds using the system clock. So the after x amount of seconds, the lander would be in the same spot in the level when the command activates. Unfortunately, this approach do not work. Every time I run a sequence of commands, they will be activated with, sometimes very slight, variations, making it impossible to actually get a consistent and reliable path for the lander. My Question So my question is, am I tackling this problem a completely wrong way? What exactly do you do when it is absolutely critical that timed events defined by the user will activate at exactly the same time and spot in a level? I seem to be quite stuck with this question."} {"_id": 21, "text": "Is there an IDE that can simplify the process of creating a game matchmaking website? Yes, I'm an old guy. And I'm well versed in \"C\" and have written several games which I have been selling on the web for a number of years. And now, I would like to adapt one of my games to be \"online\". Sounds simple. I'm sure I can use the thousands of lines of \"C\" code that I've already written. Right? So my initial investigation begins. First, I think I'll need a server program that lives on a dedicated server (or a VPS probably) that talks to a bunch of client applications that live on individual devices around the world. I can certainly handle that! (I think to myself). I'll break up my existing game into two pieces, a client piece that is just the game displays and buttons, and a server piece that does everything else. Piece of cake, right? But that means that the \"server piece\" must be executed on a remote machine somewhere and run 24 7. Can I do that? apparently, that question is so basic, so uneducated, and so lame, that nobody has ever posed it before. Because hours of Googling does not yield an answer. Fine. I'll assume I can do that and move on. I'll need a \"game room\", which to me means a website where you log in and then go to a lobby of some kind where you can setup your preferences, see if any of your friends are connected, and create or join games. Should be easy, but it's not. No way. Can I do all this with my local website builder? (which happens to be 90 Second Website Builder, a nice product, btw). It turns out, I can not. I can start with that, but must modify each page, so I can interact with my sql database. So I begin making each page a \"PHP\" page and dynamically modifying the HTML code with PHP code. I'm already starting to get a headache. Because the resulting web pages looked terrible, I began looking at using JQuery. I want to user a JQuery dialog on my website to display a list of friends and allow the user to select one to invite to the game. google search for \"how to populate a JQuery dialog from a sql database\" yields nothing but more confusion. Javascript? Java? HTML? XML? HTML5? PHP? JQuery? Flash? Sockets? Forms? CSS? Learning about each one of these, and how they interact with each other and or depend on each other is too much for my feeble old brain. Can anyone simplify this process for me? Is there an IDE that will help me do all this without having to go back to college for a few years? Thanks, Scott"} {"_id": 21, "text": "What should a game engine do? I'd like to improve my skills try something new and I'd like to start with 3D. I have read Starting programming in 3D with C but I have question about engines What should engine do? I know it is abstraction layer above 3D API (i.e. OpenGL or DirectX) but what should it exactly do?"} {"_id": 21, "text": "Display a Message Box over a Full Screen DirectX application In our custom assertion handler, I'd like to display a message box asking to see whether or not this failure can be ignored. However, when our DirectX game is full screen, I can't get the MessageBox function to display above the full screen. Note The first parameter to MessageBox is the the HWND used to create the device, and it still does not work. Is this even possible?"} {"_id": 21, "text": "How are the same items generated with slightly different attributes? Consider games like Destiny. How do they generate weapons that have the same skins and names, but different attributes? Two people can have the same weapon or armor piece, but have different attributes on these pieces based on luck or drop rate etc. How is this accomplished programmatically?"} {"_id": 21, "text": "Store and retrieve different objects on a tile (I hope the title is clear enough, if not feel free to suggest a better one) I'm trying to make a simple tile based map for a college project in Java. But I'm stuck on how to literally place things on my map. On the programming side of things, I still haven't got into graphics on this. As of now I have A \"Robot\" class, which implements an \"Attackable\" and \"Spawnable\" interface, the robot can attack and moved A \"Obstacle\" class, the obstacle too can be attacked, so it implements Attackable, Spawnable, but it also can be pushed by a robot (methods by the class itself). A \"Station\", which is nor attacable nor can be pushed, so it only implements Spawnable and other specific methods. A \"GameWorld\" class which hold the map (a 2D array of Tiles) and various methods. A \"Tile\" class (which is arrayed to create the map). It has a boolean \"Occupied\" (which doubles as a collision too). Previously it stored just a single Attackable variable, because both Obstacles and Robot can be attacked, so I just tought it would be easy to just store them as such on the map for when I need to attack something, and then use some other reference to Robot instances when I need to move the robots and have a reference to the station in GameWorld in order to use that. But then I remembered that the Obstacles need to be moved too, so it wouldn't really work. Now I'm thinking about having two maps, basically, an AttackableMap for the attackable object (which would store both robots and the obstacles) and a ObstaclesMap for the obstacles alone (with tiles occupied by robots set as occupied). Which would obviously mean having two tile classes, one to hold each kind of object. But it feels cheap, I think. It uses a lot of memory and I think it might be hard to render at a later time. But having only one map would mean having to check what kind of object I'm getting and I'd have to do loads of casts and I want to avoid that. So, I think, there must be a better way to do this. How do other people do it then? So basically my question is... How can I store different \"things\" on a tilemap in a better way? Is there some technique widely used? What I've come up with feels rigid, if I wanted to add another kind of object that can be placed on the map (like a mine) I would need to create another map entirely, another tile, write new methods... There must be some flexible (and not too complex) way to have some freedom in this aspect."} {"_id": 21, "text": "What are windows used for? I have a very general question In games, what use does the programming concept of a window have? Or, in other words, why do some game dev libraries offer interfaces through which to create multiple windows? mdash Why would you need more than one windows in a game? Are multiple windows used as different views states of the game? (I.e. in game, main menu, pause menu, etc.)"} {"_id": 21, "text": "How should I handle functions, where two classes have equal use? I'm working on a few features for a strategy engine I'm making. I'm trying to figure out the best spots to separate the components, as either option will provide the same amount of coupling, with the same effectiveness. For example, all players have a Damage component, a Player component, and a HealthBar component abstract class Damage protected abstract void sendDamage(Player targetPlayer, int rawDamage) public abstract int calculateRawDamage(Attack attackUsed) public abstract void receiveDamage(int rawDamage) class Player List lt Armor gt equippedArmor List lt Buffs gt currentBuffs public Damage damageComponent public List lt HealthBars gt healthBarComponents abstract class HealthBar can be inherited for mana or health bar protected Color color public float percent 0.0 1.0 When a player receives damage, I need to show a red number floating up from their head, indicating the amount of damage. This can either be implemented in HealthBar, or in Damage. It fits damage better, but then healing works in the same way, and wouldn't be called from damage. I could abstract damage into something like ChangeValue, which would change mana, health, etc in any direction, or I could use the abstract HealthBar class to show this number being changed. I'm trying to think of a general rule that would solve this and other problems, where two classes use the same function equally. This is an oversimplified version of my classes, but it makes more sense this way. How should I handle functions, where two classes have equal use?"} {"_id": 21, "text": "Game Design Patterns ( think GOF ) literature? Possible Duplicate What are some programming design patterns that are useful in game development? Is there any literature on game design patterns? I'm taking a software design class and would like to learn how some of these design patterns would apply to game development."} {"_id": 21, "text": "Building a unified interface for a swap chain in both DirectX 12 and Vulkan Most objects in DirectX 12 have natural analogues in Vulkan, e.g. VkInstance IDXGIFactory VkPhysicalDevice IDXGIAdapter VkDevice ID3D12Device VkQueue ID3D12CommandQueue VkCommandBuffer ID3D12CommandList However, when it comes to the swap chain, it's not clear how the entries in VkSwapchainCreateInfoKHR correspond to entries in DXGI SWAP CHAIN DESC1. Clearly, there is not always a 1 1 correspondence, but I would really like to know how I can implement a unified interface for both."} {"_id": 21, "text": "What are standard methods for organizing game code? Grouping by standard \"kinds\" of methods? I've made a few games, and am getting faster and better organized each time. I'm well out of the \"just make it work\" phase and working on methodology and readability. I need some tips on code organization though. I don't mean patterns I'm having great success with MVC but the organization of methods inside the classes themselves. I've noticed that methods in my state models can usually be grouped into four categories (1)constructor destructor, (2)data access (3)actions (4)events. My controllers usually have c d and input methods. My views usually have c d, view updaters, and event listeners. I feel like I'm reinventing the wheel though someone must have spelled out \"these are the common types of methods\" somewhere before, right? Storage has Create, Read, Update and Delete (CRUD), so what are the equivalents for objects? EDIT Found some cocoa specific advice here http www.mactech.com articles mactech Vol.21 21.07 StyleForCocoa and some generic advice here https stackoverflow.com questions 73045 whats the best way to organize code 73081 73081 I'm going to use that as a foundation, modified for game specific stuff. More info still appreciated if you have any."} {"_id": 21, "text": "How do I implement a racing clock that shows elapsed time? I'm wanting to make a old school timer like the picture below. How would I go about doing this in VD? I have tried it doing it with code bellow. The problem with this is that it starts with just seconds only adds the minutes section when you reach 1 minute. Dim StartTime As DateTime Dim PlayTime As TimeSpan Private Sub Form1 Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load StartTime Now() End Sub Private Sub tmrCountUp Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrCountUp.Tick PlayTime Now() StartTime lblTime.Text PlayTime.Hours amp PlayTime.Minutes amp PlayTime.Seconds lblTime.Text lblTime.Text 1 End Sub"} {"_id": 21, "text": "Programmatically drawing a \"pencil\" line or curve If you look closely (scan it on a computer and zoon in) at a carbon pencil line you can see that there are differing shades of gray. I tried looking on the Internet for any kind of algorithm or statistical model for how that gray would be drawn programatically. Does anyone have information on this? Thanks a lot!! I want to make drawings on a computer that look they were drawn with a pencil."} {"_id": 22, "text": "How to encapsulate game objects (entities) in Box2d I am currently learning Box2d, a 2D physics engine within libgdx. But Box2d seems to be in every game framework these days so I am not really talking about libgdx. I understand Box2d comes with lots of new concepts such as shape, bodydef, body, fixture, sprite, joint. But I think I can slowly but surely manage to learn about them. My question, however, is how to organize them into a game object for better maintenance of code. Naturally, I am thinking about following fields in the game object class. GameArea gameArea Body body BodyDef bodyDef FixtureDef fixtureDef Shape shape Sprite sprite As for its methods, it has constructor, update, and display. But I am talking without experience. For example, I don't know how I can organize joints maybe in GameArea. Any thought from experienced would be appreciated."} {"_id": 22, "text": "How to make an object in box2d have constant velocity even after collision? I have iOS game where I have a bouncing character. Everything is being handled by box2d. The problem is when the character hits a wall of another character it's velocity changes, but I don't want this. I need the velocity to stay constant even after collisions. I was thinking the only way to do this was to keep setting the velocity after each collision unless there's another way to do this that I'm not aware of?"} {"_id": 22, "text": "\"Running\" against a steep slope on a Box2D Platformer Ive seen alot of pages talking about how to emulate a platformer on Box2D, specially about how people dont want to slide down a slope. Well, my problem is different and Im surprised I cant find posts solutions about it. The problem happens when I have a very steep slope and I run against it. This is what happens Being the square a common platformer hero fixture, since in a Box2D platformer the movement is based on applying impulses or setting the velocity, what happens when I \"move\" torwards such a slope, its like im pushing against it, which creates a vertical force and therefore the square moves UP (specially since friction is 0 to avoid the \"sticking to a wall\" thing). I've solved most of Box2D's non platformer proficient issues. This one seems unsolveable. So, how do I avoid my object to go up a steep slope when pushed against it, and instead slide down since its too steep to be climbed?"} {"_id": 22, "text": "Box2d How to connect distance joint to the ground? I have a rectangular fixed size world. I want to connect a body inside it to any place(near that body) in the world with a b2DistanceJoint. Do I need to create a large static body with the size of the world that can't collide with anything? Or is there a better method? Will it slow down simulation speed if I have around 300 bodies moving on the surface of this static body?"} {"_id": 22, "text": "Sizing a Box2D ground object I am developing a platformer game using SDL2 for graphics and Box2D for physics. I am currently designing my levels and would like to know if it is better to make the static part of each level (ie ground) one big (500 units wide) polygon or to break each level up into multiple tiles just a few units wide. The Box2D manual says that I should keep my objects small to avoid bugs in the floating point code but having a single large ground object seems like a resonable way of reducing the number of objects in the simulation. So, can I make my ground object one large 500 unit polygon or should I break it up into many smaller 1 2 unit polygons."} {"_id": 22, "text": "How can I generate vertex data from an SVG? I am trying out the Phaser game engine, and am interested in making a vector graphics game (simple black and white like Asteroids), but I want to use vector graphics instead of raster PNGs. I was looking at this example, which looks like what I want to do... Where I am stuck is, say I draw a simple Asteroids style ship in Illustrator, consisting of 3 connected lines. How do I export that data into an array of vertices that would work with the setPolygon() method in Phaser Box2d?"} {"_id": 22, "text": "Why can't I swap fixtures on collision in Box2D? I'm trying to swap the fixtures associated with a body after colliding with a specific obstacle. I can listen to the collision event by extending b2ContactListener. I tested it with a trace and it's working. My listener function in the main game class calls a Player method that makes the swap. But it's just not working. The body is stored in public var body b2Body in the Player class. The method I'm calling goes like this public function changeFixture() void var newShape b2CircleShape new b2CircleShape(1) var myFixtureDef b2FixtureDef new b2FixtureDef() Here I set density, friction, restitution, etc... Not important now... myFixtureDef.shape newShape body.DestroyFixture( oldFixture) body.CreateFixture(myFixtureDef) I know the method is called because this works trace('Yay! I'm working!') What might be wrong?"} {"_id": 22, "text": "Set Position of multiple bodies I have a character composed of five bodies which are tied together by a lot of joints. On of them is the overall chassis, to which all forces and impulses are applied to move the whole Character. All in all that works very fine, except one thing I need to set the Position of the Character so that it get Beamed from one place to the other in one single frame. Unfortunately I cannot get this to work. I tried the following code, without any success playerbodies.forEach(function (bd) bd.SetLinearVelocity(new b2.Vec2()) var t bd.GetTransform() t.p.x 10 bd.SetTransform(t, bd.GetAngle()) ) How can I make that happen?"} {"_id": 22, "text": "Get Vertices of a Shape Body in Box2D Is there a way to do it? I can get only polygon shape's vertices, but i want circle, box, etc too. How to do it?"} {"_id": 22, "text": "How to set a body to a specific position using Andengine I'm developing a game with a single player and multiplayer mode. Lets say I have walls (static bodies), vehicles (dynamic bodies) and bullets (dynamic bodies). It works fine to control my own vehicle using vehicleBody.setLinearVelocity(velocityX, velocityY) . The vehicle can collide with walls and bullets as expected. Now I like to move the enemy vehicles in multiplayer mode. When I use the same method to move the body by its velocity values (in multiplayer mode), the vehicles get out of sync really quickly, means they don't have the same position on all devices because some data packages get lost. What I'm currently doing is the following On device 1 1) I move the body using setLinearVelocity 2) Then I get the X and Y position of the body and send a data package to the other device On device 2 3) I receive the data package and set the position of the body. I tried different ways, hopefully you can tell me the best way or alternatives I did not try yet using vehicleBody.setTransform(...) activity.runOnUpdateThread(new Runnable() Override public void run() vehicleBody.setTransform(new Vector2(newPosX, newPosY), angle) ) I also tried using MouseJoint (based on that tutorial), but somehow the body was bouncing randomly to the next position. Sometimes it was working great, but when I restarted the game the vehicle of the enemy started bouncing again. Maybe I failed to setup the parameters. Here is what I used public MouseJoint createMouseJoint(float newPosX, float newPosY) final float PIXEL TO METER RATIO PhysicsConstants.PIXEL TO METER RATIO DEFAULT Vector2 v vehicleBody.getWorldPoint( new Vector2(newPosX PIXEL TO METER RATIO, newPosY PIXEL TO METER RATIO)) MouseJointDef mjd new MouseJointDef() mjd.bodyA groundBody mjd.bodyB vehicleBody mjd.dampingRatio 0.2f mjd.frequencyHz 30 mjd.maxForce (float) (1000.0f vehicleBody.getMass()) mjd.collideConnected true mjd.target.set(v) return (MouseJoint) mScene.mPhysicsWorld.createJoint(mjd) Before I've used bodies I was using simple sprites and it worked perfectly. I sent data packages to the other device(s) and set the position and rotation of the enemy vehicle by using vehicleSprite.setX(newPosX), vehicleSprite.setY(newPosY) and vehicleSprite.setRotation(angle). Compared to that, bodies seem to be very complicated. So how I can I keep positions synced without bouncing? By the way, on some pages I read about using KinematicBody instead of DynamicBody for a vehicle. What is the advantage? My vehicle needs to collide with the environment, so I think DynamicBody is the correct choice, isn't it?"} {"_id": 22, "text": "Box2d get free space I am developing a little Game with something like particles, where every particle is represented by a box2d Body. To insert new particles I need to find a place in the b2World where no bodies reside. How can I obtain this? greeting..."} {"_id": 22, "text": "Hill jumping game mechanic like Tiny Wings I'm a huge Tiny Wings fan and I'd like to understand the game mechanic at a deeper level. What are some good resources for the basic Box2d (or similar) physics behind the hill jumping game mechanic? I've used some basic features of Box2d. I imagine the flying character is just a circle, tapping the screen increases the downward force on the character, and the hills are some sort of curve object from the physics engine. Edit 1 Here's more info I'd like to understand which objects from the Box2d physics library are used to create the bare bones hill jumping mechanic. This mechanic would look like a \"curvy\" horizontal line that just scrolls across the screen. The most basic shape for this line that comes to mind is a sine wave so that's probably a good starting point. Then there's the character that moves around. Note the character's horizontal position is fixed while the vertical position moves up and down. I'm curious about which Box2d body shape, type etc is used for this character. What are some values for the coefficient of friction that work well? How about the density etc. I've searched around the web for tutorials that ideally will answer the above questions and perhaps provide additional resources regarding efficiency, camera motion and so on."} {"_id": 22, "text": "Cocos2D Box2D body that is movable by one type of object but not another I'm in the process of creating a simple platform game using Cocos2D 2.0 and Box2D. I'm trying to create a kind of crate object that cannot be moved by the player, but that can be moved by an elephant object. When the player runs up to the crate, it should stop him dead in his tracks (as if he is running into a static Box2D body). If the elephant runs into it it should get knocked out of the way (as if the elephant was running into a dynamic Box2D body of much smaller mass density). I can't use collision bitmask because of course I want collision to occur in both cases, I just want that collision to result in different things depending on which type of object is hitting the crate. Anyone have a hint as to how to make this work? Thanks in advance!"} {"_id": 22, "text": "Setting a Box2D Bodies Center? How do I set the center of a fixture body consisting of multiple shapes (triangles)?"} {"_id": 22, "text": "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. I 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. Now how can I make the objects actually look like feathers falling through air? Specifically 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."} {"_id": 22, "text": "Relative movement in Box2D (keep object from falling off planet) I'm creating a game with planets orbiting around a sun, like this The brown square is the earth, rotating around its center and around the sun. The yellow square is the sun, which doesn't move. Now imagine a player standing on the planet, the planet moves at a velocity of 20 m s. How do I prevent the player from falling off? I have to give the perception to the player that the planet isn't moving. I got the gravity on earth working, but I don't know how I can keep the player on the planet! I have thought about two solutions until now Just apply the angular velocity and linear velocity of the planet on the player (if it's in a specified radius), I think this method will cause jittery movement glitches. Create a separate Box2D world for the planet and render this Box2D world with the rotation translation of the planet. This method is complex though since it would add the problem of moving bodies between different worlds if the player would leave the planet. This image explains it I think there is another (better) way to fix this problem, but I haven't found a solution yet."} {"_id": 22, "text": "Rotate Box Sprite With Circle Body I want to rotate my rectangular sprite with circle body. The problem is the body doest not attached to the centre of the sprite. This was the default behaviour of the body and sprite. But I want that circle body attached in the bottom of the rectangle and when rotation happen at that time rectangular sprite always attached with the body at the bottom and during simulation it change its angle and position according to this only. I try to write question in words if I don't able to understand you then know me then I post a picture of my problem here. Although I know that cocos2d has setAnchorPoint method available so similar task become easily but what about my engine that right now I was using AndEngine. So be relevant to this game platform. Also thanks in advance for efforts you take."} {"_id": 22, "text": "box2d raycast filter category I am trying to filter a category in my ray casting (jBox2D within libGDX), which should return the closest object that does not belong to the category LEVEL0. I've tried a plethora of approaches, but none of them seem to work. This post, for example, instructed me to do so private static class RayCast implements RayCastCallback Fixture f Vector2 point float fraction public RayCast() this.fraction 1f Override public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) if (fixture.getFilterData().categoryBits Corpo.LEVEL0) return 1f if (fraction lt this.fraction) this.f fixture this.point point this.fraction fraction return 1f Yet, it ignores the LEVEL0 bodies only sometimes, and sometimes ignores other bodies as well (though it seems to work on most cases, it fails frequently enough to be unacceptable). I've tried a few other solutions, including returning 1 in the first if (which should mean ignore this collision), return this.fraction always, instead of 1, but nothing works this, in fact, seems to be a very common problem, as the internet is filled with a variety of workarounds, none of them working for me. I think my library is updated, or at least is the version that is included in the latest libGDX (which, according to my quick research, is the actual latest). I've posted this same question here, but I'm not sure about the official forum's activity, so I decided to ask here too, just in case. Whichever website gives the answer first, I shall copy it to the other."} {"_id": 22, "text": "Errors happen when using World.destroyBody( Body body ) on Android application using libgdx, when I use World.destroyBody( Body body ) method, once in a while the application suddenly shuts down. Is there some setting I need to do with body collision or Box2DDebugRenderer before I destroy bodies? Below is the source I use for destroying bodies. private void deleteUnusedObject( ) for( Iterator lt Body gt iter mWorld.getBodies() iter.hasNext() ) Body body iter.next( ) if( body.getUserData( ) ! null ) Box2DUserData data (Box2DUserData) body.getUserData( ) if( ! data.getActFlag() ) if( body ! null ) mWorld.destroyBody( body ) Thanks"} {"_id": 22, "text": "Error in destroying object in Box2D LibGDX I'm trying to delete an object when a collision happens. I have put the following code in the render method of the object so it would be outside of the physics calculations. public void render(SpriteBatch spriteBatch) some other code... body.setActive(false) body.getWorld().destroyBody(body) But I'm getting an run time error which crashes the JVM and shows, AL lib alc cleanup 1 device not closed Assertion failed! Program C Program Files Java jre6 bin javaw.exe File var lib hudson jobs libgdx git workspace gdx jni Box2D Dynamics b2World.cpp, Line 133 Expression m bodyCount 0 Can anyone help me here?"} {"_id": 22, "text": "coloring box2d body in LibGDX I want to color polygon of box2d in LibGDX. Found below useful class for that. http libgdx.badlogicgames.com nightlies docs api com badlogic gdx graphics glutils ShapeRenderer.html But, it is not coloring the body instead making colored shapes. I want colored bodies having all the property like gravity, restitution etc. In brief, I want to make colored ball and surface.And i don't want to attach sprite on bodies. Want just fill color in bodies. Need some guidance????"} {"_id": 22, "text": "Can i add friction in air? I have issue regarding speed in air. When i jump and move simultaneously that time speed of player increase.For jump i am using impuls and for movement i am using force.I want to slow speed when player is in air. Thanks in advance Following is my update method ih HUDLayer (void)update (ccTime)dt (b2Body )ballBody (CCSprite )player1 (b2World )world if (moveRight.active YES) ballBody gt SetActive(true) b2Vec2 locationworld b2Vec2(maxSpeed,0) double mass ballBody gt GetMass() ballBody gt ApplyForce(mass locationworld, ballBody gt GetWorldCenter()) ballBody gt SetLinearDamping(1.2f) else if(moveLeft.active YES) ballBody gt SetActive(true) b2Vec2 locationworld b2Vec2( 10,0) double mass ballBody gt GetMass() ballBody gt ApplyForce(mass locationworld, ballBody gt GetWorldCenter()) ballBody gt SetLinearDamping(1.2f) Following is jump (void)jump (b2Body )ballBody (ccTime)dt (BOOL)touch if (touch) if (jumpSprte.active YES) ballBody gt SetActive(true) b2Vec2 locationWorld locationWorld b2Vec2(0.0f,98.0f) locationWorld b2Vec2(0,32) double mass ballBody gt GetMass() ballBody gt ApplyLinearImpulse(locationWorld, ballBody gt GetWorldCenter()) ballBody gt ApplyForce(mass locationWorld, ballBody gt GetWorldCenter()) ballBody gt SetLinearDamping(1.2f) So where i apply logic??"} {"_id": 22, "text": "Handling player background movements in 2D games Suppose you have your animated character controlled by the player and a 2D world (like the old 2D side scrolling games). When the user presses right on the keyboard, the background is moved to the right. If the path is always horizontal, this is simple to do (incrementation decrementation of the x coordinate). But suppose that the path is instead a polygonal chain. My questions are How do you move the background? How do you move the background if the game objects are managed with a physics engine like box2D? Note. What I wanted to ask is, how do you move a 2D character in a side scroller? For example, consider the following path A B C' D' C D You start from A, move horizontally to B, then move diagonally to C, then move horizontally to D OR, from B, jump on C' and continue till D' and so on."} {"_id": 22, "text": "Making the player walk on walls in box2d I'm making a game in stencil where players walk form left to right along randomly generated walls. I cant use waypoints, since the walls' shapes and positions are unpredictable. Here's a descriptive sketch The red line is the player's path. The red circles are what I thought might make good waypoints until I scrapped the idea."} {"_id": 22, "text": "Would a box2D sensor fit my needs? I have a object in my game that when the main character hits it, all I want to do is have the object explode and then notify the character object that a hit has occurred. Would I use a b2Body and set it as a sensor for this or would I achieve this some other way? I'm using cocos2d by the way."} {"_id": 22, "text": "Include Box2D libraries to a cocos2d project (iOS) I have a problem including box2D to my cocos2d project. I've tried different ways to do it with no success. This is what I've done I downloaded Box2D (Box2D v2.2.1) to my project directory. Dragged the Box2D directory (which includes Box2D.h, Collision, Common, Dynamics, Rope) to my Xcode project (from Finder to Xcode) Then I added include \"Box2D.h\" to my .h file and got many errors... Here is where I started my research P I went to Project Settings and edited the attribute Header Search Paths (contained in the Search Paths section) specifying the path of Box2D. At this point, I builded the project and I got less errors. After that, I renamed my .m file to .mm (I think this is because Box2D is written in C and with this, the compiler can treat it as it is). Still got errors. Then I tried changing the attribute Always Search User Paths (contained in Project Settings Search Paths) from YES to NO. Still got errors. As my last option I tried changing the attribute Compile Sources As (contained in Project Settings LLVM GCC 4.2 Language) from According to File Type to Objective C . By now I'm frustrated xD. I have 203 errors and most of them are in the .h files contained in the Box2d engine. b2Timer.h Expected ' ', ',', ' ', 'asm' or 'attribute' before 'b2Timer' b2Distance.h Expected specifier qualifier list before 'b2DistanceProxy' b2Math.h Cfloat No such file or directory And so on... Thanks!!!"} {"_id": 22, "text": "box2d resize bodies arround point I have a compound object, consisting of a b2Body, vector graphics and a list polygons which describe the b2body's shapes. This object has its own transformation matrix to centralize the storage of transformations. So far everything is working quiet fine, even scaling works, but not if i scale around a point. In the initialization phase of the object it is scaled around a point. This happens in this order transform the main matrix transform the vector graphics and the polygons recreate the b2Body After this function ran, the shapes and all the graphics are exactly where they should be, BUT after the first steps of the b2World the graphical stuff moves away from the body. When I ran the debugger I found out that the position of the body is 0 0 the red dot shows the center of scaling. the first image shows the basic setup and the second the final position of the graphics. This distance stays constant for the rest of the simulation. If I set the position via myBody.SetPosition( sx, sy ) the whole scenario just plays a bit more distant for the origin. Any Idea how to fix this? EDIT I came deeper down to the problem and it lies in the fact that i must not scale the transform matrix for the b2body shapes around the center, but set the b2body's position back to the point after scaling. But how can I calculate that point? EDIT 2 I came ever deeper down to it, even solved it, but this is a slow solution and i hope that there is somebody who understands what formula I need. assuming to have a set polygons relative to an origin as basis shapes for a b2body scaling the whole object around a certain point is done in the following steps i scale everything around the center except the polygons i create a clone of the polygons matrix i scale this clone around the point i calculate dx, dy as difference of clone.tx original.tx and clone.ty original.ty i scale the original polygon matrix NOT around the point i recreate the body i create the fixture i set the position of the body to dx and dy done! So what i an interested in is a formula for dx and dy without cloning matrices, scaling the clone around a point, getting dx and dy and finally scale the vertex matrix."} {"_id": 22, "text": "Problem with sensor in box2d I have two bodies one green static sensor (spikes) and one orange dynamic body (brick). I have bullet and it's a dynamic body too, but with bullet flag set. My problem is that when the bullet is moving left to right, it sometimes hits the orange brick instead of the spikes and it flies away. There is code to remove the bullet when it hits spikes. How can I make sure it hits the spikes first?"} {"_id": 22, "text": "How can I convert a tilemap to a Box2D world? I want to use Box2D physics and lighting with a .tmx map. How can I \"convert\" a tilemap to Box2D world? My basic idea is to go through the tiles on the map and create an object for them in Box2D. I'm using the Tiled map editor for the tilemap, and the target platform is PC. Firstly, is this a good solution for my idea? Or is this even possible? Secondly, if yes, then I dont know how to get the tile's position. My code so far public class WorldLoader public static TiledMap map public static void loadMap(String mapName) map new TmxMapLoader().load(mapName) TiledMapTileLayer collisionLayer (TiledMapTileLayer) map.getLayers().get(\"collision\") for (int x 0 x lt collisionLayer.getWidth() x ) for (int y 0 y lt collisionLayer.getHeight() y ) Cell cell collisionLayer.getCell(x, y) if (cell ! null amp amp cell.getTile() ! null) float tileX collisionLayer.getProperties().containsKey(\"x\") float tileY cell.getTile().getProperties().get(\"y\", Integer.class) BodyDef bodyDef new BodyDef() bodyDef.position.set(tileX, tileY) PolygonShape shape new PolygonShape() shape.setAsBox(16, 16) Body body GameWorld.world.createBody(bodyDef) body.createFixture(shape, 0f) shape.dispose()"} {"_id": 22, "text": "Rotating kinematic object around a moving point Box2D I'm new at Box2D and I am making a simple game where you control the rotation of the maze and the gravity leads the ball to the exit. The game looks like The problem I want to rotate the maze, and I'm doing it well. It is a kinematic object, so it will only move when I want. But it always rotate on a static pivot, I think that's it's center of mass. Rotating the maze, the ball hits the walls and when too further to the center, it becomes hard to control the movement of the ball by rotating the maze as the centrifugue force is too high for the ball. What I want I want to change the maze's rotation pivot to the ball's position, every game loop frame, so it will rotate around the ball always and I will be able to use only gravity, not centrifuge forces, to lead the ball to the exit. What I tried I already tried to find a function to change the pivot center, or the center of mass, but I only found to change the mass proprieties. It changes the center of mass only if it was a dynamic body. Even the kinematic body having the same localCenter.x and localCenter.y proprieties as the dynamic body, it remains on (0.0 ,0.0) when trying to change it. And when changing the localCenter on the dynamic body, it doesn't rotate at this point anyway, so I'm not sure what to do. Is there any possibility to change the center of the kinematic body all the time? I'm using Box2D Vestion 2.3.2, as you can see on the picture, and Visual Studio 2013 with OpenGL. Thanks!"} {"_id": 22, "text": "Why set the position of both b2Body and Box2DSprite? In a game, we add a body for each sprite, the method is createBodyAtLocation (CGPoint) forSprite (Box2DSprite )sprite In which we create the body and we attach it to the sprite in parameter sprite.body body Then we set the position of the body, but later on in the code, in the update method, we also set the position of the sprite to the same position as the body. I was wondering Why are we doing it twice? As we already set the position of the body in the world, and we made a link between the two with sprite.body?"} {"_id": 22, "text": "Hill jumping game mechanic like Tiny Wings I'm a huge Tiny Wings fan and I'd like to understand the game mechanic at a deeper level. What are some good resources for the basic Box2d (or similar) physics behind the hill jumping game mechanic? I've used some basic features of Box2d. I imagine the flying character is just a circle, tapping the screen increases the downward force on the character, and the hills are some sort of curve object from the physics engine. Edit 1 Here's more info I'd like to understand which objects from the Box2d physics library are used to create the bare bones hill jumping mechanic. This mechanic would look like a \"curvy\" horizontal line that just scrolls across the screen. The most basic shape for this line that comes to mind is a sine wave so that's probably a good starting point. Then there's the character that moves around. Note the character's horizontal position is fixed while the vertical position moves up and down. I'm curious about which Box2d body shape, type etc is used for this character. What are some values for the coefficient of friction that work well? How about the density etc. I've searched around the web for tutorials that ideally will answer the above questions and perhaps provide additional resources regarding efficiency, camera motion and so on."} {"_id": 22, "text": "What's the best way to handle slopes for a platfomer game using Box2D I would like to know if there is any known solution for handling the player's movement on slopes using Box2D engine. I tried to do it using a circle as the player. Everything was fine until I tried to walk on slopes, the main problem is that due to gravity, the circle does not stop on the slope. Please if somebody has tried this before I'll appreciate it. If you have a better solution without the physics engine would be fine for me too. Thank you."} {"_id": 22, "text": "Frame independent box2d object movement In my game I use box2d objects and, as I understand it, you can move them only in two ways, SetLinearVelocity, and ApplyImpulse. I need to move the object 32 pixels in 1 turn. So I make a constant speed and the next problem appears. If the laptop is connected to the charge and gives 60 frames, the object begins to move faster. How do I make frameindependent movement? Without connection 30 FPS and the game makes slowly. I also know that if you want to be frameIndependent you need to use this formula x x speedPerSecond secondsElapsedSinceLastFrame But i cant use this formula, because i cant set box2d position. It is make box2d itself. I only can set the Velocity ( Or may me i just dont know. 2 it is meters per second. 64 pixels. private void handleInput(float delta) if (Gdx.input.isKeyPressed(Input.Keys.W)) b2body.setLinearVelocity(0, 2) if (Gdx.input.isKeyPressed(Input.Keys.S)) b2body.setLinearVelocity(0, 2) if (Gdx.input.isKeyPressed(Input.Keys.A)) b2body.setLinearVelocity( 2, 0) if (Gdx.input.isKeyPressed(Input.Keys.D)) b2body.setLinearVelocity(2, 0) How can i move object in another way or how to make movement frameindependent? SetTransform is not a good decision becasuse collisions are ignored. Thank You!"} {"_id": 22, "text": "Speed seems random with constant impulse I'm shooting an object from the top vertex of a triangle using Box2dWeb. The issue I'm having is that the projectile speed seems to be fairly random, even with applyimpulse set to a constant. The gravity is set to zero. I thought it could be the physics step, changing these settings hasn't made a difference. The projectile will shoot out at very very fast speeds, then it will shoot out at its defined speed. bodyman 0 .GetBody().ApplyForce( bodyman 0 .GetBody().GetWorldVector(new b2Vec2(0, 50)), bodyman 0 .GetBody().GetWorldCenter())"} {"_id": 22, "text": "Box2dWeb must fixtures be destroyed explicitly when destroying the body? I use b2WorldObj.DestroyBody(bodyObj) to destroy the body when it is not needed anymore. The body has one fixture attached to it. Do I need to destroy the fixture before destroying the body? or should I assume that by destroying the body all its fixtures will be automatically destroyed? Right now, I do not destroy the fixtures explicitly and the game runs fine. But my concern is more about memory leaks. I want to make sure that all the bodies and fixtures that are not used anymore are completely removed from the memory. How can I best achieve this? Thanks!"} {"_id": 22, "text": "In Box2D, how do I create an infinitely oscillating spring? How do I create an ideal spring that can oscillate indefinitely using Box2D? A b2DistanceJoint works almost perfectly, but it eventually slows to a stop, even with damping set to 0. I think it is because b2DistanceJoint is not meant for creating springs, but for preserving the distance between two bodies by correction the violated distance with a spring like behaviour. Hence, it should have a damping to eventually bring back the bodies to initial state and stop at some point."} {"_id": 22, "text": "Starter love2d physics program not working I am starting out with my first love2d (using L VE 0.8) physics program. I am just creating some ground floor, a car body and attaching two wheels with revolute joints and setting the motors a go. However, the car stands still, whereas I expect it to move. Can someone glance over the code below and see what I am doing wrong? UPDATE See below! function love.load() Set up world love.physics.setMeter(50) world love.physics.newWorld(0, 9.81 50, true) Window dimensions windim height love.graphics.getHeight(), width love.graphics.getWidth() objects Ground Floor objects.ground objects.ground.body love.physics.newBody(world, 300, windim.height) objects.ground.shape love.physics.newRectangleShape(2000,20) objects.ground.fixture love.physics.newFixture(objects.ground.body, objects.ground.shape) objects.ground.fixture setFriction(3) Body of the car a rectangle objects.carbody objects.carbody.body love.physics.newBody(world, 300, 500, \"dynamic\") objects.carbody.shape love.physics.newRectangleShape(100,40) objects.carbody.fixture love.physics.newFixture(objects.carbody.body, objects.carbody.shape) objects.carbody.fixture setFriction(3) objects.carbody.fixture setDensity(3) objects.carbody.fixture setRestitution(0) First wheel objects.wheel objects.wheel.body love.physics.newBody(world, 330, 520, \"dynamic\") objects.wheel.shape love.physics.newCircleShape(20) objects.wheel.fixture love.physics.newFixture(objects.wheel.body, objects.wheel.shape) objects.wheel.fixture setFriction(3) objects.wheel.fixture setDensity(3) objects.wheel.fixture setRestitution(0.6) Second wheel objects.wheel2 objects.wheel2.body love.physics.newBody(world, 270, 520, \"dynamic\") objects.wheel2.shape love.physics.newCircleShape(20) objects.wheel2.fixture love.physics.newFixture(objects.wheel2.body, objects.wheel2.shape) objects.wheel2.fixture setFriction(3) objects.wheel2.fixture setDensity(3) objects.wheel2.fixture setRestitution(0.6) Create joint between car body and first wheel objects.carbody.wheeljoint1 love.physics.newRevoluteJoint(objects.carbody.body, objects.wheel.body, 330, 520) objects.carbody.wheeljoint1 enableMotor() objects.carbody.wheeljoint1 setMaxMotorTorque(10000) Following example from http www.emanueleferonato.com 2011 08 22 step by step creation of a box2d cartruck with motors and shocks Create joint between car body and second wheel objects.carbody.wheeljoint2 love.physics.newRevoluteJoint(objects.carbody.body, objects.wheel2.body, 270, 520) objects.carbody.wheeljoint2 enableMotor() objects.carbody.wheeljoint2 setMaxMotorTorque(10000) end function love.update(dt) Set contstant speed for the wheels objects.carbody.wheeljoint1 setMotorSpeed(20) objects.carbody.wheeljoint2 setMotorSpeed(20) world update(dt) end function love.draw() love.graphics.print(objects.carbody.wheeljoint1 getMotorSpeed(), 10, 10) Render ground love.graphics.setColor(72, 160, 14) love.graphics.polygon(\"fill\", objects.ground.body getWorldPoints(objects.ground.shape getPoints())) Render car body love.graphics.setColor(72, 160, 200) love.graphics.polygon(\"fill\", objects.carbody.body getWorldPoints(objects.carbody.shape getPoints())) Render wheels love.graphics.setColor(193, 47, 14) love.graphics.circle(\"line\", objects.wheel.body getX(), objects.wheel.body getY(), objects.wheel.shape getRadius()) love.graphics.circle(\"line\", objects.wheel2.body getX(), objects.wheel2.body getY(), objects.wheel2.shape getRadius()) end UPDATE I added a line to print the angle of one of the wheels (see below). When this line is present, suddenly the car flips over from the wheels spinning when it hits the ground. This leads me to believe that something did not get initialized properly first time around. This is the line added function love.draw() love.graphics.print(objects.wheel.body getAngle(), 10, 10) Line added"} {"_id": 22, "text": "how to attach a body to a rope and making it swing to another rope I've set some ropes (using cocos2d and box2d) and would like to attach a body to one rope in such a way that it can swing to another rope. I am not sure how to go about this. I read making and object swing from one rope to another but it didn't seem to be of any help."} {"_id": 22, "text": "How to keep the value of angle between 0 and PI in box2d In box2d, if i rotate an object multiple times in clockwise or anti clockwise direction, the value of angle ( body.getAngle() ) keeps on increasing. Like at start it is at 0 radians, then 1.57(90 deg), after complete roatation 6.28, then after second rotation 2 6.28 . If a player keeps on rotating for too much time, angle value becomes really big.And for multiplayer games, sending big values uses more bytes. How can i keep the value between 0 to 3.14.Is there any solution in box2d Or Is it a good way of sending Sin(angle) to keep the value between 1 and 1 and doing reverse of sin at client side."} {"_id": 22, "text": "Stopping on a slope in Box2d I am creating a simple platformer using Box2d. I've implemented a variant of the technique described here. To make the player character move more 'platformer like' I want him to stop on (shallow) slopes. However, the engine I am using does not support angle joints, so I have trouble restricting the movement of the wheel. I've tried some different alternatives that not worked Setting the horizontal velocity to 0 every game loop doesn't seem to work, because between calls the wheel catches up speed once again. Is there another way to fix this?"} {"_id": 22, "text": "Rotating kinematic object around a moving point Box2D I'm new at Box2D and I am making a simple game where you control the rotation of the maze and the gravity leads the ball to the exit. The game looks like The problem I want to rotate the maze, and I'm doing it well. It is a kinematic object, so it will only move when I want. But it always rotate on a static pivot, I think that's it's center of mass. Rotating the maze, the ball hits the walls and when too further to the center, it becomes hard to control the movement of the ball by rotating the maze as the centrifugue force is too high for the ball. What I want I want to change the maze's rotation pivot to the ball's position, every game loop frame, so it will rotate around the ball always and I will be able to use only gravity, not centrifuge forces, to lead the ball to the exit. What I tried I already tried to find a function to change the pivot center, or the center of mass, but I only found to change the mass proprieties. It changes the center of mass only if it was a dynamic body. Even the kinematic body having the same localCenter.x and localCenter.y proprieties as the dynamic body, it remains on (0.0 ,0.0) when trying to change it. And when changing the localCenter on the dynamic body, it doesn't rotate at this point anyway, so I'm not sure what to do. Is there any possibility to change the center of the kinematic body all the time? I'm using Box2D Vestion 2.3.2, as you can see on the picture, and Visual Studio 2013 with OpenGL. Thanks!"} {"_id": 22, "text": "cocos2d Merging box2d bodies i'm using cocos2d to build an iphone game. my game currently has two sprites one for the main character and another for an item i should carry once he gets on him. the main character and the item are both box2d bodies. i can detect the collision between the two. what is want is to make the item body stick to the main character body when they meet, that way any movement of the main character would also affect the item. any suggestions on how to implement this? thanks!"} {"_id": 22, "text": "How to make box2d bodies block each other but not push each other? I want to use box2D to create a movement system for an RTS game. How can I make bodies block the movement of other bodies while preventing these bodies from pushing each other?"} {"_id": 22, "text": "in box2d how to decrease joint's reaction force? I'm trying to make a game like cut the rope and meet some problems. when I create a float bubble and connect with a rope(a sets of bodies connected with revoluteJoint), the rope will become longer and when I destroy the bubble,rope gives a a big reaction force to candy, so how to decrease this reaction force? to simulate bubble's floating, I did this class Bubble extends PhyObject override function draw() void if(this.combined) this.getBody().SetLinearVelocity(velocity) velocity new b2Vec2(0, 3.5) other code class Main public function loop() getAllPhyObject().forEach(function(phyObj) phyobj.draw() ) so if bubble was combined with candy ,It \"float\". I think maybe I can do this pseudo code if(bubble is connected with rope) dynamic adjust bubble's linear velocity with rope's reaction force but I just cannot figure out how to dynamic adjust bubble's linear velocity.and is there a simpler way to solve this problem? thanks! update finally I solved my problem,so I write it down and hope it help to you. below code is grab from b2BuoyancyController and it works in my case. buoyancy private function float() void if (bodies.length lt 1) return var body b2Body bodies 0 if(body.IsAwake() false) Buoyancy force is just a function of position, so unlike most forces, it is safe to ignore sleeping bodes return var normal b2Vec2 new b2Vec2(0, 1) var offset Number 20 var density Number 2 var velocity b2Vec2 new b2Vec2(0, 0) var linearDrag Number 2 var angularDrag Number 1 var gravity b2Vec2 toolkit.world.GetGravity().Copy() var areac b2Vec2 new b2Vec2() var massc b2Vec2 new b2Vec2() var area Number 0.0 var mass Number 0.0 for(var fixture b2Fixture body.GetFixtureList() fixture fixture fixture.GetNext()) var sc b2Vec2 new b2Vec2() var sarea Number fixture.GetShape().ComputeSubmergedArea(normal, offset, body.GetTransform(), sc) area sarea areac.x sarea sc.x areac.y sarea sc.y var shapeDensity Number 1 mass sarea shapeDensity massc.x sarea sc.x shapeDensity massc.y sarea sc.y shapeDensity areac.x area areac.y area massc.x mass massc.y mass if(area lt Number.MIN VALUE) return Buoyancy var buoyancyForce b2Vec2 gravity.GetNegative() buoyancyForce.Multiply(density area) body.ApplyForce(buoyancyForce,massc) Linear drag var dragForce b2Vec2 body.GetLinearVelocityFromWorldPoint(areac) dragForce.Subtract(velocity) dragForce.Multiply( linearDrag area) body.ApplyForce(dragForce, areac) tmpForce if(candy.bodies.length gt 0) TODO !!!!! var tmpForce b2Vec2 candy.bodies 0 .GetLinearVelocity() body.SetLinearVelocity(tmpForce) tmpForce.x 0 tmpForce.Subtract(velocity) tmpForce.Multiply( linearDrag area) body.ApplyForce(tmpForce, areac) Angular drag TODO Something that makes more physical sense? body.ApplyTorque( body.GetInertia() body.GetMass() area body.GetAngularVelocity() angularDrag) tips use force instated of impulse and changing linear velocity."} {"_id": 22, "text": "Why won't my Box2d bodies collide? I'm doing something wrong when trying to get bodies to collide using jBox2d amp Slick2d. Here is have just my basic init, update, and render methods. Render and update seem to work fine for drawing (gravity effectively pushes the ball down, and will rotate if I apply an impulse). I have a feeling I'm overlooking something when creating the edge, but I have no idea what. My shapes bodies work fine in the testbed, but I'm having no luck in my standalone application. I have experimented with moving the edge body ball body around, but it doesn't seem to have any effect. Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException world new World(new Vec2(0F, 9.8F), false) windowCenter new Vec2(gc.getWidth() 2, gc.getHeight() 2) circleShape.m radius CONSTANTS.BALL RADIUS CONSTANTS.SCALE FACTOR circleFixtureDef.shape circleShape circleFixtureDef.density 1f circleFixtureDef.restitution .6f circleBodyDef.type BodyType.DYNAMIC circleBodyDef.bullet true circleBodyDef.position.set(windowCenter) circleBody world.createBody(circleBodyDef) circleBody.createFixture(circleFixtureDef) bottomEdge.setAsEdge(new Vec2(0, gc.getHeight()), new Vec2(gc.getWidth(), gc.getHeight())) bottomEdgeDef.position.set(0f, gc.getHeight()) bottomEdgeDef.type BodyType.STATIC bottomEdgeFixtureDef.restitution .6f bottomEdgeFixtureDef.density 0f bottomEdgeBody world.createBody(bottomEdgeDef) bottomEdgeBody.createFixture(bottomEdgeFixtureDef) ball new Image(\"src main resources bball.png\") float shapeToImageFactor ball.getWidth() circleShape.m radius ball ball.getScaledCopy(1 shapeToImageFactor) circleBody.setUserData(ball) Override public void render(GameContainer gc, StateBasedGame sbh, Graphics g) throws SlickException Vec2 ballBodyPos circleBody.getPosition() ball.draw(ballBodyPos.x, ballBodyPos.y) Override public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException world.step(delta, 10, 10) ball.setRotation((float)Math.toDegrees(circleBody.getAngle())) System.out.println(world.getBodyCount()) if (world.getContactCount() gt 0) System.out.println(\"thank god, something hit another thing\") Also, the commented out bottomEdgeBody.createFixture(bottomeEdgeFixtureDef) throws a NullPointerException, and I have no idea why. Could this be related to the body not being created properly? The world body count is at 2 as I think it should be. I was also thinking that when setting the vector's Y position at my screen height, it's actually getting set at screen height meters rather than pixels. Am I overlooking something obvious?"} {"_id": 22, "text": "Client side physics simulation I am trying to create a very simple client server based physics game, using box2d library. A simple football game. Obviously, the server runs only the box2d world. My question is is it correct to state that the client should run not only the needed rendered simulation but another box2d world as well? I ask this because I know that the client should receive state information of the elements that have a changing state. And this information is received in packets every few ticks. And between every packet received, there's a time gap where I need to run the world like \"nobody did nothing\", and then correct the world state if somebody did something after I received the next packet. That is why I need to run the box2d world in the client as well, but I feel it's kinda awkward and assymetrical. Is this right? Is box2d prepared for this?"} {"_id": 22, "text": "Libgdx explain steps for beginner to create and use image as a box2d body I am basically from corona background and new to LibGdx , familiar with stage and actor from scene2D. Now wants to use physics body from box2d in the game besides using actor from scene2D. But I need to use images in the game as body... not shapes.. anyone please explain me the steps to use images as a body. Thanks.."} {"_id": 22, "text": "Why might a body suddenly stop while moving on continue platform? I have a 32x32 sprite and I make some to be platform like this for (int i 0 i lt 15 i ) attachChild(new Ground(32 i, 200, regPlatform, vertexBufferObjectManager, physicsWorld)) And I have another sprite (32x32 also) moving over those platforms (A player object) attachChild(new Player(10, 10, regPlayer, vertexBufferObjectManager, physicsWorld)) And the physicsWorld connects the player like this (Where move 1 when user click right button, and move 2 when user click left button) physicsWorld.registerPhysicsConnector(new PhysicsConnector(this, body, true, false) if (move 1) body.setLinearVelocity(new Vector2(8, body.getLinearVelocity().y)) else if (move 2) body.setLinearVelocity(new Vector2( 8, body.getLinearVelocity().y)) The Player moves smoothly form left to right and reverse. But sometimes, it is blocked. If the player move back a bit, and back again where it is blocked, it isn't blocked any more at the same place. Anyone has any idea to fix this? Maybe it is a bug of andengine and box2d and I need some trick here? Please help me. (The two sprites above are just normal png with 32x32px) Player image Platform image"} {"_id": 23, "text": "How reimport a package in UDK with command line? sometimes ago, I saw a command to re import a UDK package content without opening the UDK Editor. (Especially, it was used for reimporting a Flash package in a scaleform tutorial, but it doesn't matter now ) It's very useful, because every time I change my .swf file, I should open the heavy UDK and just press re import. So, can anyone give me that solution again ?"} {"_id": 23, "text": "How are the Unreal Development Kit (UDK) and Unreal Engine 4 (UE4) related? I'm thinking of learning Unreal Engine 4, but it costs money, and I want to try and keep costs as low as possible while I'm learning. In contrast, the Unreal Development Kit is free. How similar are the two? If I learn UDK first, how easily can I transition to UE4?"} {"_id": 23, "text": "Unrealscript splitting a string Note, this is repost from stackoverflow I have only just discovered this site ) I need to split a string in Unrealscript, in the same way that Java's split function works. For instance return the string \"foo\" as an array of char. I have tried to use the SplitString function array SplitString( string Source, optional string Delimiter \",\", optional bool bCullEmpty ) Wrapper for splitting a string into an array of strings using a single expression. as found at http udn.epicgames.com Three UnrealScriptFunctions.html but it returns the entire String. simulated function wordDraw() local String inputString inputString \"trolls\" local string whatwillitbe local int b local int x local array lt String gt letterArray letterArray SplitString(inputString,, false) for (x 0 x lt letterArray.Length x ) whatwillitbe letterArray x log('it will be ' whatwillitbe) b letterarray.Length log('letterarray length is ' b) log('letter number ' x) Output is b returns 1 whatwillitbe returns trolls However I would like b to return 6 and whatwillitbe to return each character individually. I have had a few answers proposed, however, I would still like to properly understand how the SplitString function works. For instance, if the Delimiter parameter is optional, what does the function use as a delimiter by default?"} {"_id": 23, "text": "Optimizing UV Map Sheet Based On Surface Area? I am trying to get my UV Map Sheets Optimized Based On Surface Area , I need Them optimized cause my scene area is huge and i want to use them in UDK so i am trying to get maximum possible optimization and i am running out of time Here is What i Try TO Achieve Default 3DS Max Optimized By HAND THIS IS WHAT I WANT Or Even Better If There Is Automated Intelligence Tool Also I know this Tools Flatiron , UVPacker But They Are No Use"} {"_id": 23, "text": "How should I set up UDK with Git and CruiseControl? For a new project in UDK, I'd like to set up a Git repository for version control and a CruiseControl.NET based continuous integration solution. The good news is that he first part seems easy enough and CruiseControl.NET can work off Git repositories. The bad news is that according to my searches, nobody has ever tried to do this. Ideally, I'm looking for a step by step guide on how to set up such a development environment assuming more than one development computer, one central repository for the \"master\" branch, and one machine for building and packaging the binaries via CruiseControl.NET. Related Version control system for game development with UDK? Options for UDK and version control repositories? CruiseControl.NET and Git"} {"_id": 23, "text": "How to add melee weapons in UDK? I am very new to game design and programming in Unrealscript for UDK. I have created a weapon mesh and imported it alongside it's animation set and created a start and end socket on it. I was wondering if anyone could help me create a weapon class for it and allow it to be used in the game?"} {"_id": 23, "text": "Push and damage player pawn when hit by rotating pawn? (UDK) I'm working on a game in which the player runs around a level themed as a pinball machine. There are flippers that react to the presence of pinballs by flipping (as one would expect pinball flippers to do). The problem that I'm having is that if the player is in the path of the flipper as it rotates, the player is instantly killed. The desired behavior is that the player is damaged and pushed away from the moving flipper. I've tried all sorts of things to make this stop happening. Currently, in the flipper, I have the following code to handle the collision event Bump(Actor other, PrimitiveComponent otherComp, Object.Vector hitNormal) local vector pushVelocity if( If Flipper is moving and is bump()ing the Player ) pushVelocity hitNormal CalcLinearVelocity(vsize(location other.location)) player.TakeDamage(playerDamage, none, player.Location, pushVelocity 2.1f, class'DamageType', , self) By using all sorts of logging, I can determine that the code in question is being called when the flipper hits the player and the player is being killed on the first frame this collision occurs logging within the if() block only appears once. And yes, playerDamage is a value low enough that it would take many hits to kill the player. Does anyone have any insight as to why the player is immediately dying instead of being damaged and pushed away? Or what sorts of things I should try to get my intended behavior?"} {"_id": 23, "text": "SetBase with a KActor descendant does not appear to function I have a KActor descendant, which is a carging shot, kind of like in R Type. When it starts charging, I do projectile.SetBase(Pawn) in the PlayerController where it is spawned. I've checked in the debugger, and its base is in face the pawn. But it does not move with the pawn. I have done this before, where I base KActors on a moving entity, and it moved with them. I must have done something differently, but I can't figure out what it was. Looking at the old code, I just did SetBase like I am now. Any ideas where I might be going wrong?"} {"_id": 23, "text": "UDK Checking actor type in projectile ProcessTouch So, to be brief, I'm trying to teleport a pawn when it's struck by a projectile (or damaged by any weapon in my game.) Right now, I'm trying to just call Pawn.SetLocation in the projectile's ProcessTouch. That's a problem because ProcessTouch will hit any actor, not just a pawn. Additionally, any attempts to check the ProcessTouch's \"Actor Other\" throws errors. I've tried a bunch of solutions (including making a event TakeDamage in the Pawn controller class,) but to no avail. simulated function ProcessTouch(Actor Other, Vector HitLocation, Vector HitNormal) if (Other ! Instigator) This is where the Other.TakeDamage goes if we are using a traditional gun. if (Other Pawn) Other.SetLocation(0,0,0) Destroy This code complains that Pawn's a bad expression. How else should I check actor type here?"} {"_id": 23, "text": "Get Final output from UDK ( sorry for my bad english in advance D ) I'm trying to get a .exe setup output, from my UDK !( with my own maps and scripts which I made within MyGame) I tried UnrealFrontEnd! But It made a setup , that after installation I can see my .udk maps, my packages and etc. But It's not a real output that I can show to my customers. I don't want, other can use my resources ! So... How can I get a binary like output from UDK as a real Game Output ? ( like what we see in all commercial games ) Is there any option in frontend that I missed ?"} {"_id": 23, "text": "Optimizing UV Map Sheet Based On Surface Area? I am trying to get my UV Map Sheets Optimized Based On Surface Area , I need Them optimized cause my scene area is huge and i want to use them in UDK so i am trying to get maximum possible optimization and i am running out of time Here is What i Try TO Achieve Default 3DS Max Optimized By HAND THIS IS WHAT I WANT Or Even Better If There Is Automated Intelligence Tool Also I know this Tools Flatiron , UVPacker But They Are No Use"} {"_id": 23, "text": "UnrealEngine how to create pirate boat tutorial I fount an Unity tutorial how to crate pirate boat, but I still can't find any sources (links, videos) how to create it using UE. Kind of this. So when you use character controller it can jump, run and etc, but with a boat you should smoothly running trough the waves with some bouncing effects. So I try to find tutorial that describe how to create this pirate boat. So the question not about model, so I can even use a cube that I can move through waves."} {"_id": 23, "text": "How to factorize code in Unreal Kismet (i.e. \"Material Function\"s for Kismet) In the Unreal Development Kit, when using the Material Editor, one can factorize frequently used groups of nodes by creating a Material Function (content Browser right click new matrial function, IIRC). When defining the behaviour of some actor in Kismet, one can easily have a dozen nodes involved. If I have many actors that share the same behaviour, then I'll copy paste these nodes, and change the variables so they point to the other actors. This leads to inconsistencies (a modification in the behaviour of an actor isn't propagated in the copy pasted nodes), complexity (you end up with hundreds of nodes), and generally useless effort. My question is Can I create a \"kismet function\", just like a material function ? Note I'd rather avoid using UnrealScript. I don't even know where to type UnrealScripts, don't know where the documentation is and more generally don't have enough time to invest in learning UnrealScript. This \"kismet function\" feature must be usable by graphists (with little programming knowledge). If a (simple) script suffices to add this feature in the Kismet editor, so that one can create several \"functions\" without using UnrealScript, then fine, but I don't really want to have to write a script each time I want to factorize a few nodes. Thanks for any information !"} {"_id": 23, "text": "Why might a Projectile hitting a KActor only call HitWall, and not ProcessTouch? I have a Projectile subclass that seems to work fine. It travels, does Explode(), etc. But when it hits one of our KActors, I get a HitWall event but not a ProcessTouch event. So my question is, why would a colliding actor trigger HitWall, but not ProcessTouch?"} {"_id": 23, "text": "differences in UDK map on different installs My goal is to create a simple groundplane in UDK (11 2012 version, fresh install) that the user will be able to run around on. My requirements are therefore very basic and I tried to whip something up quickly in the editor. I created a circular (cylinder) plane and applied a material. I added a Blocking Volume, a Lightmass Importance Volume, and a Sky Light. I built everything and get no errors. The map played fine on my system. I transferred the file to another system with the same version of UDK (also a recent install). When I try to play the map, I plunge to my death. Though I have verified that my player start position is above the ground, I seem to start below the ground looking up at it. What could cause a map that works great on one system have such a positioning issue on another system? I believe this is a valid question. I'm obviously going to need to systematically test things and I already have tried moving the player start etc. However, I will need to have some idea of what can differ between installs. I'm extremely new to the UDK. Thanks."} {"_id": 23, "text": "Import FBX with multiple meshes into UDK I used this script to generate a few buildings that I was hoping to import into UDK. Each building is made of about 1000 separate objects. When I export a building as FBX and import the file into UDK it breaks it up into its individual objects again, so I was wondering how I would avoid this. Whether there was a tool to combine all of the objects into one mesh automatically before exporting or if I could prevent UDK from breaking them upon import."} {"_id": 23, "text": "3D Game Engine comparable to UDK that's not GPL'd Are there any good, free 3D game engines similar to UDK that are under open source licenses without copyleft provisions?"} {"_id": 23, "text": "Hidden Loading with UDK I was wondering, how would I go about creating hidden loading scenes with UDK? For example, a character walks in to an elevator, the elevator fakes movement, whilst the previous floor is destroyed and the next floor is loaded on top. I assume it's possible with UDK, since it's supposedly rather flexible, but I've never used UDK before (I decided to ask this question first to save me learning it all, finding out it isn't possible, then giving up). So yeah, is hiding the loading process possible? And if so, how would I go about doing it?"} {"_id": 23, "text": "How do I make game server for UDK game? I'm new in UDK and I'm starting to develop online multiplayer games. There is a one problem, I couldn't find any tutorials about how to make a game server using udk. I suppose, that it uses unreal script. But that's about all I know about it. So I'd really like for some help."} {"_id": 23, "text": "3D Game Engine comparable to UDK that's not GPL'd Are there any good, free 3D game engines similar to UDK that are under open source licenses without copyleft provisions?"} {"_id": 23, "text": "Changing State in PlayerControler from PlayerInput In my player input I wanna change the the \"State\" of my player controller but I have some trouble to do it my player input is declared like that class ResistancePlayerInput extends PlayerInput within ResistancePlayerController config(ResistancePlayerInput) and in my playerControler I have that class ResistancePlayerController extends GamePlayerController var name PreviousState DefaultProperties CameraClass class 'ResistanceCamera' Telling the player controller to use your custom camera script InputClass class'ResistanceGame.ResistancePlayerInput' DefaultFOV 90.f Telling the player controller what the default field of view (FOV) should be simulated event PostBeginPlay() Super.PostBeginPlay() auto state Walking event BeginState(name PreviousStateName) Pawn.GroundSpeed 200 log(\"Player Walking\") state Running extends Walking event BeginState(name PreviousStateName) Pawn.GroundSpeed 350 log(\"Player Running\") state Sprinting extends Walking event BeginState(name PreviousStateName) Pawn.GroundSpeed 800 log(\"Player Sprinting\") I have tried to use PCOwner.GotoState() and ResistancePlayerController(PCOwner).GotoState() but won't work. I have also tried a simple GotoState, and nothing happen how can I call GotoState for the PC Class from my player input ?"} {"_id": 23, "text": "UDK Problem with Touching Actors In my game I am trying to see all touching actors of a particular DynamicSMActor and it does return only two Actors as touching Actors Water Volume and Player Pawn. It is ignoring all the other DynamicSMActors that are touching. I actually tried different values for collision type, Blocking type, etc,. No success. Any help is really appreciated."} {"_id": 23, "text": "Unreal Engine Scaleform How do I capture a button click event? I'm new to Unreal Development. In a nutshell, how do I create a button, install it in a basic game, and capture the button click event?"} {"_id": 23, "text": "How do I create an actor class in UDK that will spawn a specific particle system? I'm trying to write a new class that I can drag from actor classes window into the scene and it will spawn a specific particle effect. Its going to be a 'prop' that later will also contain a static mesh and a point light. Maybe some defined variables that can be changed in the properties window. So far, I have the static mesh working using this code class LightFixture extends StaticMeshActor defaultproperties Begin Object Class StaticMeshComponent Name myMesh bAllowApproximateOcclusion TRUE bForceDirectLightMap TRUE bUsePrecomputedShadows TRUE StaticMesh StaticMesh'props.Meshes.lamp' End Object Components.Add(myMesh) now, I'd like to add a particle system (template?), and from what I'm learning, it's not as easy as adding the mesh. In a new class, I tried to add a particle effect this way class FireParticle extends EmitterPool placeable var ParticleSystemComponent PSC defaultproperties Begin Object Class ParticleSystemComponent Name myEffect bAutoActivate true Template ParticleSystem'props.FX.fire' End Object ParticleSystemComponent myEffect Components.Add(myEffect) So that didn't work... I read somewhere that emitterpool was the way to spawn.. I am very new to scripting, if that isn't already obvious ) thanks in advance, if anyone can help.."} {"_id": 23, "text": "How do I avoid Race Conditions in UnrealScript? I'm trying to create a pseudo turn based battle system in the Unreal Engine (think Final Fantasy style). I'm trying to avoid the Enemies and the players attacking while another animation is in progress. I thought the most simple solution is to have a flag somewhere that the player controllers check before starting an animation, and set it to a value before they start, and then reset it when they've finished. However, I could see this leading to race conditions if two controllers (AI or player) try to access the variable at the same time, then both start their animations. If I was writing this in Java I'd obviously use synchronized methods, but I haven't come across anything like that in UnrealScript. Is there another way to avoid this? Its probably not the end of the world, as its a pretty unlikely occurance, but I'd like to try and avoid it completely if possible."} {"_id": 23, "text": "How should I set up UDK with Git and CruiseControl? For a new project in UDK, I'd like to set up a Git repository for version control and a CruiseControl.NET based continuous integration solution. The good news is that he first part seems easy enough and CruiseControl.NET can work off Git repositories. The bad news is that according to my searches, nobody has ever tried to do this. Ideally, I'm looking for a step by step guide on how to set up such a development environment assuming more than one development computer, one central repository for the \"master\" branch, and one machine for building and packaging the binaries via CruiseControl.NET. Related Version control system for game development with UDK? Options for UDK and version control repositories? CruiseControl.NET and Git"} {"_id": 23, "text": "What exactly is the difference between Unreal Development Kit and Uunreal Engine 4? I want to start learning game development and I would obviously come across this tool. So every where I went people mentioned Unreal Engine 4 to be a viable choice, I've tried a bit of Unity and now I want to try Unreal. Only issue I came across UDK and UE4, I downloaded UDK which turns out to be different from tutorials and I can't seem to find any info on that and besides I could only run the software once because after the first time it starts a game, I re installed UDK I still get the issue, but anyways that's a different topic, what I want to know is whether UDK and UE4 are different and if they are, where do i get UE4, becauuse when I down UE4 (from https www.unrealengine.com dashboard), it downloads a game launcher and no development tool. In case they are same, why is my version of UDK different fr"} {"_id": 23, "text": "Transfer my UDK 2 project to UDK 3? Is it possible to export my UDK 2 project to UDK 3 ? What kinds of things aren't transferable?"} {"_id": 23, "text": "Valve Source Engine UDK and CUDA Do any games use the GPU for more game tasks than just rendering, as a way to reduce the game's load on the CPU? I'm most interested in games which use either Valve's Source engine or the UDK. Is it possible effective to even do such a thing?"} {"_id": 23, "text": "Push and damage player pawn when hit by rotating pawn? (UDK) I'm working on a game in which the player runs around a level themed as a pinball machine. There are flippers that react to the presence of pinballs by flipping (as one would expect pinball flippers to do). The problem that I'm having is that if the player is in the path of the flipper as it rotates, the player is instantly killed. The desired behavior is that the player is damaged and pushed away from the moving flipper. I've tried all sorts of things to make this stop happening. Currently, in the flipper, I have the following code to handle the collision event Bump(Actor other, PrimitiveComponent otherComp, Object.Vector hitNormal) local vector pushVelocity if( If Flipper is moving and is bump()ing the Player ) pushVelocity hitNormal CalcLinearVelocity(vsize(location other.location)) player.TakeDamage(playerDamage, none, player.Location, pushVelocity 2.1f, class'DamageType', , self) By using all sorts of logging, I can determine that the code in question is being called when the flipper hits the player and the player is being killed on the first frame this collision occurs logging within the if() block only appears once. And yes, playerDamage is a value low enough that it would take many hits to kill the player. Does anyone have any insight as to why the player is immediately dying instead of being damaged and pushed away? Or what sorts of things I should try to get my intended behavior?"} {"_id": 23, "text": "How do you set event after a pawn takes damage? How can I set event after bot pawn takes damage in UDK? (possibly in Kismet?) I need to do something similar to this http www.youtube.com watch?v gjRf5lTcWLY"} {"_id": 23, "text": "Hidden Loading with UDK I was wondering, how would I go about creating hidden loading scenes with UDK? For example, a character walks in to an elevator, the elevator fakes movement, whilst the previous floor is destroyed and the next floor is loaded on top. I assume it's possible with UDK, since it's supposedly rather flexible, but I've never used UDK before (I decided to ask this question first to save me learning it all, finding out it isn't possible, then giving up). So yeah, is hiding the loading process possible? And if so, how would I go about doing it?"} {"_id": 23, "text": "Using Canvas instead of Scaleform in UDK I'm working with Unreal Script, and I need to use Canvas instead of Scaleform to create a HUD. I've extended the game type from UTGame, and used bUseClassicHUD in the Default Properties section, but the default Scaleform HUD continues to appear. I know for certain that I have everything configured properly to load and run the scripts, but this one line just doesn't seem to have any effect. DefaultProperties Disable the scaleform (flash) HUD in the UTGame bUseClassicHUD true Initial score value nScore 0 Initial time value m gameTimer 30.0 Is there something else I need to include? I've done a reinstall (I'm using the July 2013 build), but to no avail."} {"_id": 23, "text": "Does Unreal Engine Has Good grapic texture editor or I have to Learn Maya? I'm new in game Development , and I had no experience of it (except programming) So , for my Engine , I preferred to use Unreal Engine. So here's the question Are Maya or 3D'sMax needed to be learned or Unreal Engine has a built in Editor ? and , in comment , After i learned graphic , witch programming Language Does Unreal Engine support and recommended ?"} {"_id": 23, "text": "Hidden Loading with UDK I was wondering, how would I go about creating hidden loading scenes with UDK? For example, a character walks in to an elevator, the elevator fakes movement, whilst the previous floor is destroyed and the next floor is loaded on top. I assume it's possible with UDK, since it's supposedly rather flexible, but I've never used UDK before (I decided to ask this question first to save me learning it all, finding out it isn't possible, then giving up). So yeah, is hiding the loading process possible? And if so, how would I go about doing it?"} {"_id": 23, "text": "UDK Packaging the Game I have set up all the config files to my game classes and am able to launch the game to test everything. Although when I package the game, it still runs the UT deathmatch game?? What other lines in the config files should be changed to make it default to my game and default map once published?"} {"_id": 23, "text": "How do I avoid Race Conditions in UnrealScript? I'm trying to create a pseudo turn based battle system in the Unreal Engine (think Final Fantasy style). I'm trying to avoid the Enemies and the players attacking while another animation is in progress. I thought the most simple solution is to have a flag somewhere that the player controllers check before starting an animation, and set it to a value before they start, and then reset it when they've finished. However, I could see this leading to race conditions if two controllers (AI or player) try to access the variable at the same time, then both start their animations. If I was writing this in Java I'd obviously use synchronized methods, but I haven't come across anything like that in UnrealScript. Is there another way to avoid this? Its probably not the end of the world, as its a pretty unlikely occurance, but I'd like to try and avoid it completely if possible."} {"_id": 23, "text": "How can I disable the green frames after a cinematic in UDK? These green frames appear in my scene after the display of a cinematic (which I just added recently) How can I remove them, ideally without resorting to transitioning the game mode?"} {"_id": 23, "text": "UDK Toggle Material on Brushes? I'm attempting to change toggle the material that's applied to a BSP brush. I've seen where it's possible on static meshes, but I can't seem to get it to work on brushes. Below is an example scenario. The ground (BSP Brush) is covered in a stone material The player hits a trigger. A new \"moss\" material is applied to the brush, removing the old stone material. Any assistance you could offer would be greatly appreciated."} {"_id": 23, "text": "UnrealScript access variable in one class from another? So there are some similar questions out there but the responses often say that you should use 'new' or 'spawn', but I'm working with the playercontroller don't want to make a new playercontroller. Maybe this isn't the right way to be doing this but I want to view the state of a variable in the playercontroller that will change fairly often from my HUD. Is there a way to do this? playercontroller class var bool bYeaNo exec function change() bYeaNo !bYeaNo defaultproperties bYeaNo false HUD class event PostRender() Super.PostRender() function DrawHUD() Super.DrawHUD() Canvas.SetDrawColor(0, 0, 0) Canvas.SetPos(25, 25) if (bYeaNo) this is wrong so what would make this work? Canvas.DrawText(\"Yea\") else Canvas.DrawText(\"No\")"} {"_id": 23, "text": "How to detect the device type in UnrealScript? How can I recognize if the player device is an iPad or an iPhone? Now I can do it by checking the viewport size. But I think is just a tricky way, is there any other, more standard way?"} {"_id": 23, "text": "Deleting Objects Before Export from Maya Causes .PSK to Crash UDK on Import I'm using Maya 2008 Complete and 03 11 build of UDK as well as 07 10 build (haven't got around to installing newer version on other computer). I am using ActorX to export. I have a character that I have rigged and animated (I'm not using UDK rigs). Here was my process Early on in the process, I had other objects skinned to the character's skeleton. I hid those objects while weighting the character I decided later that I wanted to delete them. I tested my .psk in both UDK builds with those objects hidden and noticed that they still showed up (in UDK) So, I went back into Maya, detached the skin on those objects and deleted history, then deleted them. I then re exported my .psk and now when I try and import, udk crashes. Here are my input output connections for one of the objects before detaching the skin. http i.stack.imgur.com hoDdv.jpg Here is my log 0002.77 Log gt gt gt gt gt gt gt gt gt gt gt gt gt gt Initial startup 2.77s lt lt lt lt lt lt lt lt lt lt lt lt lt lt lt 0002.81 Cmd MODE MAPEXT udk 0002.87 SourceControl Source Control disabled in GAMEEditorUserSettings.ini. SourceControl has Disabled False 0005.61 Log TIMER ALL OF INIT 5.028131 0070.42 Log FactoryCreateBinary SkeletalMesh with SkeletalMeshFactory (0 0 Z websterProject2 EXPORTTESTING SK snailMesh01.PSK) 0070.42 Log Skeletal skin VPoints 812 0070.42 Log Skeletal skin VVertices 1166 0070.42 Log Skeletal skin VTriangles 1596 0070.42 Log Skeletal skin VMaterials 1 0070.42 Log Skeletal skin VBones 73 0070.42 Log Skeletal skin VRawBoneInfluences 1520 0070.42 Log Skeletal skin VertexColors 0 0070.42 Log Skeletal skin Num Tex Coords 1 0070.42 Log Mesh material not found among currently loaded ones lambert3SG 0070.42 Log Bones digested 73 Depth of hierarchy 15 0070.49 Critical appError called Assertion failed Wedges.Num() WedgeInfluenceIndices.Num() File c depot UnrealEngine3 Development Src Engine Src UnSkeletalTools.cpp Line 301 Stack Address 0x402228f9 (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x40924bb1 (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x412bfbc8 (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x401a178d (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x412964a4 (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x412823a4 (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x983633 (filename not found) in C UDK UDK 2010 07 Binaries Win64 wxmsw28u vc custom 64.dll Address 0x983d73 (filename not found) in C UDK UDK 2010 07 Binaries Win64 wxmsw28u vc custom 64.dll Address 0x983e30 (filename not found) in C UDK UDK 2010 07 Binaries Win64 wxmsw28u vc custom 64.dll Address 0x800a34c6 (filename not found) in C UDK UDK 2010 07 Binaries Win64 wxmsw28u core vc custom 64.dll Address 0x800aec65 (filename not found) in C I would like to know why deleting these objects is causing the .psk to crash on import and how I can fix it. Thanks very much for your time."} {"_id": 23, "text": "Hidden Loading with UDK I was wondering, how would I go about creating hidden loading scenes with UDK? For example, a character walks in to an elevator, the elevator fakes movement, whilst the previous floor is destroyed and the next floor is loaded on top. I assume it's possible with UDK, since it's supposedly rather flexible, but I've never used UDK before (I decided to ask this question first to save me learning it all, finding out it isn't possible, then giving up). So yeah, is hiding the loading process possible? And if so, how would I go about doing it?"} {"_id": 23, "text": "Options for UDK and version control repositories? Another developer and I have begun to experiment with the Unreal Development Kit and have installed the UDK to our local computers. He's been toying around and experimenting and has some basic code and assets already developed. We want to set up a VCS repository so we can collaborate on development of a UDK project. Some things we've noticed Source code goes in Development Src GameName . Binary Content and other assets go in UDKGame . The rest of the folders in the root directory are for the core UDK installation. In terms of repositories, we've already come up with several options Commit everything (even the core UDK code). Pro Easy Con We're committing lots of code that, while a dependency of our project, isn't technically part of the project. Commit the two folders we contribute to in two separate repositories. Pro Isolates versioned code to stuff we create. Con Slightly more difficult to set up, commits for one fix span multiple repositories, and we're committing a lot of binary content. Change the config so both the src and the assets live in one folder, then commit that. Pro Isolates versioned code, commits for changes are in one repo. Con Committing binary content. Commit SRC to one repo, use another solution for assets (FTP, Dropbox, etc) Pro Isolates versioned code, no extra overhead in versioning binary content. Con Changes span multiple places and manual updates to a remote storage solution are needed. As we assess the best way to go about this so we don't back ourselves into a corner later, I'm wondering if there are other options and what their pros and cons are. I realize we could easily just pick a solution and change it up once we ran into scaling issues, but version control has always been one of those things I like to do once upfront and then forget about when I work on projects."} {"_id": 23, "text": "Unreal Engine Scaleform How do I capture a button click event? I'm new to Unreal Development. In a nutshell, how do I create a button, install it in a basic game, and capture the button click event?"} {"_id": 23, "text": "How do I make game server for UDK game? I'm new in UDK and I'm starting to develop online multiplayer games. There is a one problem, I couldn't find any tutorials about how to make a game server using udk. I suppose, that it uses unreal script. But that's about all I know about it. So I'd really like for some help."} {"_id": 23, "text": "UDK license (DLLBind) I dont understand part of UDK's license about DLLBind does it allow to use DLLBind in UDK projects? Could I use DLLBind for commercial games without buying c native license?"} {"_id": 23, "text": "UnrealScript access variable in one class from another? So there are some similar questions out there but the responses often say that you should use 'new' or 'spawn', but I'm working with the playercontroller don't want to make a new playercontroller. Maybe this isn't the right way to be doing this but I want to view the state of a variable in the playercontroller that will change fairly often from my HUD. Is there a way to do this? playercontroller class var bool bYeaNo exec function change() bYeaNo !bYeaNo defaultproperties bYeaNo false HUD class event PostRender() Super.PostRender() function DrawHUD() Super.DrawHUD() Canvas.SetDrawColor(0, 0, 0) Canvas.SetPos(25, 25) if (bYeaNo) this is wrong so what would make this work? Canvas.DrawText(\"Yea\") else Canvas.DrawText(\"No\")"} {"_id": 23, "text": "Deleting Objects Before Export from Maya Causes .PSK to Crash UDK on Import I'm using Maya 2008 Complete and 03 11 build of UDK as well as 07 10 build (haven't got around to installing newer version on other computer). I am using ActorX to export. I have a character that I have rigged and animated (I'm not using UDK rigs). Here was my process Early on in the process, I had other objects skinned to the character's skeleton. I hid those objects while weighting the character I decided later that I wanted to delete them. I tested my .psk in both UDK builds with those objects hidden and noticed that they still showed up (in UDK) So, I went back into Maya, detached the skin on those objects and deleted history, then deleted them. I then re exported my .psk and now when I try and import, udk crashes. Here are my input output connections for one of the objects before detaching the skin. http i.stack.imgur.com hoDdv.jpg Here is my log 0002.77 Log gt gt gt gt gt gt gt gt gt gt gt gt gt gt Initial startup 2.77s lt lt lt lt lt lt lt lt lt lt lt lt lt lt lt 0002.81 Cmd MODE MAPEXT udk 0002.87 SourceControl Source Control disabled in GAMEEditorUserSettings.ini. SourceControl has Disabled False 0005.61 Log TIMER ALL OF INIT 5.028131 0070.42 Log FactoryCreateBinary SkeletalMesh with SkeletalMeshFactory (0 0 Z websterProject2 EXPORTTESTING SK snailMesh01.PSK) 0070.42 Log Skeletal skin VPoints 812 0070.42 Log Skeletal skin VVertices 1166 0070.42 Log Skeletal skin VTriangles 1596 0070.42 Log Skeletal skin VMaterials 1 0070.42 Log Skeletal skin VBones 73 0070.42 Log Skeletal skin VRawBoneInfluences 1520 0070.42 Log Skeletal skin VertexColors 0 0070.42 Log Skeletal skin Num Tex Coords 1 0070.42 Log Mesh material not found among currently loaded ones lambert3SG 0070.42 Log Bones digested 73 Depth of hierarchy 15 0070.49 Critical appError called Assertion failed Wedges.Num() WedgeInfluenceIndices.Num() File c depot UnrealEngine3 Development Src Engine Src UnSkeletalTools.cpp Line 301 Stack Address 0x402228f9 (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x40924bb1 (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x412bfbc8 (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x401a178d (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x412964a4 (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x412823a4 (filename not found) in C UDK UDK 2010 07 Binaries Win64 UDK.exe Address 0x983633 (filename not found) in C UDK UDK 2010 07 Binaries Win64 wxmsw28u vc custom 64.dll Address 0x983d73 (filename not found) in C UDK UDK 2010 07 Binaries Win64 wxmsw28u vc custom 64.dll Address 0x983e30 (filename not found) in C UDK UDK 2010 07 Binaries Win64 wxmsw28u vc custom 64.dll Address 0x800a34c6 (filename not found) in C UDK UDK 2010 07 Binaries Win64 wxmsw28u core vc custom 64.dll Address 0x800aec65 (filename not found) in C I would like to know why deleting these objects is causing the .psk to crash on import and how I can fix it. Thanks very much for your time."} {"_id": 23, "text": "UDK Toggle Material on Brushes? I'm attempting to change toggle the material that's applied to a BSP brush. I've seen where it's possible on static meshes, but I can't seem to get it to work on brushes. Below is an example scenario. The ground (BSP Brush) is covered in a stone material The player hits a trigger. A new \"moss\" material is applied to the brush, removing the old stone material. Any assistance you could offer would be greatly appreciated."} {"_id": 24, "text": "Unity 5 Camera Functions Usage Error How to use functions like ScreenToRayPoint() in Camera class? I have used this code Ray ray camera.ScreenPointToRay(Input.mousePosition) and it says Component.camera is obsolete, instead using GetComponent() Then I tried these Camera cam GetComponent lt Camera gt () Ray ray cam.ScreenToRayPoint(Input.mousePosition) and it says Camera doesn't contain a definition of ScreenPointToRay and no extension method 'ScreenPointToRay' accepting a first argument of type 'Camera' could be found."} {"_id": 24, "text": "Camera (pole cam) implementation problem In my project I have simple scene graph to render whole scene and Bullet physics SDK to provide physics simulation. Each rendered object is represented as scene node. Camera always has target and located behind this target. Target can be any scene node. First, I want to describe my rendering pipeline. 1)When time to render whole scene, we calculate view matrix from target's world matrix. We take offset vector in order to locate camera behind targeted scene node and transform it to scene node world's coordinate. Then add position of target with transformed offset vector. Finally, get inverse matrix of scene node. This method always is called before rendering whole scene. HRESULT CameraNode SetViewTransform(Scene pScene) If there is a target, make sure the camera is rigidly attached right behind the target if(m pTarget) Mat4x4 mat m pTarget gt VGet() gt ToWorld() Vec4 at m CamOffsetVector Vec4 atWorld mat.Xform(at) Vec3 pos mat.GetPosition() Vec3(at) mat.SetPosition(pos) VSetTransform( amp mat) Set normal matrix and calculate inverse matrix m View VGet() gt FromWorld() Get inversed matrix pScene gt GetRenderer() gt VSetViewTransform( amp m View) return S OK 2)Then, when time to render particular scene node, we calculate projection matrix and send it to the vertex shader. Mat4x4 CameraNode GetWorldViewProjection(Scene pScene) Mat4x4 world pScene gt GetTopMatrix() Mat4x4 view VGet() gt FromWorld() Mat4x4 worldView world view return m Projection worldView I have next problem, when I calculate view matrix from target's world matrix and locate target on coordinate ( x 0 y 10 z 1) it started to fall due to physics and jerk twitch. 1 When I set view camera matrix only offset position. Scene node falls without jerking twitching. 2 How I can fix this jerking twitching when camera is following the scene node ? I suppose that it is problem of matrices multiplication, when Bullet SDK sets new coordinates to scene node. But I have no idea how it can be solved."} {"_id": 24, "text": "Min. Distance for Spotlights in Ogre3d? I have a simple scene with only one empty box. Within that box I have the camera attached to a scene node, which the user can move (translate rotate). Additionally a spotlight is attached to the camera's scene node, facing into the same direction as the camera. So when the camera is moved, then the light moves as well. m pCamera m pSceneMgr gt createCamera(\"Camera\") m pCamera gt setNearClipDistance(0.01) m pCamNode gt attachObject(m pCamera) Light spotLight m pSceneMgr gt createLight(\"spotLight\") spotLight gt setType(Light LT SPOTLIGHT) spotLight gt setDiffuseColour(1, 1, 1) spotLight gt setSpecularColour(1, 1, 1) spotLight gt setSpotlightRange(Degree(50), Degree(100)) spotLight gt setSpotlightNearClipDistance(0) spotLight gt setDirection(m pCamera gt getDirection()) m pCamNode gt attachObject(spotLight) So, this basically works fine. There is one problem though As soon as the user moves the camera very close to a side of the box, then suddenly all is black, I can't see anyting. I am sure the camera is NOT moving through the box's side, it is still within the box. So the problem seems to be that the light does not \"work\" when it is too close to an object, as if the object (the box side in my case) is not reflecting the light any more. Any ideas?"} {"_id": 24, "text": "Swapping Y and Z causes problems with Camera I am trying to swap the Y and Z axis in my program. Everything worked great when Y used to be the axis coming out of the plane. After having swapped y and x, I have been able to draw my terrain using the X Y as the plane and Z as the height, however when converting the code for the camera I am running into trouble. Here is the code that gives me the correct camera (so y is the axis coming out of the plane), along with an illustration. The code is in SharpDX which is a C wrapper for DirectX Setup the position of the camera in the world. Vector3 position new Vector3(PositionX, PositionY, PositionZ) Setup where the camera is looking forwardby default. Vector3 lookAt new Vector3(0, 0, 1.0f) Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians. float pitch RotationX 0.0174532925f float yaw RotationY 0.0174532925f float roll RotationZ 0.0174532925f Create the rotation matrix from the yaw, pitch, and roll values. Matrix rotationMatrix Matrix.RotationYawPitchRoll(yaw, pitch, roll) Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin. lookAt Vector3.TransformCoordinate(lookAt, rotationMatrix) Vector3 up Vector3.TransformCoordinate(Vector3.UnitY, rotationMatrix) Translate the rotated camera position to the location of the viewer. lookAt position lookAt Finally create the view matrix from the three updated vectors. ViewMatrix Matrix.LookAtLH(position, lookAt, up) Here is an illustration of what this produces, I am able to successfully move the camera around with the mouse by having the mouse differences affect the x and y rotation Now if I swap all the X and Y in my terrain, without affecting the camera, I get this So now the camera is facing the terrain directly, and attempts to yaw will not produce the desired view. (the world will revolve around the camera when looking perpendicular to the terrain, and spin in place when looking at the horizon, the exact opposite of what we want.) Now I thought that maybe if I just change the lookAt to 0, 1.0f, 0 swap the y and z rotations, and change the Up vector to use Vector3.UnitZ, it would solve all my problems. Setup the position of the camera in the world. Vector3 position new Vector3(PositionX, PositionY, PositionZ) Setup where the camera is looking forwardby default. Vector3 lookAt new Vector3(0, 1.0f, 0) Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians. float pitch RotationX 0.0174532925f float yaw RotationZ 0.0174532925f float roll RotationY 0.0174532925f Create the rotation matrix from the yaw, pitch, and roll values. Matrix rotationMatrix Matrix.RotationYawPitchRoll(yaw, pitch, roll) Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin. lookAt Vector3.TransformCoordinate(lookAt, rotationMatrix) Vector3 up Vector3.TransformCoordinate(Vector3.UnitZ, rotationMatrix) Translate the rotated camera position to the location of the viewer. lookAt position lookAt Finally create the view matrix from the three updated vectors. ViewMatrix Matrix.LookAtLH(position, lookAt, up) However, doing this, I get the same issue as before, the world will revolve around when looking perpendicular to the ground, but spin in place when looking parallel to the ground (so towards the horizon). I believe the camera now looks like this Which doesn't make sense to me, since I thought changing the Up vector to UnitZ would make Z face up and not parallel to the ground. Any suggestions to change the second code block is appreciated."} {"_id": 24, "text": "Camera view projection issue I made a simple OpenGL program but I can figure out why the camera is not working, here it's a little fragment of the Camera class public Matrix4f getView() initializes the view matrix return new Matrix4f().lookAt( new Vector3f(0f, 0f, 1f), camera position at 0,0,1 new Vector3f(0f, 0f, 0f), camera target at 0,0,0 new Vector3f(0f, 1f, 0f)) up axis set to \"worldUp\" (0,1,0) public Matrix4f getProjection() return new Matrix4f().perspective( (float) Math.toRadians(fieldOfView), the fov has a value between 0f and 180f, by default I set it to 90 viewportAspectRatio, the aspect ratio is equal to 1024 960 (screen height screen width)... even if I've not understood what is it... 0.1f, 1000f) I've not really understood what near and far planes are... public Matrix4f getMatrix() with this function I obtain the final camera matrix return getView().mul(getProjection()) And it's how I handle the camera Matrix in GLSL, created using camera.getMatrix() gl Position camera model vec4(position, 1.0) Without the camera all is fine here's the program running using gl Position model vec4(position, 1.0) (Yeah, it's a cube) But using the camera in the way I showed you before, increasing the FOV, I get this Could anyone look at my code and tell me where I'm wrong? I would be really happy... D"} {"_id": 24, "text": "Unreal Engine custom camera I was looking at game engines and found Unreal Engine. I want to make a game where the player has to create a camera by crafting it and can customize how many pixels the camera detects and what the camera detects (Ex Sound, light, energy, etc). How could I do this?"} {"_id": 24, "text": "Moving camera along generated terrain? I'm generating my terrain on the GPU, using diamond square subdivision (no height map involved). How can I anchor the camera's position to always be on top of the generated terrain? Thanks"} {"_id": 24, "text": "Smooth Camera Offsets I am attempting to implement a sort of, smooth camera that has angle offsets from the player as they turn, creating a cinematic effect as well as visual feedback for when the player turns. Here is an example of the desired functionality. (Starts at 1 06) http youtu.be uJ6tD k RuA?t 1m6s One idea I was thinking of (if even feasible) is to store a \"desired quaternion\" of orientation of where the camera wants to look (preferably the player's quaternion of orientation) and a \"current quaternion\" of the cameras orientation and SLERP to the desired quaternion. Then possibly set a max angle between the two rotations to cap how large the angle offset could be. What are the ways of doing that?"} {"_id": 24, "text": "What does it mean to \"strafe\" the camera? I'm looking at a tutorial in which both the terms camera moving and \"strafing\" are used. I looked onto dictionary.com and found strafe verb (used with object) 1. to attack (ground troops or installations) by airplanes with machine gun fire. 2. Slang . to reprimand viciously. noun 3. a strafing attack. WTF??? I'm not a native english speaker."} {"_id": 24, "text": "Isometric character from 3D blender model I am trying to make a character for an isometric game from a 3D model in Blender. I managed to create a simple humanoid model and implement an isometric camera, rotated by 60 on the x axis and 45 on the z axis. Following a screenshot of this model with camera settings I chose making a 3D model in blender because I want to be able to make changes to my models without having to change loads of images or sprite sheets and I also wanted to get into 3D modelling. I looked into articles by clint bellanger that's where I got the idea to make my graphics in blender, rather than draw in Illustrator or photshop but I am not sure how I should continue now. My questions are is this a good way to accomplish my goal of making an isometric character from a 3d model if it is feasible to turn around the ratio of 2 1 between width and height for my character or if I should render it another way if the settings of the camera I have in blender are correct to use for an isometric game with a 2 1 ratio of width and height for the tiles. Thanks in advance"} {"_id": 24, "text": "What does it mean to \"strafe\" the camera? I'm looking at a tutorial in which both the terms camera moving and \"strafing\" are used. I looked onto dictionary.com and found strafe verb (used with object) 1. to attack (ground troops or installations) by airplanes with machine gun fire. 2. Slang . to reprimand viciously. noun 3. a strafing attack. WTF??? I'm not a native english speaker."} {"_id": 24, "text": "Pygame Scrolling Map I have two questions. I'm working in a rogue like and I've manage to implement a camera on the player, the camera shows just the players surroundings and is fixed in the side of the windows. The problem is, when the player is close to the sides of the map there's a black space in the surface. Like so 1) How do I make the camera 'snap' to the side and don't go any further? To draw the map I took the Camera Rect positions topleft and bottomright Converted it to World Position Iterate over it, with a enumerator too Did any lit visited FOG calcunations with X and Y And Blited in the screen using the enumerators 'i' and 'j'. Here's the code topleft Map.toWorld(camera.rect.topleft) bottomright Map.toWorld(camera.rect.bottomright) for i, x in enumerate(xrange(topleft 0 , bottomright 0 )) for j, y in enumerate(xrange(topleft 1 , bottomright 1 )) tile mymap.tileAt(x, y) object obj for obj in Object.OBJECTS if obj.pos (x,y) if tile lit field of view.lit(x, y) visited field of view.visited(x, y) graphic tile.graphic if lit color tile.color elif visited color GRAY else color BLACK renderedgraphic myfont.render(ch, 1, graphic) screen.blit(renderedgraphic, Map.toScreen((i 1, j))) if object Draw.drawObject(object 0 , Map.toScreen((i 1, j))) I saw HERE a exemple of this but I couldn't adapt the code to my game because it uses sprites. I also tried a different approach using just a camera.center position in short class Object() def update(self) self.relX self.x camera.x self.relY self.y camera.y class Camera(Object) def update(self) self.x self.relX PLAYER.x self.y self.relY PLAYER.y def MapDraw() for x in xrange(mymap.width) for y in xrange(mymap.height) ... do fov stuff tile Tile.At(x, y) get tile instance if tile tile.update() update it's relative position screen.blit(renderedgraphic, (tile.relX TILESIZE, tile.relX TILESIZE)) blit the postion to it's relative position This is what happens which leads to the next question 2) Is there a better way to create a camera than using this 'hack' of enumerating? EDIT Answer So after some struggles I tried the old, print whatever I had and found out that I could use the camera.x and camera.y for this. first I check the distace between camera.x and the optional position in the sides, It was 3 for up and down, 7 to sides. Then a couple of if statements fixed this. But since int's aren't very consitent depending on mapsize, cameraview, I found that the camera.rect width and height divided by 2 in world position was the same as (7,3) I was looking for. Anyway, here's the code for the camera. def update(self) self.x, self.y PLAYER.pos center camera on player self.size Map.toWorld((camera.rect.width, camera.rect.height)) get the ScreenSize of the rect and convert to World Position self.size 0 2 divided each one by two, because the player is in the center. self.size 1 2 if self.x lt self.size 0 right self.x self.size 0 if self.y lt self.size 1 up self.y self.size 1 if self.x self.size 0 gt mymap.width left self.x mymap.width self.size 0 if self.y self.size 1 gt mymap.height down self.y mymap.height self.size 1 self.rect pygame.Rect((self.x TILESIZE) CAMERA WIDTH 2, (self.y TILESIZE) CAMERA HEIGHT 2, CAMERA WIDTH, CAMERA HEIGHT) updated the rect Thanks Tyyppi 77, even tho you provided a small answer, the way you phrased it was just right for me to get it."} {"_id": 24, "text": "Implementing Screen Shake I'm looking to implement screen shake in a 2D top down game. From an earlier Q on this exchange, I learned that noise values could be a good candidate, so I intent to try that. But I wonder is a screen shake more about rotating the 2D topdown camera, or about jittering the position of that camera? Or does it really require both? Additionally, I would like to know if a good screenshake would require motion blur? Something like rendering your world in 4 small micro steps for each 60fps frame, maybe? Or can you shake the camera at 60fps with normal rendering and it still looks good? The quality I am after is something like shown in this video. It's kinda hard to judge, but it seems that video does translational jitter only?"} {"_id": 24, "text": "Ortbit camera rotation multiplication order with quaternions? So I switched my camera to use quaternions and the first thing I noticed is that things started to 'roll' even though I'm not using any roll values. I looked it up and I found that people suggest that using rotation horizontal rotation vertical solves the issues instead of rotation rotation horizontal vertical which I thought was the more intuitive thing from doing matrix multiplication. The explanations I read as to why one works and the other doesn't were pretty vague and unclear. My question is why does it work this way? what's wrong with 'rotation h v ? Sample code float Horizontal 0 float Vertical 0 if (Keys 'W' Key Held) Camera gt Position Camera gt Forward() CamMovSpeed DeltaTime if (Keys 'S' Key Held) Camera gt Position Camera gt Forward() CamMovSpeed DeltaTime if (Keys 'A' Key Held) Camera gt Position Camera gt Right() CamMovSpeed DeltaTime if (Keys 'D' Key Held) Camera gt Position Camera gt Right() CamMovSpeed DeltaTime if (Keys 'E' Key Held) Camera gt Position vec Up CamMovSpeed DeltaTime if (Keys 'F' Key Held) Camera gt Position vec Up CamMovSpeed DeltaTime mouse int dx Mouse gt x Mouse gt LastX Mouse gt LastX Mouse gt x int dy Mouse gt LastY Mouse gt y Mouse gt LastY Mouse gt y if (Mouse gt MMB Key Held) pan Camera gt Position (Camera gt Up() dy Camera gt Right() dx) SpeedMul 2 DeltaTime if (Mouse gt RMB Key Held) orbit Horizontal dx SpeedMul 10 DeltaTime Vertical dy SpeedMul 10 DeltaTime if (Mouse gt Wheel) zoom Camera gt Position Camera gt Forward() Mouse gt Wheel SpeedMul 10 DeltaTime if (Horizontal ! 0 Vertical ! 0) quat QVertical(vec Right, Vertical) quat QHorizontal(vec Up, Horizontal) Camera gt Rotation QHorizontal Camera gt Rotation QVertical this works Camera gt Rotation Camera gt Rotation QHorizontal QVertical this doesn't Camera gt Rotation.Normalize()"} {"_id": 24, "text": "Realistic Camera Screen Shake from Explosion I'd like to shake the camera around a bit during an explosion, and I've tried a few different functions for rocking it around, and nothing seems to really give that 'wow, what a bang!' type feeling that I'm looking for. I've tried some arbitrary relatively high frequency sine wave patterns with a bit of linear attenuation, as well as a square wave type pattern. I've tried moving just one axis, two, and all three (although the dolly effect was barely noticeable in that case). Does anyone know of a good camera shaking pattern?"} {"_id": 24, "text": "Camera LookAt position with fixed screen position I have a perspective \"lookAt type\" camera. I'm trying to compute specific focus point of the camera, which should be placed in the middle of the screen I also have a custom 3d point in world space, margin values in screen space and camera's tilt as inputs. I want to compute lookAt point, amp camera distance with restriction, that input world space point has to be visible in the middle of the free screen space area (not affected by margin values) and it has to have a given tilt. I'm able to compute this in 2D, but I'm lost in 3D. Any idea how to achieve this? Here's a sketch of the problem, red and blue area's are margin values of 0.5f in both x and y direction."} {"_id": 24, "text": "Godot Camera shake without target I'm working with godot 3.2 to make this screen shake, but my issue is that i don't have a target, like in the example, in the example code, it's a kinematic body that is being followed by the camera, i don't have that, i'm making a match three type of game, so i don't use those. What i tried it's to use the main node, in which the game loop logic is executed but the camera shake didn't work, also tried with another elementsd but it failed beacuse they are mostly HUD elements and shows an error about global positions. Also i not sure how to get the board grid, since it's instantiated by code. How i can make shake camera without a target or get a similar effect?"} {"_id": 24, "text": "Camera type for puzzle game like tetris I can't find what is the name of the camera type. Sided camera view seems logical but not correct thought"} {"_id": 24, "text": "What game systems exist which uses camera input? The group and I is in the middle of a semester project where we are currently researching on which game systems are using camera as input or as an interactive medium? We would like some help listing some of the game systems which uses camera input, as it seems hard to find other examples. Currently we know that webcam browser games uses camera input (Newgrounds webcam games), as well as the xbox kinect. I know this questions seems rather vague, though I still hope some people is capable of helping."} {"_id": 24, "text": "Unreal Engine custom camera I was looking at game engines and found Unreal Engine. I want to make a game where the player has to create a camera by crafting it and can customize how many pixels the camera detects and what the camera detects (Ex Sound, light, energy, etc). How could I do this?"} {"_id": 24, "text": "What is the term for making an object transparent when it blocks the player's view? In many games if your camera gets too close to certain objects, or the object starts to block your screen, the game turns it transparent so you can still see. What is the name for this effect? It is not occlusion culling. The model does not reduce its polygons, it simply just gets transparent so that you can look through it."} {"_id": 24, "text": "Unreal Y Axis boundary on a Camera Bounding Box I was wondering if I could get some help with modifying a Blueprint I'm currently using for a project in Unreal Engine. I am currently attempting to make a side scrolling platformer game and I'm using a camera bounding box Blueprint to restrict where the camera can move when tracking the player's movement, based on the following series of tutorials on YouTube by JvtheWanderer How to make a Metroidvania 2D Camera Blueprint System on UE. The camera bounding box works as intended, in that it prevents the camera from moving beyond the limitations of the camera box placed within the scene, but I want to go even further than that and establish a limitation within the camera bounding box that not only limits the camera's movement but also prevents the player from moving on the Y axis beyond the box's boundaries. Pretty much every platformer from Super Mario to Sonic the Hedgehog to Castlevania, have such boundary limitations, usually at the very start of the level and also frequently at the end. The limitation on the Y axis boundary is also frequently used to lock the player into a particular area for forced enemy encounters, mini boss fights as well as proper boss battles, a limitation that lasts until the player has vanquished the threat. I wish to implement similar boundaries on the camera bounding boxes within my project to restrict where the player can go without having to place walls everywhere to keep the player from wandering beyond the level's limits. Using walls to restrict the player's movement is fine for indoor areas, but it ends up looking distractedly out of place in outdoor areas if used in excess. I've included screenshots below of the Construction Script amp Event Graph from the SideScrollerCamera Blueprint I'm using. I would also include the Viewport and the Level Blueprint as well, except that the time being, I am unable post more than two links. Construction Script Event Script Any help with this matter would be greatly appreciated."} {"_id": 24, "text": "Camera rotation in 4D What practical choices do I have in order to rotate a camera in 4D space? I would like to make it as intuitive as possible. A camera in 3D space can be represented by a point where it is located the forward vector (movement using the w and s buttons) the left (movement using the a and d buttons) the up vector (eg. space and ctrl ) In 4D space, the an additional axis is added the fourth axis vector (eg. q and e ) All of the vectors remain orthogonal to eachother. So the movement is trivial."} {"_id": 24, "text": "How to avoid gimbal lock in Unreal Engine (c )? I created an orbit camera (sometimes called turntable camera similar to the one with the \"use UE3 orbit controls\" setting in a static mesh view). I attached the camera to a USpringArmComponent with a TargetArmLength set to 400. In the tick function, I rotate the arm with this simple method Simple, clamped version FRotator Rotation CameraSpringArm gt GetComponentRotation() Rotation.Yaw CameraInput.X CameraRotationSpeed Rotation.Pitch FMath Clamp(Rotation.Pitch CameraInput.Y CameraRotationSpeed, 85.0f, 85.0f) CameraSpringArm gt SetRelativeRotation(Rotation) I had to clamp the pitch to hide the gimbal lock problem. But this prevent users to rotate completely around objects. I don't understand why the Z rotation (the yaw) occurs on the world z axis ( FVector UpVector which is (0, 0, 1)) and not on the local z axis. It turns out that this is exactly what I want. I tried to solve this gimbal lock problem with this other method Taken from https answers.unrealengine.com questions 232923 how can i avoid gimbal lock in code.html FRotator RotationDelta(CameraInput.Y CameraRotationSpeed, CameraInput.X CameraRotationSpeed, 0.f) FTransform NewTransform CameraSpringArm gt GetComponentTransform() NewTransform.ConcatenateRotation(RotationDelta.Quaternion()) NewTransform.NormalizeRotation() CameraSpringArm gt SetWorldTransform(NewTransform) It works, but this time, the Z rotation (yaw) occurs on the local Z axis. How can I change it to rotate around the world Z axis, and the local Y axis, without gimbal lock? I tried this hybrid solution, but the gimbal lock is still there Hybrid FRotator RotationDelta(CameraInput.Y CameraRotationSpeed, 0.f, 0.f) FTransform Transform CameraSpringArm gt GetComponentTransform() FRotator Rotation CameraSpringArm gt GetComponentRotation() Rotation.Yaw CameraInput.X CameraRotationSpeed Transform.SetRotation(Rotation.Quaternion()) Transform.ConcatenateRotation(RotationDelta.Quaternion()) Transform.NormalizeRotation() CameraSpringArm gt SetWorldTransform(Transform) I did solve this problem (a long time ago) in OpenGL using quaternions, so I tried this version Quaternion FRotator Rotator CameraSpringArm gt GetComponentRotation() FQuat Quaternion Rotator.Quaternion() Rotate around the world Z axis Quaternion FQuat(FVector UpVector, FMath DegreesToRadians(CameraInput.X CameraRotationSpeed)) Rotate around the local Y axis Quaternion FQuat(Rotation.RotateVector(FVector RightVector), FMath DegreesToRadians(CameraInput.Y CameraRotationSpeed)) CameraSpringArm gt SetRelativeTransform(Quaternion) But this does not work. I also tried this Quaternion transform FTransform Transform CameraSpringArm gt GetComponentTransform() Transform.ConcatenateRotation(FQuat(FVector UpVector, FMath DegreesToRadians(CameraInput.X CameraRotationSpeed))) Transform.ConcatenateRotation(FQuat(Rotation.RotateVector(FVector RightVector), FMath DegreesToRadians(CameraInput.Y CameraRotationSpeed))) Transform.NormalizeRotation() CameraSpringArm gt SetWorldTransform(Transform) without success."} {"_id": 24, "text": "Follow camera for car object I have a car object in my game that has a car location like any other object. It is able to steer with bicycle KInematics and even rotates while it drives from a car heading vector. Now I need the camera to follow the car. I put the camera position 10 up and 10 behind the car. But I'm confused on where to make the camera look. I tried this pseudo code lookatcamera carLocation.x 5 cos(carHeading), carLocation.y, carLocation.z 5 sin(carHeading)"} {"_id": 24, "text": "What does it mean to \"strafe\" the camera? I'm looking at a tutorial in which both the terms camera moving and \"strafing\" are used. I looked onto dictionary.com and found strafe verb (used with object) 1. to attack (ground troops or installations) by airplanes with machine gun fire. 2. Slang . to reprimand viciously. noun 3. a strafing attack. WTF??? I'm not a native english speaker."} {"_id": 24, "text": "Can I position a player avatar behind the camera based on rotation? I'm currently reverse engineering a video game where what's rendered on the screen depends on the proximity of the player avatar to the camera. As such, for my freecam to work properly, I need to bring the player avatar along with the camera. Since I can't yet find how the player avatar is rendered to the screen, the next best thing I can think to do is to place the player avatar behind the camera at all times (I suppose essentially like making the player avatar orbit the camera, but always be behind it). I just can't quite pin down how to make this happen. The values I have are as follows Player Avatar X Y (Up Down) Z Camera X Y (Up Down) Z Pitch (In degrees natively, but converted to radians for my calculations) Yaw (In degrees natively, but converted to radians for my calculations) World Orientation To get my camera to move forward in the direction I'm pointing my mouse when pressing the Y key, these are the calculations I'm using (code is in Lua) Camera XYZ values local camCoordX readFloat(\" cameraBase 990\") Camera X local camCoordY readFloat(\" cameraBase 994\") Camera Y local camCoordZ readFloat(\" cameraBase 998\") Camera Z Camera pitch and yaw local pitch math.rad(readFloat(\" cameraBase 1540\")) Pitch local yaw math.rad(readFloat(\" cameraBase 1544\")) Yaw Sine and cosine calculations local sinOfYaw math.sin(yaw) Sine of Yaw local cosOfYaw math.cos(yaw) Cosine of Yaw local sinOfPitch math.sin(pitch) Sine of Pitch local cosOfPitch math.cos(pitch) Cosine of Pitch If Y key is pressed, write new camera XYZ values accordingly if isKeyPressed(VK Y) then writeFloat(\" cameraBase 990\", camCoordX (sinOfYaw speed)) writeFloat(\" cameraBase 994\", camCoordY (sinOfPitch speed)) writeFloat(\" cameraBase 998\", camCoordZ (cosOfYaw speed)) end Based on that information, is it feasible for me to accomplish placing the player avatar behind the camera at all times based on rotation? I'm open to other suggestions or options as well. Thank you for any help you can offer!"} {"_id": 24, "text": "Simulating a real camera's perspective projection I'm trying to simulate a real camera's perspective projection of straight, parallel lines running along the ground (one point perspective) by mapping the real world 3D coordinates of the lines to 2D screen coordinates. Suppose the camera's tilt angle is known, is there a way to calculate the slopes coordinates expression of these lines projected on to the 2D plane? Which parameters of the camera are needed? My understanding is that when the camera is tilted, the vanishing point is effectively shifted. But does tilting the camera cause the same changes in the perspective of the lines as moving the camera lower to the ground (closer to the lines)?"} {"_id": 24, "text": "How to figure out which tiles are within view, and where to draw them in the grid? I know there are a few questions on here similar to mine, but none of them seem to fit my needs. I'm using PyGame to implement a tile based game similar to Final Fantasy or Zelda from the early Nintendo and Super Nintendo generation consoles. The issue I'm running into is that I can't figure out how make a general way to render and position the tiles within view of the player camera. Once the camera starts moving, finding how much of an image is present in the camera view is very difficult, and then positioning it correctly is more complicated. Any suggestions on how I can figure out a general way to create the grid correctly?"} {"_id": 24, "text": "How can I track a falling ball with a camera? I have been trying to get my camera to follow a falling ball but with no success. here is the code float cameraY (FrustumHeight 2) ((ball.getPosition().y) 2) (FrustumHeight 2) if (cameraY lt FrustumHeight 2 ) cameraY FrustumHeight 2 camera.position.set(0f,cameraY, 0f) Gdx.app.log(\"test\",camera.position.toString()) camera.update() camera.apply(Gdx.gl10) batch.setProjectionMatrix(camera.combined) batch.begin() batch.draw(backgroundRegion, camera.position.x FrustumWidth 2, cameraY (FrustumHeight 2) , 320, 480) batch.draw(ballTexture, (camera.position.x FrustumWidth 2) ball.getPosition().x, cameraY ball.getPosition().y (FrustumHeight 2) , 32, 32) I'm sure I am doing this completely wrong what is the correct way to do this?"} {"_id": 24, "text": "How to avoid gimbal lock I am trying to write code with rotates an object. I implemented it as Rotation about X axis is given by the amount of change in y coordinates of a mouse and Rotation about Y axis is given by the amount of change in x coordinates of a mouse. This method is simple and work fine until on the the axis coincides with Z axis, in short a gimble lock occurs. How can I utilize the rotation arount Z axis to avoid gimbal lock."} {"_id": 24, "text": "How can I find the opposite angle and position of the camera? In this project I have a character and a camera that follows it. The camera has a position relative to the character that was defined as (x 0, y 0, z 0) and also its rotation I found a value close to its position and opposite angulation, but not really the correct value By pressing the Q key, the camera shifts to the position and angulation that I have discovered. Releasing the Q key, the camera returns to its initial position IN GAME As you can see, the inversion is not 100 correct. One of the ways I thought, is a way where I take this relative value from the camera (x 0, y 0, z 0) and with that I put the character's mesh at the location (x 0, y 0, z 0) at the level and so, as the camera will be (for example) x 250, y 0, z 300, it's just I invert the value of x. The angulation is simpler to deduce, but it would be interesting for me to also derive its relative value (0, 0, 0). EDIT 1 (Attempt that I did and that almost worked out) By clicking the down arrow to the left of the values, you can select whether you want the variable to be Relative or World (I did not know that) Before it was all 0, it now has a value Taking the minus sign, I was able to figure out the opposite position New position It happens that at the time of changing the angulation from relative to absolute, a conversion is not made I can not get absolute value equivalent to relative. What happens is that the value 0, 0, 0 is also defined for the absolute rotation. In the image below the camera was exactly in the same position as the VR camera I discovered by trial and error the equivalent angulation between relative and absolute BLUEPRINT The code works correctly, but I feel that again I did not get exactly the position and opposite angles. Here are some screenshots of the game Local X with NORMAL CAMERA Local X with OPPOSITE CAMERA Local Y with NORMAL CAMERA Local Y with OPPOSITE CAMERA Note that in the opposite camera you can see the end of the world (sky) from wherever you are, which is not the case with the normal camera. I noticed this, and so, I think once again I did something wrong."} {"_id": 24, "text": "Render a 3D scene in multiple windows extended panoramic view Is there any resource location on how to view a 3D scene from an application or a game on multiple windows or monitors? Each window should continue drawing from where the neighbouring one left off (in the end, the result should be a mosaic of the scene). My idea is to use a camera for each window and have a reference position and orientation for a meta camera object that is used to correctly offset the other cameras (e.g. like in the above figure where the render targets of the two cameras reproduce the star when stitched together). Since there are quite some elements to consider (window specs, viewport properties, position orientation of each render camera), what is the correct way to update the individual cameras considering the position and orientation of the central, meta camera? I currently cannot make the cameras present the scene contiguously (and I am reluctant in working out the transformations without checking whether this is the actual way of doing things)."} {"_id": 24, "text": "Camera (pole cam) implementation problem In my project I have simple scene graph to render whole scene and Bullet physics SDK to provide physics simulation. Each rendered object is represented as scene node. Camera always has target and located behind this target. Target can be any scene node. First, I want to describe my rendering pipeline. 1)When time to render whole scene, we calculate view matrix from target's world matrix. We take offset vector in order to locate camera behind targeted scene node and transform it to scene node world's coordinate. Then add position of target with transformed offset vector. Finally, get inverse matrix of scene node. This method always is called before rendering whole scene. HRESULT CameraNode SetViewTransform(Scene pScene) If there is a target, make sure the camera is rigidly attached right behind the target if(m pTarget) Mat4x4 mat m pTarget gt VGet() gt ToWorld() Vec4 at m CamOffsetVector Vec4 atWorld mat.Xform(at) Vec3 pos mat.GetPosition() Vec3(at) mat.SetPosition(pos) VSetTransform( amp mat) Set normal matrix and calculate inverse matrix m View VGet() gt FromWorld() Get inversed matrix pScene gt GetRenderer() gt VSetViewTransform( amp m View) return S OK 2)Then, when time to render particular scene node, we calculate projection matrix and send it to the vertex shader. Mat4x4 CameraNode GetWorldViewProjection(Scene pScene) Mat4x4 world pScene gt GetTopMatrix() Mat4x4 view VGet() gt FromWorld() Mat4x4 worldView world view return m Projection worldView I have next problem, when I calculate view matrix from target's world matrix and locate target on coordinate ( x 0 y 10 z 1) it started to fall due to physics and jerk twitch. 1 When I set view camera matrix only offset position. Scene node falls without jerking twitching. 2 How I can fix this jerking twitching when camera is following the scene node ? I suppose that it is problem of matrices multiplication, when Bullet SDK sets new coordinates to scene node. But I have no idea how it can be solved."} {"_id": 24, "text": "What game systems exist which uses camera input? The group and I is in the middle of a semester project where we are currently researching on which game systems are using camera as input or as an interactive medium? We would like some help listing some of the game systems which uses camera input, as it seems hard to find other examples. Currently we know that webcam browser games uses camera input (Newgrounds webcam games), as well as the xbox kinect. I know this questions seems rather vague, though I still hope some people is capable of helping."} {"_id": 24, "text": "Ortbit camera rotation multiplication order with quaternions? So I switched my camera to use quaternions and the first thing I noticed is that things started to 'roll' even though I'm not using any roll values. I looked it up and I found that people suggest that using rotation horizontal rotation vertical solves the issues instead of rotation rotation horizontal vertical which I thought was the more intuitive thing from doing matrix multiplication. The explanations I read as to why one works and the other doesn't were pretty vague and unclear. My question is why does it work this way? what's wrong with 'rotation h v ? Sample code float Horizontal 0 float Vertical 0 if (Keys 'W' Key Held) Camera gt Position Camera gt Forward() CamMovSpeed DeltaTime if (Keys 'S' Key Held) Camera gt Position Camera gt Forward() CamMovSpeed DeltaTime if (Keys 'A' Key Held) Camera gt Position Camera gt Right() CamMovSpeed DeltaTime if (Keys 'D' Key Held) Camera gt Position Camera gt Right() CamMovSpeed DeltaTime if (Keys 'E' Key Held) Camera gt Position vec Up CamMovSpeed DeltaTime if (Keys 'F' Key Held) Camera gt Position vec Up CamMovSpeed DeltaTime mouse int dx Mouse gt x Mouse gt LastX Mouse gt LastX Mouse gt x int dy Mouse gt LastY Mouse gt y Mouse gt LastY Mouse gt y if (Mouse gt MMB Key Held) pan Camera gt Position (Camera gt Up() dy Camera gt Right() dx) SpeedMul 2 DeltaTime if (Mouse gt RMB Key Held) orbit Horizontal dx SpeedMul 10 DeltaTime Vertical dy SpeedMul 10 DeltaTime if (Mouse gt Wheel) zoom Camera gt Position Camera gt Forward() Mouse gt Wheel SpeedMul 10 DeltaTime if (Horizontal ! 0 Vertical ! 0) quat QVertical(vec Right, Vertical) quat QHorizontal(vec Up, Horizontal) Camera gt Rotation QHorizontal Camera gt Rotation QVertical this works Camera gt Rotation Camera gt Rotation QHorizontal QVertical this doesn't Camera gt Rotation.Normalize()"} {"_id": 24, "text": "How far back should I move my camera to fit a given GameObject in frame? In Unity with C , I want to calculate the minimum distance that my perspective camera has to be from a given GameObject (a procedurally generated mesh), so that the object is fully framed by the camera and leaving the least space possible around it in the screen. In other words, fully framed means that there is no part of the object outside the view area. To make things easier, my camera does not need to rotate or move it's fully static, with the exception of one axis to zoom in or out in order to frame the target object. So, in fact, we could summarize my problem as a zoom problem (not using FOV to zoom) where I need to frame a procedurally generated mesh whose size varies considerably. Would anyone be kind enough to point me in the right direction with code snippets, suggestions, etc?"} {"_id": 24, "text": "How can I emulate Diablo 3's Isometric view using Perspective? Using DX11, SimpleMath I am building a isometric game like Diablo 3 in 3D and I want to use a perspective camera that emulates their top down view. Projection Matrix CreatePerspectiveFieldOfView(1, width height, 0.1f, 100.0f) But after this I am a bit unsure how I am suppose to rotate the camera. I assume I could just do p Vector3(10, 10, 10) to get a 45 degree angle at any given p. How do I properly position, and rotate the camera and point it at position p, to mimic Diablo 3 view?"} {"_id": 24, "text": "Looking for online resources to understand game camera properties What are some good online resources to understand game camera properties, such as fov, aspect ratio and more?"} {"_id": 24, "text": "How do I move a camera to a new X and Y position when the player collides with a certain object? The lowdown is this I'm making a 2D overhead game that takes place in separate screens in a room. Each screen is separated by a few blocks of black space (to give the impression of screens being separate rooms) and a rectangular \"transition block\" in doorways. My idea is, once a player touches this block, they are moved to the next adjacent screen along with the camera instantly. I can move a player to the next screen this way, the big hangup that I'm having is moving the camera as well. I want every collision box to have the coordinates needed to set the camera around the next screen once player box collision happens, similar to the setup I have with the player character."} {"_id": 24, "text": "How do I output a webcam stream to a 2D canvas with SharpDX in C ? I'm writing an application for the Oculus Rift using the SharpOVR library to access HMD position data. I decided it is reasonable to use SharpDX to also output webcamera streams. Unfortunately, all SharpDX documentation is basically a copy paste from C documention and I only know basic C . C uses a different style, class names, etc. The MediaFoundation samples are also C only. I'm trying to write a pretty simple part that renders 2 videos from 2 webcams. I've managed to get webcameras list with this code, but I'm failing to init one it currently fails at source.Start(descriptor, null, time) According to the exception, I need to bind all Stream events first. Or I am missing something I need to init? Can one help with further actions from camera start till outputting to monitor? I know the code shouldn't be too hard, problem is adapting it to C ."} {"_id": 24, "text": "GLM Camera attached to model moves in opposite direction from the model I have been working on a component based engine with nested game objects each with there own transformation's. Each game object calculates its position in the world based on its parents world transformation multipled by there own local one (ModelsWorldTransform ParentsWorldTransform LocalTransform). This all works great until I attach the camera component to a model and in this scenario, as the model the camera is attached to moves away from the origin, the camera moves in the opposite direction to the movement whitest still seeming like it is in the correct position according to its mat4. All local transformations are stored in a mat4 rather then three vec3's for position, rotation and scale to save on calculations each update having to generate new mat4's. Transformation Component Update Code m world transformation m local transformation If we have a parent object if (m parent transform component) m world transformation m parent transform component gt GetWorldTransformation() m world transformation Camers position buffer being updated BufferData.view m transformation component gt GetWorldTransformation() m camera buffer gt SetData() I'm not sure what i'm missing, if anyone has any sugestions that would be apreatiated."} {"_id": 24, "text": "FlxSprite ignore camera follow in flixel I am using flixel v2.5 and am using FlxG.camera.follow to get the camera to follow the player. I have a background FlxSprite that I don't want to move with the camera. Is there a way I can set this FlxSprite to stay in the same place on the screen? I would also like to have a GUI HUD that stays fixed to the screen, and was thinking I could do this the same way."} {"_id": 24, "text": "How does time dependent camera rotation with a mouse work? The commonly used equation for camera rotation with a mouse does not involve time. This make sense since higher frame rates have smaller changes in mouse position and vise versa so it all evens out. If time slows down or speeds up, however, camera rotation from the mouse does not adjust accordingly. Just as you move slower when time is slowed, logically I also want rotating to be slower. One option is to multiply the change in position of the mouse with the same multiplier I'm using on time, but shouldn't it be possible to have change in rotation and change in time in the same equation, independent from framerate?"} {"_id": 24, "text": "How do I create a bounding frustum from a view projection matrix? Given a left handed Projection matrix, a left handed View matrix, a ViewProj matrix of View Projection How do I create a bounding Frustum comprised of near, far, left, right and top, bottom planes? The only example I could find on Google (Tutorial 16 Frustum Culling) seems to not work for example, if the math is used as given, the near plane's distance is a negative. This places the near plane behind the camera..."} {"_id": 24, "text": "How to make TEXT RENDER stand facing the camera of my character and also for the camera of simulation? I have an actor (Minion) with a Text Render just above it mesh As you have seen, I defined your rotation as absolute, so the text does not rotate along with the actor. In the game the rotation setting is good and acceptable at various times At other times it is very bad An example of what I want is something like the life of the champions in the League of Legends I would also like to know how to do this when I am simulating I've made some attempts at the camera of my main character. And I got some of what I tried. Character Blueprint I know I could put on the Event Begin Play because the camera does not rotate. Minion Blueprint I did (partially) Ignoring the fact that the text is inverted. I tried Split Struct and added 180 to each of the 3 axes (ROLL, PITCH, YAW) and I could not solve it anyway. Simulating nothing works EDIT 1 (Attempt made based on a rrat's answer) Blueprint I think I tried all the combinations and none worked the way I would. The combination defined in the image made the Text Render spin. EDIT 2 (Correction of the attempt I made wrongly) Correction that I did With the answer I was given I noticed a marked improvement. Result 1 Besides the value is no longer inverted. Result 2 But I still have not got what I like. Result I am looking for I wish life would be displayed the same way anywhere on the map the character is on. EDIT 3 (Removing roll) Blueprint In game there was no difference. EDIT 4 (Trying to explain what I want to happen) I think that because I can not speak English and have to use programs to translate things for myself, I do not know the best way to explain my doubts, the best words, among other things. I think the best way then to try to explain what I want is with images. I want regardless of the location or angle life is seen in the same way. Image Image Image In the LEAGUE OF LEGENDS anywhere on the screen that the champion is, the life bar appears the same way. I would like to achieve this result."} {"_id": 24, "text": "How to avoid gimbal lock in Unreal Engine (c )? I created an orbit camera (sometimes called turntable camera similar to the one with the \"use UE3 orbit controls\" setting in a static mesh view). I attached the camera to a USpringArmComponent with a TargetArmLength set to 400. In the tick function, I rotate the arm with this simple method Simple, clamped version FRotator Rotation CameraSpringArm gt GetComponentRotation() Rotation.Yaw CameraInput.X CameraRotationSpeed Rotation.Pitch FMath Clamp(Rotation.Pitch CameraInput.Y CameraRotationSpeed, 85.0f, 85.0f) CameraSpringArm gt SetRelativeRotation(Rotation) I had to clamp the pitch to hide the gimbal lock problem. But this prevent users to rotate completely around objects. I don't understand why the Z rotation (the yaw) occurs on the world z axis ( FVector UpVector which is (0, 0, 1)) and not on the local z axis. It turns out that this is exactly what I want. I tried to solve this gimbal lock problem with this other method Taken from https answers.unrealengine.com questions 232923 how can i avoid gimbal lock in code.html FRotator RotationDelta(CameraInput.Y CameraRotationSpeed, CameraInput.X CameraRotationSpeed, 0.f) FTransform NewTransform CameraSpringArm gt GetComponentTransform() NewTransform.ConcatenateRotation(RotationDelta.Quaternion()) NewTransform.NormalizeRotation() CameraSpringArm gt SetWorldTransform(NewTransform) It works, but this time, the Z rotation (yaw) occurs on the local Z axis. How can I change it to rotate around the world Z axis, and the local Y axis, without gimbal lock? I tried this hybrid solution, but the gimbal lock is still there Hybrid FRotator RotationDelta(CameraInput.Y CameraRotationSpeed, 0.f, 0.f) FTransform Transform CameraSpringArm gt GetComponentTransform() FRotator Rotation CameraSpringArm gt GetComponentRotation() Rotation.Yaw CameraInput.X CameraRotationSpeed Transform.SetRotation(Rotation.Quaternion()) Transform.ConcatenateRotation(RotationDelta.Quaternion()) Transform.NormalizeRotation() CameraSpringArm gt SetWorldTransform(Transform) I did solve this problem (a long time ago) in OpenGL using quaternions, so I tried this version Quaternion FRotator Rotator CameraSpringArm gt GetComponentRotation() FQuat Quaternion Rotator.Quaternion() Rotate around the world Z axis Quaternion FQuat(FVector UpVector, FMath DegreesToRadians(CameraInput.X CameraRotationSpeed)) Rotate around the local Y axis Quaternion FQuat(Rotation.RotateVector(FVector RightVector), FMath DegreesToRadians(CameraInput.Y CameraRotationSpeed)) CameraSpringArm gt SetRelativeTransform(Quaternion) But this does not work. I also tried this Quaternion transform FTransform Transform CameraSpringArm gt GetComponentTransform() Transform.ConcatenateRotation(FQuat(FVector UpVector, FMath DegreesToRadians(CameraInput.X CameraRotationSpeed))) Transform.ConcatenateRotation(FQuat(Rotation.RotateVector(FVector RightVector), FMath DegreesToRadians(CameraInput.Y CameraRotationSpeed))) Transform.NormalizeRotation() CameraSpringArm gt SetWorldTransform(Transform) without success."} {"_id": 24, "text": "Design of a camera system Thinking about a common game, doesn't matter the type of the game, it's very likely that we need some camera type. For example Debug camera controlled by keyboard and mouse, with that we are able to move around in any place of our scene. Scripted camera with that we can instruct the camera to move around, following a determinate path. Player camera. ... Each of these camera types has its own update function. The easiest (and bad) system,is to have a camera manager class with a generic update function and specialized update functions for every camera type. Inside the generic update function we have a switch statement that, based on the camera type, calls the proper update function. Instead of this I've thought to another approach strategy pattern. We move each camera behavior (update method) in an appropriate class that implements a common interface. In the camera manager we have a member to that interface, and we can set dinamically any behavior we want. What do you think about that? What other systems do you suggest me? Thanks. Additional info there is the are real possibility that I need more than one camera active, for example for reflections. In short, I must take account also of that."} {"_id": 24, "text": "Why does this work? camera rotation from screen space I do not understand the math behind the linked function or why it works. I would like to know this. https sidvind.com wiki Yaw, pitch, roll camera void Camera motion(int x,int y) theta x 200 Adjust this to control the sensitivity phi y 200 target.x cos(theta) sin(phi) target.y cos(phi) target.z sin(theta) sin(phi)"} {"_id": 24, "text": "How do I get the camera's local XYZ axis in Direct X 11? I'm currently working on quaternion rotation and I have them working, but it seems to be using the world XYZ axis to rotate around, which is an issue as the camera rotates itself around an axis. Similar to the last image, how do I rotate the camera around its local XYZ axis rather than the world XYZ? Edit The camera now rotates around its local axis, but when doing so, it does not change its values in world space. I can hold a key down and it will rotate around the correct axis, but once I release the key it will snap back to its original position before the rotation began. What must I do to allow the local changes to be applied to world space?"} {"_id": 25, "text": "Legally possible to re create remake an old game? Recently I started remaking an old game on Unity. Basically I want to remake an old RPG that was released for Playstation 1. I'm not ripping anything from the old game, all the assets are being created by me. I'm creating everything from the scratch, music, 3D models, gameplay however I will keep the (copyrighted ?) names, I will try to create the characters and maps levels as they were in the original version of Playstation 1 but with better graphics. I'm not planning on selling it or adding in on a platform like Steam (for obvious reasons, copyrights etc), just giving it for free. But I wanna know when I will finish the development, can I share the game on public with other people so they can download it? Can the company that made the original game sue me fine me because of copyrights reasons even though I'm not planning on selling for money? tl dr Remake an non profit game of PS1 from the scratch, can the company that holds the copyrights of the game sue me fine me?"} {"_id": 25, "text": "Copyright and patents on game design and names? We all know that each game has elements from another game but when does one cross the line of copyright? I have a view particular questions about this since this \"line\" is very vague. While looking for a name and Googling it usually return some kind of old or unknown game already with the exact same name. Can i use this name? And what about a name like Diablo, since Diablo is the commonly used name for the devil there cannot be a patent on this afaik. So would a different kind of game named Diablo be allowed? Let's say i want to make a game of mechs like in Mechwarrior. Obviously the mech designs have copyright, the name as well since i suppose. But am i crossing any rights if i make a top down tactical squad game that include mechs of different designs names and call it Clash of Steel? I understand there are not much lawyers here, but how could anyone create a game these days that does not cross the lines of copyright. Like the Mechwarrior example, there are plenty of games nowadays even movies that use this concept. For what it matters Mechwarrior could have ripped the idea from the Gundam anime series. With so many titles coming out each week including the indies it is next to impossible not to infringe into someone copyright."} {"_id": 25, "text": "What do I need to do legally to protect my game with copyright? I am in the process of writing a game and I'm wondering what the copyright laws about publishing this game are. I do not (for now) intend to make money from this. The beginning of my code contains a comment with Copyright 2013, Collin Norwood, but is that legally valid? Do I have to apply with some government for a trademark or such?"} {"_id": 25, "text": "Adding actors musicians famous people in a videogame Let's say I want to make a videogame with several famous characters in it, you can't copyright a name and a face, right (I'm talking about names and surnames, not branded ones)? How does it work? Are there any royalties to pay? To whom? If there are royalties, can I get away by making my names similar to original ones?"} {"_id": 25, "text": "Version Not Final, Does Not Represent Actual Game Footage? Just curious about this. Frequently, a lot of gameplay videos from big studios have small subtitled text at the lower part of the screen, reading something like Pre Alpha Gameplay Footage not Final Game Footage not Final Pre Alpha, Game here is not final Is there some sort of reason they do this? Is there some sort of legal ramification that they need to go through by adding this? I have especially seen some gameplay vids whose titles are \"Alpha x.x.x\", yet still, in the video itself, it always something like \"footage not final, game may change\"."} {"_id": 25, "text": "What resources can I use to determine if the name of my game violates any copyrights or trademarks? I'm a indie hobbyist game developer. How do I check that I'm not infringing any copyrights or trademarks when I release my game? I'm not making megabucks so it's not financially feasible to get professional legal help for each game. I asked recently if I can reuse the name of an old arcade game (Crazy Balloon), but this got me thinking about future games where I might not even be aware of something similar that existed before. So, are there any tools or resources that you can recommend to check myself (due diligence I think it's called)."} {"_id": 25, "text": "Copyright notices on a web game portal I notice that for several games on Kongregate, the copyright notice either uses the author's handle name (login name), the name of the group that produce it or a domain name. Are all those valid copyright notices?"} {"_id": 25, "text": "Using an unregistered company name If I want to release an App with a Company Name do I have to have that registered before I can use it? I have checked and the name is not taken, so is it fine to just use a made up company name? As a side note, I have made this game just as a hobby project, not looking to make any money from it."} {"_id": 25, "text": "What is the proper, legal way to make a derivative video game? I want to make a game derived from an existing game. That game is owned by a live company. How do I go about contacting the rights owners correctly and negotiating for the rights to the content?"} {"_id": 25, "text": "Are there legality issues using a company's name in a game? I'm working on an RPG of sorts where the character has a \"day job\" that determines how much money they make each time the day cycles and other things like that. Are there any legality issues with using the names of companies like \"Barnes amp Noble\" or even \"Apple\"?"} {"_id": 25, "text": "How or when to add a copyright notice in published games? I've seen lot of videogame title screens show a copyright notice together with the company name. I'm about to publish my game and I am looking for possibilities or requirements on how or when to add such a copyright notice (including date or year published). Does it apply to both indie game makers and larger companies?"} {"_id": 25, "text": "If I release code under GPLv3, can I specify what parts of users' code can be released under a new license? I have a few questions about what users of my engine could copyright in their own project. The way the engine would work would be that it would be a standalone program in Java that would load all of the scripts assets data from a folder that the game takes place in. The code could be written in Python or compiled to Java. Onto my questions, the code that they write would access some parts of my engine through Jython, and so I assume those would have to be released under the GPL. But what about the rest of the game other than the code? Like could they copyright their own art? I guess what I really want is that modifications of the code of the engine must be released under the GPL, but projects created using my engine can be released under any copyright, as long as they obey they distribute the engine itself under the GPL."} {"_id": 25, "text": "Does using an licensed game engine prevent you from open sourcing a defunct work? I'm curious as my previous company is asking us (people who developed the game) on what to do to the game since it's no longer financially viable. My suggestion was to open source it so people can still enjoy the game at the same time it could at least be improved. But we did use a licensed Torque engine which was mostly recoded reworked. Not sure if their license allows for the move though. (Also not sure if this is an appropriate question to ask here)"} {"_id": 25, "text": "Is it legal to record music with a synthesizer and use it in my game? I want to make music for game on my own because I don't have professional composer hired. I have found some softwares for making music, but most of them cost some money. I have an idea to record music on synthesizer, then edit it and use in my game. My question is Is it legal to record music (that I have composed and edited) on synthesizer and use it in my game (the game may be free or charged)?"} {"_id": 25, "text": "Can I get around a Pokemon copyright with new art and minor changes? If I develop a game that is essentially pretty much Pokemon (you're a trainer, you catch \"monsters\" and put them to fight and level up etc), and I do the next things I'm a trainer with a 6 \"Monsters\" party. Mechanics like the PC, Gym Leaders and \"tall grass\" will be used. I will throw an \"ball\" to catch the weakened \"monster\". I will use common item names, like \"potion\", \"high potion\". The battles are almost the same as Pokemon in terms of mechanics (four moves, elements, critical, evasion etc) I will NOT use Pokemon names nor graphics... artwork is mine. Some of the attack names will match Pokemon attack names. I think it is okay, like \"ember\". Come on. With all these points, I shouldn't run into copyright issues or anything right? Even if the game feels a lot like Pokemon itself?"} {"_id": 25, "text": "Workflow for accountable file transfers between freelancer and developer I'm an indie game developer and I often hire freelancers for artwork. We sign an agreement to basically state that I'd get ownership of the resources they produce. I'm a fairly picky person when it comes to formalities in these agreements, and I can't find a good system to document file transfers between freelancer and client. What I'm looking for is A way to track a relationship between their email account and mine, and document file exchanges, like a quot timeline quot Freelancer uploaded X file at 16 50 UTC 03 00, download button Freelancer uploaded Y file at 17 43 UTC 03 00, download button Client uploaded Z file at 18 35 UTC 03 00, download button And files are permanently kept in the timeline for documentation purposes it should be impossible to delete an entry (unless both parties agree to delete it). The point of such structure is to quot vouch quot that this person transferred a file at some point and neither party can deny it. Technically, e mail attachments do exactly this. However, if it is a relatively large file, Gmail will ask them to upload to Google Drive. The problem with this is that Drive lets them keep ownership of the file (so if they delete it, I cannot get it back unless I had downloaded it) we would lose the whole quot record quot thing as there will be no guarantee that the file that I have is in fact the file that they uploaded. How we've worked with a few freelancers in the past is that they will transfer a bulk of files (zip) to us using whatever convenient method, and then, in written, state that they have produced and transferred a zip with some MD5 hash. So if it is ever necessary to prove that such a file was given to me by a freelancer, we'd just compute its hash. However that's understandably inconvenient."} {"_id": 25, "text": "Will using similar exact name to a current Marvel superhero name for your game be a problem? I have heard that the word 'superhero' is trademarked by marvel and DC and thus we can't use superhero as part of the name of a game we develop. But I wonder do they also have exclusibe rights to all the names of their super hero characters? For example will people get in trouble if they name their games 'premagneto', 'superwolverine', 'exbeyonder' or 'the cyclop'?"} {"_id": 25, "text": "How do I publish to Google Play if I'm under 18? I've finished my first Unity and want to release it on the Google Play store but can't because I am under 18. The main issue is that Google Wallet requires you to be over 18. How could I work around this?"} {"_id": 25, "text": "How do I protect my rights to my game on the web? My small games all have different gameplay. I want to showcase them through the internet. However, I'm worried about them and their concepts getting copied. How can I protect them? Also, if I have to openly display the code to the open source community, how can I make sure I get credit for my work."} {"_id": 25, "text": "To what extent it is legal to declare support of third party commercial products' assets? Is it legal to say that MyGame supports other (specific) games' textures, sounds and models? I'd like to get involved into an open source game project and implement support for Quake's weapon models (for example), but the owners of the project don't know about the legal aspect of it, so I'm asking here."} {"_id": 25, "text": "Cloning a Game Dev diary while using original assets I'm currently cloning a game and still using the sound and graphic assets of the original. I know that I may not distribute those assets but what about publishing a video of my progress as part of a dev diary, is that allowed? Thanks."} {"_id": 25, "text": "Can I sample audio sources from others without asking? As the title says, would it be considered legal if I take a part of an audio source (any media like music, dialog, video, etc.) to use in a project, whether it is for commercial or non commercial purposes, without contacting the owner creator of the asset? As an example, Earthbound used this technique to create unique and memorable soundtracks."} {"_id": 25, "text": "List of all games names? Is there any list of game names anywhere, so i can choose a name for my game and avoid (legal) conflicts with other games as much as possible?"} {"_id": 25, "text": "Legal issues around using real players names and team emblems in an open source game I'm writing a sports management simulation game. Like most sport management games, it makes heavy use of statistics. I would like to use real players, teams and league names. i) Am I running the risk of getting into legal battles if I should use the real names? ii) Also what about team colours and emblems etc? Update Much thanks for all the input!"} {"_id": 25, "text": "Could you create a game for an older system (say, SNES) and sell it with an emulator as well as the game? I was looking into development for the SNES in assembly, as programming in assembly is my hobby. I then had the thought what if I could sell my native SNES games for modern use (on steam, bundled with an emulator for example)?"} {"_id": 25, "text": "Using name of real products in games My friend and I are creating a Computer Tycoon game. We're using graphics cards and other real CPUs in the game. So can we use names like GeForce 210 in the game without issues? Also, if the above doesn't work, can we just change a little bit in the name like LeForce and will that work?"} {"_id": 25, "text": "Question about Monster Rancher My Brute generators I want to build a system based on the idea of Monster Rancher's monster generation system. First, is it legal per se? Obviously, I don't know how they built theirs and I will be generating my own \"generator\". But the idea itself of being able to randomly create a character or monster based on something..is it copyrighted? patented?"} {"_id": 25, "text": "what is the legality behind \"openMW\" ( an open source implementation of morrowind) knowing bethesda those people probably sue hard....yet there is an open source implementation of morrowind which is actually quite good. but that question remains, what is the legality behind all of this? is it legal to distribute a free open source implementation adaptation of a videogame?"} {"_id": 25, "text": "Game Trailer Reference other Games I am currently developing a game that pulls in the basic ideas and concepts from 3 other games. I want to make a trailer, and can I put in the trailer something like this Pulling Game Concepts from ...Pokemon ...Fable ...and Harvest Moon Can i do this? Or would I have to get permission to even reference them?"} {"_id": 25, "text": "Can I mention other games' titles, characters, maps, weapons etc. in my game? Let's say I was about to make a quiz game where the questions are like this When was Fallout 4 released? What is your first pickaxe in Minecraft? Who do you have to kill as the last boss in Skyrim? And let's pretend I have 1000 of these questions, from 1000 games. What are the chances some of those 1000 could sue me, remove my game from the internet, pay them a fee etc.? Even if it becomes very popular. Taking it one step further, could I buy their games, take in game screenshots personally, then use those as pictures in my own game? Does it make a difference if it's a free to play or a game that has to be bought?"} {"_id": 25, "text": "Can I use popular classical music as my game's soundtrack? Can I use popular classical music in my game as a soundtrack? I'm concerned about copyright protection. I don't plan to make money off of my game. Will I break some law if I do that?"} {"_id": 25, "text": "Can i use the same name for a spell in my game that already exists in another game what does trademarks and copyrights contain. how similar can a name be to a name that already exists."} {"_id": 25, "text": "Is a programmer liable for copyright infringement in other people's mods to his games? If a programmer (P) releases a game, and a modder (M) releases a game modification which includes copyrighted content, can P be held liable for the copyright infringement in the mod?"} {"_id": 25, "text": "Issues using real names in a soccer player game Is illegal to use the real player and team names in a game? When I say game could be and desktop, mobile or fantasy game. If is illegal, is ok to change a little bit names? Instead of using Messi could I use Messsi (or something similar)? All gambling and statistics soccer websites have permissions to use those names? Thanks!"} {"_id": 25, "text": "Legal status of games with similar titles I've been working on a game for around a year and a half named Planetfall, in which you build a colony on a new planet. I've bee working on it with that title since before the announcement of Age of Wonders Planetfall. The games have some overlapping mechanics and aesthetic, but other than that it would be clear that my game is not a clone or a rip off. I know that I probably should change the name anyway (so there's no confusion between the titles) but I was wondering what the legal status is of a title that was in development since before the announcement of another similar title. If I decided to go ahead and not change the name, what could happen?"} {"_id": 25, "text": "Is it acceptable to say \"Inspired from ... game\" For a game I'm developing, I would like to use \"inspired from ... game\" to acknowledge and praise that game. But I'm not sure if this is a good idea from a legal point of view. They might think my game is a ripoff, and base the claim on my word. Any ideas?"} {"_id": 25, "text": "Copyright and patents on game design and names? We all know that each game has elements from another game but when does one cross the line of copyright? I have a view particular questions about this since this \"line\" is very vague. While looking for a name and Googling it usually return some kind of old or unknown game already with the exact same name. Can i use this name? And what about a name like Diablo, since Diablo is the commonly used name for the devil there cannot be a patent on this afaik. So would a different kind of game named Diablo be allowed? Let's say i want to make a game of mechs like in Mechwarrior. Obviously the mech designs have copyright, the name as well since i suppose. But am i crossing any rights if i make a top down tactical squad game that include mechs of different designs names and call it Clash of Steel? I understand there are not much lawyers here, but how could anyone create a game these days that does not cross the lines of copyright. Like the Mechwarrior example, there are plenty of games nowadays even movies that use this concept. For what it matters Mechwarrior could have ripped the idea from the Gundam anime series. With so many titles coming out each week including the indies it is next to impossible not to infringe into someone copyright."} {"_id": 25, "text": "Will my \"Block Buster\" game infringe on the Blockbuster (movie rental) trademark? I'm developing a small puzzle game called \"Block Buster\" and I was wondering if there will be any collision with already existing \"Blockbuster\" (movie rental company) registered trademark. Does the space or case difference in the trademark mean something? Or is there any difference in that Blockbuster is a movie renting company and I will just be selling a game? Do I really have to change the game's name?"} {"_id": 25, "text": "Using modified copyrighted music in non commercial games Background I'm making a retro style game for both fun, and an unofficial contest. I have bought a song, song X. However, I then found notation for song X, and all the instruments. So basically, it's a program recreating song X in a sense. I took the notation, and used another program to make it sound like a chiptune does (just for the fun of it, and it sounds good P). However, I would like to use this in my game. It's non commercial, but is this allowed? I would've said yes, because I'm not actually using the original, copyrighted song. I think the main point is can I Use the music with no reference to the author Use the music with a reference, since it's non profit. Not use the music at all since the melody and rhythm is copyright."} {"_id": 25, "text": "Releasing a game without really having an officially registered company I'm thinking of releasing my iOS game without formally registering a company at all. I'm not sure I even want to create a company. ITunes wants to know the copyright holder of my title. I have 2 questions regarding this 1) Can I use my (already decided upon if will exist) company name and just register it later (if the need arises)? 2) Or should I just use my NAME as the copyright holder, regardless if I plan to formally register the company later or not?"} {"_id": 25, "text": "Do I need licensing to use real city names in my game? I want to allow people to go to real places (Seattle Washington, Portland, Maine, etc.) in my game. Will I need licensing to make those places and use their names?"} {"_id": 25, "text": "Would making a satirical version of someone else's character get me sued? Licensing the rights to a popular character is definitely a hard process. Rather than licensing the rights to (insert hero here), what if I were to make a satirical version of the IP owner's character(s) like Spaceballs did? What sort of legal trouble could I face for making a satirical rip off of a character?"} {"_id": 25, "text": "legal disclaimers and lisence type for a free multiplayer browser game I have created a multiplayer browser game. The game is completely free (donations are welcome) but I would like (a) to protect my concept in some way. (b) to provide legal notes that the user should accept before registering. In some games (i.e. Travian) there are legal notes such as Terms and Conditions, Privacy Policy. Should I include things like these? Where can I get create such legal texts? I can barely afford hosting, not to mention a lawyer to write all those things for me. What should I do? Chris"} {"_id": 25, "text": "Using name of real products in games My friend and I are creating a Computer Tycoon game. We're using graphics cards and other real CPUs in the game. So can we use names like GeForce 210 in the game without issues? Also, if the above doesn't work, can we just change a little bit in the name like LeForce and will that work?"} {"_id": 25, "text": "Legal and IP considerations with publishers and playable prototypes I'm almost ready to send a playable prototype of a game to a publisher. I've never worked with publishers. What legal or intellectual property issues should I consider at this stage (if any)? In this specific case the publisher is well known... perhaps this makes a difference. Also the game is for a mobile platform."} {"_id": 25, "text": "How not to break licence laws? I have an idea for a game. Also I have almost everything worked out considering coding. What interests me the most is how can I know if that game can be published. As it would be for iOS and android, these markets are of the geratest interest for me. I found on apples store something similair to what I would make and it's published by some big game developer. How can I be sure I am not breaking any laws when publishing the game? Can I make a game like board game 'Risk'? I don't have any knowledge considering licencing. This game would be avaliable for free, with an option to donate, so money isn't my objective (but it won't hurt)"} {"_id": 25, "text": "Making an indie with friends Legal considerations I am close to finishing a game I am making with 3 friends. 1 other coder, and 2 graphic designers. We agreed from the start to split revenue (40 40 10 10). However we have no contract, and I know that I don't own the graphics sounds in my game just because \"my friend made it\". What steps should we take to make sure that all graphics sounds that were provided by my friends, are actually owned by me (the company). We have a budget of 0 so hiring a lawyer is not an option, should we draft our own contract regarding the revenue share?"} {"_id": 25, "text": "Can art syle proportions have copyright? I like the art of a mobile game called Battleheart. Is it copyright infringement if I copy only the proportions of his characters? Obviously the clothes, style of the brush, and all the rest of the art will be my own style. The gameplay of the game will be different, too."} {"_id": 25, "text": "Pac Man Public Domain? I've googled this and haven't come up with anything. Can I create a Pac Man game and not get in trouble with? Like can I sell it, and be able to make money without having to pay someone else royalties?"} {"_id": 25, "text": "Can I include a public domain book in my game? Just for fun, I want to include a bookshelf in my game with a real book (or few) that you can actually read. Would I run into any legal trouble if I included an out of print book in the public domain, such as Pride and Prejudice or Alice in Wonderland?"} {"_id": 26, "text": "Networking to make a single player RPG into multiplayer I ve written a few games in Xcode before and would like to turn one into the simplest possible 2D top down RPG multiplayer game. Essentially just needing movements around a big tiled map (I love drawing), and chat. Keen to just host my own server on the iMac I use, with python and twisted framework (new to this but happy to take the time to learn). I m thinking TCP for chat and UDP for tracking movements but do they need to be on separate servers? Also for games like this I know there isn t much on the client side. All my map drawing and game logic is set up in Xcode, which I would prefer to keep working in because I m familiar with the language and love the sprite kits and tile maps. Do I have to redo it all in python on the server side for scaling in the future? Or for cross platform? I've done lots of research and found plenty of tutorials, just want to know I m on the right track. I m not looking to make a WoW killer just something simple I can gradually build on for fun"} {"_id": 26, "text": "What sort of data should be sent for mouse based movement in a multiplayer game? I'm new to the Multiplayer Rodeo here so please bear with me... I am just getting started and I'm trying to figure out how to deal with movement. I've looked at the question Best way to implement mouse based movement in MMOG which gives me a pretty good idea, but I'm still struggling with what kind of data should be sent to the server. If a player is on position x 0, y 0 and I click with the mouse on x 40, y 40 to start movement, what information should I send to the server? Should I calculate the position based on velocity on client side and just send the expected location? Or should I send current location and velocity and direction? When the server is updating the clients on the players' whereabouts, should the position be sent only, and the clients expected to interpolate predict movement, or can the direction sent from the client (instead of just coordinates) be used. My concern(or confusion) is regarding the ping lag frequency of data update and use of a predictive algorithm, as I'd like the movement to be smooth even with a high latency, and prevent ability to cheat(though that's not the top priority)."} {"_id": 26, "text": "Game logic on the server! Good or bad? I'm currently planning a simple online multiplayer game. And here is the question. Does it make sense to make the whole game logic on the server and just send the input from the client to the server? Which are the pros and the cons or are there any reasons why I shouldn't do that?"} {"_id": 26, "text": "Input and output of a server side game using web sockets I am having a look at redeveloping an old flash based top down zombie shooter game I made in highschool so that it supports multiplayer using socket.io. My experience over the last 5 years has been mostly writing server side code, so writing the game logic itself on the server isn't a huge concern. The places I am having trouble with due to my very limited experience with sockets specifically is What the most appropriate input and output should be to and from the server in a game context. How much data is appropriate to send. Off the top of my head, I imagine the process would look something like The server runs the game (using NodeJS). Clients that connect send their input to the server (key presses, clicks, etc). Those inputs are queued against the client ID on the server and interpreted to move their character or whatever it does. The server sends back the updated position of the client as well as everything else around the client in the \"world\". The last point is where I have the most doubts. Assuming a reasonable collection of objects in the world, I am not confident that sending through the position of everything every 30ms to every client would be sustainable (though I really don't know what is sustainable with web sockets). Then again, maybe it actually is perfectly fine to do this. Obviously I can limit the amount of objects by only sending ones who have actually been updated (so static objects would never come through, etc) but I am not sure whether that is necessary at all or whether that is something extremely crucial. I also don't see this working if we implemented something like everyone being able to fire 100s of projectiles (or some other massive collection of constantly updating objects). Are there any general guidelines or common knowledge around how much data you would expect to see come through a web socket and how frequently? Am I way off the mark or would this work okay for a moderate amount of clients? I realize this all sounds very broad so to try tighten it up a bit I am specifically interested in how much data is realistic to send through web sockets and how frequently. Any auxiliary information based on the above is a great addition."} {"_id": 26, "text": "Do \"write once run anywhere\" engines require platform specific code for multiplayer? I've been investigating the myriad selection of mobile game dev engines that allow compilation of your code onto multiple target platforms, but, something I can't seem to figure out is if multi platform \"write it once\" development is possible when you bring multiplayer into the equation. I've looked at Unity and Monkey mostly, so far, but aside from seeing threads on the Monkey forum such as \"I've developed such and such networking library for Monkey\"... I can't find a definitive answer. That example is one of many that causes me concern. Is it the case that if you used a cross platform engine, you'd have to write platform specific code for the networking portion of your game app? (Even if the rest of the game did work on your target platforms with no minimal platform specific \"jiggery\". I'm not talking about cross platform multiplayer, but I do presume that'd be a happy by product of a write once deploy anywhere (within reason) networking solution."} {"_id": 26, "text": "Do \"write once run anywhere\" engines require platform specific code for multiplayer? I've been investigating the myriad selection of mobile game dev engines that allow compilation of your code onto multiple target platforms, but, something I can't seem to figure out is if multi platform \"write it once\" development is possible when you bring multiplayer into the equation. I've looked at Unity and Monkey mostly, so far, but aside from seeing threads on the Monkey forum such as \"I've developed such and such networking library for Monkey\"... I can't find a definitive answer. That example is one of many that causes me concern. Is it the case that if you used a cross platform engine, you'd have to write platform specific code for the networking portion of your game app? (Even if the rest of the game did work on your target platforms with no minimal platform specific \"jiggery\". I'm not talking about cross platform multiplayer, but I do presume that'd be a happy by product of a write once deploy anywhere (within reason) networking solution."} {"_id": 26, "text": "client server Silverlight turn based game domain model question I am making multiplayer (2 players) Minesweeper like the one that's available on MS Live Messenger. Client side is going to be silverlight, server side will be MVC Application. Client (the one who is waiting for his turn) will poll server every X seconds to get current state, the other client (who's turn it is will post his click to server and than roles will reverse) Now my question is should domain model classes be the same for client and server side? I mean you need Minefield class on both sides, but while server side class will have rules and logic, client side will be more or less a data holder."} {"_id": 26, "text": "Revenue model for an open source multiplayer game I've had an idea for a multiplayer game, and ideally, I'd absolutely love for it to be open source. However, I also want to make a profit from it so I can make more games and maybe even have a dev team. Is it possible to keep it open source and generate revenue? One idea I've had is to charge for online multiplayer services, but then users could easily circumvent that by patching in their own servers. Is there a revenue model that can work for this kind of game project?"} {"_id": 26, "text": "PHP Browser Game Private Messages? First off, I'm asking this question here because gaming and messaging are intimately connected. Why win if you can't gloat? Nevertheless, I won't be offended if this needs to be moved to overflow. I need a PM system for my browser game, which already has a user and authentication system (To clarify the game already has a user system). Specifically, I'm wondering if a PHP library already exists that I can use to save some time. Better yet, if anyone knows of a nice Codeigniter library for messaging, that would be perfect. I already have a good idea on how I would approach this if I have to write my own, but it seems like something that would already exist in a robust form (despite my failed Google searches). Requirements Messages can be sent to individuals, multiple users, and guild mates (which is essentially just multiple users with server side selecting who to target). Users can reply to individual or all recipients Messages appear in sender's outbox and receiver's inbox. Utilizes some 2 table design to handle marking read deleting messages on a user by user basis Messages are semi threaded. I.e. I won't necessarily have them appear in the GUI as threaded, but previous messages should be included at the bottom of a reply. Maybe better to say, previous messages are identifiable and accessible. (This, I'm not yet 100 sure how I would design if I write my own. I.E. whether to include the text of the previous message into the new message or somehow remember the previous message's database ID to link later) Technology in Use PHP, Codeigniter, Javascript, JQuery, Ajax, Sqlite Note I have seen that there are some similar questions on overflow, but they were very little help in the answer department. Otherwise, people were looking for either chat boxes or more umm.. like social media site threads, which I find a bit different than something you would find in a game."} {"_id": 26, "text": "Calculating interpolation percentages I've been reading valve's article on multiplayer networking repeatedly recently and everything is starting to make since. One thing I'm wondering on though however is what percentage value to use for interpolation. For example the article shows this image Then the following explanation is given The last snapshot received on the client was at tick 344 or 10.30 seconds. The client time continues to increase based on this snapshot and the client frame rate. If a new video frame is rendered, the rendering time is the current client time 10.32 minus the view interpolation delay of 0.1 seconds. This would be 10.22 in our example and all entities and their animations are interpolated using the correct fraction between snapshot 340 and 342. At the end of the last sentence it states to use \"the correct fraction between snapshot 340 and 342\". What would this fraction be? Is it the time it takes for a frame to render?...or am I way off?"} {"_id": 26, "text": "How can I keep a consistent number of players per match in a continuous multiplayer game? Fortnite Battle Royale is an example of a non continuous multiplayer game. 100 players join a game which has fixed start and end times. When there's only one player remaining, the game ends. Agar.io is an example of what I like to call a continuous multiplayer game. Players join in and die out, but the game goes on forever. How would a game developer design a system to split players into different groups when there're too many online to fit in a single game? Let's say a game has a limit of 10 players, and 50 players are trying to join. The server will split them up into 5 separate groups. New players will be sorted evenly into these groups to replace players who died. When the player count increases past the global limit, new games will be created to fit them. The problem arises when the player count decreases. The system needs some way to seamlessly delete extra groups of players that are no longer needed. How can that be done without A) interrupting games to merge players together or B) block new players from joining into the group(s) that require deletion and waiting for everyone in it to die (which will be a bad experience for the last few players). Agar.io obviously has a player population management system that works, so how do they do it?"} {"_id": 26, "text": "Can game replays be used as cheat protection? Say you're writing a complex turn based multiplayer strategy game in the browser (i.e. JavaScript). The game state is big and complicated (think line of sight calculations in a 3d world). There can be many simultaneous games on different maps. Thus keeping all of those maps in memory on the server and verifying every single client action as it happens would quickly become prohibitively expensive. So we're faced with the situation that we cannot trust anything from the client and we cannot verify every individual client action on the server due to cost. Has anyone experimented with recording game sessions and running offline asynchronous verification on them as a cheat deterrent? Ideally, the players themselves would get suspicious and spot check each others' replays. Obviously there would be a significant delay between the cheat happening and the player getting flagged, but in a long running strategy game with persistent state, I think this would be a significant disincentive. Do you know of such examples? Have they worked well?"} {"_id": 26, "text": "Hobbyist game dev, want to create async multiplayer game. Are server costs manageable? I want to make the game I want to play, and that game happens to be an asynchronous multiplayer game. Think Hero Academy or Hearthstone, where there are 2 players and each submits moves to a central server. Alternatively (and not ideally), clients connect to each other and play is limited to a fixed window of connection, but still there needs to be a central server to acquire new opponents. That said, this is very much going to be a hobby type endeavor I'm just one guy after all. This is not going to commercially support itself. If I have 100 players ever, that would be fantastic. Given that I'm going to have to eat server costs myself, what are my options for getting a server? I don't need much bandwidth or CPU, due to the nature of async games only the sending of the gamestate current move, and perhaps some checking of legal moves. Going to Amazon or getting dedicated hosting seems drastically overkill for what I want. If it makes a difference, I'm intending to learn and use Unity for this."} {"_id": 26, "text": "How to manage a multiplayer asynchronous environment in a game I'm working on a game where players can setup villages, which can contain defending units. Any of these units (each on their own tiles) can be set to \"campaign\" which means they are no longer defending but can now be used to attack other villages. And each unit on a tile can have up to a 100 health. So far so good. Oh and it's all asynchronous so even though the server will be aware that your village is being attacked, you won't be until the attack is over. The issue I'm struggling with, is the following situation. Let's say a unit on a tile is being attacked by a player from another village. The other player see's your village and is attacking your units. You don't know this is happening though, so you set your unit to campaign and off you go to attack another village, with the unit which itself is actually being attacked by this other player. The other player stops attacking your village and leaves your unit with say a health of 1, which is then saved to the server. You however have this same unit are attacking another village with it, but now you discover that even though it started off with a 100 health, now mysteriously it only has 1... Solutions? Ideas? Edit The simplest solutions are often the best. I referred to Clash of clans below, well after a bit more digging it seems that in CoC you can only attack players that are offline! ha, that almost solves the problem. I say almost because there's still the situation where a players village could be in the process of being attacked when they come back online, still need to address that. Edit 2 A solution to the \"What happens when a player is attacking your village and you come online\" issue, could be the attacking player just get's kicked out of the village at that point and just get's whatever they had won up to that point, it's a bit of a fudge but it might work."} {"_id": 26, "text": "Building a simple bomberman game with Node.js and Socket.io I'm building this game mostly because I want to experiment with Node.js and Socket.io, and the game is more like a proof of concept. To start with, I have a 2D grid system as the game map. . . . . . . . . . . . . . . . Each position with values 0 empty 1 wall can not be destroyed by explosion 2 obstacles can be destroyed by explosion 3 bomb 4 9 some powerups 10 gt the id of player CLIENT SIDE I'm not planning to have any game logic happen on the client side, so the client simply send left, right, up, down and plant a bomb command to my server. There is however, some simple check that happen on the client side 1. check that there's no wall at the direction the client is moving to 2. the client didn't plant a bomb in the last 3 seconds. The client also receives the state of the map as a 2d array and knows how to draw everything using that info. SERVER SIDE Main game logic happen on the server side, which includes updating the position of player, calculating the damage of bomb explosion destroy stuff in the range, except walls and space behind walls Questions When the player is moving, he won't see himself moved until he gets the data back from server that updates his position. So I worry this delay may affect user experience, is it better that I move his position on his browser right away, and only update other players' position using info received from server, that means his own movement is rendered away, while his position info is sent to server. When rendering everything, it's simple to implement that whenever anything on the map move or change, redraw everything with the new data. Is that a waste? Can I only update things that change, for example, a player move right 1 position, nothing else changed on the game map, do I still have to redraw everything? I think I'm going to use Canvas to render. Please feel free to comment or answer if you think there are places I can improve or I simply thought wrong, thanks!"} {"_id": 26, "text": "What are some ways to prevent or reduce cheating in online multiplayer games? Punkbuster exists just to prevent cheating, and yet cheating is common in punkbuster enabled games. Modern Warefare 2 is seriously locked down from the end user running their own server or making any mods, and cheating happens constantly. For a multiplayer game where each client is running on a PC, what can be done to reduce or eliminate cheating?"} {"_id": 26, "text": "Multiplayer and creeps (NPC enemies) how to compute bullet hits given the lag? We are making a multiplayer co op game, where players will shoot not each other but AI enemies (creeps), controlled by the game. The chosen implementation is client server with an authoritative server. Edit we use client side prediction for both creeps and avatats to give the illusion of immediate responses. So far we managed to make creeps movement syncronized on the client and the server, that is at the same point in time each and every creep are located in the very same place on the client and on the server. However, the player avatars cannot be syncronized in this way it is simply impossible. Player avatar will always lag on the server. Now the problem arises when we try to shoot and hit the creeps. The two avatars (client and server ones) will fire bullets in different places (because one lags from another), but the creeps positions are equal. Bullets hit almost instantly, which means that quite often the bullets will not hit the creeps on one of the machines and, as the server is authoritative, it will have the final say in what actually happened. Ofcourse such behaviour is unacceptable. One solution would be to force creeps to lag on the server, but that is a poor solution as the lag (ping) may vary dynamically and, more importantly, the game is designed to allow for up to 4 player multiplayer mode and I cannot even start to think, how to fit this solution to other players' bullets. The only thing I could find so far on the internet is the fact that in FPS multiplayer shooters you see your opponent in the past and the server \"rewinds\" each of you before hit scanning. But how do you exacly implement this? Do you keep the list of recent positions actions on the server? But what if hit scanning involves taking skeletal animation into account? Do you store recently played animations aswell? Any advice would be appreciated."} {"_id": 26, "text": "Is It Possible To Make Matchmaking System Without Server? I want to make a matchmaking system without a server, but I don't know much about matchmaking. First, let me list what I want to do Cheating is not important in the game, so that the architecture will be listen server. (One of the clients in the lobby will be host.) The players will be connected to each other by sending invitations. I will not list any lobbies in the game. All the data in the game will be sent via RPC functions. (I have already coded this.) The game will be published on mobile platforms. I wonder if I can connect 2 players to each other in the game without a server. Is that possible? Can I make this kind of system by using a library like socket.io?"} {"_id": 26, "text": "How to support more than 4 XInput controllers? I'm making a multiplayer game in GameMaker Studio 2. The game supports upto 12 controllers, where the first four are XInput controllers. The rest would be DirectInput. If I try playing with 8 Xbox controllers, only 4 of them are detected in the game, as expected. But, is there a way to get more than 4 Xbox controllers working?"} {"_id": 26, "text": "Do \"write once run anywhere\" engines require platform specific code for multiplayer? I've been investigating the myriad selection of mobile game dev engines that allow compilation of your code onto multiple target platforms, but, something I can't seem to figure out is if multi platform \"write it once\" development is possible when you bring multiplayer into the equation. I've looked at Unity and Monkey mostly, so far, but aside from seeing threads on the Monkey forum such as \"I've developed such and such networking library for Monkey\"... I can't find a definitive answer. That example is one of many that causes me concern. Is it the case that if you used a cross platform engine, you'd have to write platform specific code for the networking portion of your game app? (Even if the rest of the game did work on your target platforms with no minimal platform specific \"jiggery\". I'm not talking about cross platform multiplayer, but I do presume that'd be a happy by product of a write once deploy anywhere (within reason) networking solution."} {"_id": 26, "text": "Storing quests for an online RPG in a MySQL database I'm creating an online RPG game and I've been looking around for a way to save players' progressions in quests in MySQL. I've been looking at Pim Jager's answer answer for a while and I've come to the conclusion that this could work, but then my question would be Where how do I store if a player currently has a quest accepted? How do I keep track of at which step of the quest the player currently is? This has to be saved somehow but I can't seem to figure out how I would do that. Let me know if you can help me out. Thanks!"} {"_id": 26, "text": "The tolareable lag range in a multiplayer game I am programming a multiplayer game. I calculate the ping in ms as ping the time i recieved pong the time i sent ping I implemented client side prediction and interpolation algorithms. When I test the game with my friends, it works quite fine for those who have a ping under 100ms, but after 120ms it becomes unplayable as they have told me. So my question is wheter I should try to improve the client's game experience under a latency more than 120 ms or not ( is a lag 120ms considered tolerable ? ) Thank you all ! NOTE My game is a fast paced game so the lag compensation matters."} {"_id": 26, "text": "Single player game into Multiplayer game I developed a Single player game in Flash (Tic Tac Toe) and in the Multiplayer mode i will be able to do both player playing on the same system with out network. I would like to extend it and make it enable to play the Multiplayer game for two player playing it online. How i can be made give me some ideas , How test the Multiplayer game playing along with different computers(I do not have internet connection in home). How I able to change the single player game into Multiplayer game , any minor changes required or I have to change the code base completely. In which way i can make it possible."} {"_id": 26, "text": "Race condition implementing World Boss System in Web Browser MMO using PHP I am trying to create a world boss system using PHP. But I am having a problem with how to account for all the damage while updating the health of the boss in real time. The current damage process is as follows Get boss' current HP from database. Reduce the HP based on the calculated damage. Update the boss' HP to database. Example Player 1 (P1) attacks the boss. Calculated damage is 10. The boss' current HP is saved to variable boss hp which is 100. It will now be boss hp 10. Which is 90. The boss' HP in database is then updated. Now, imagine two player attack the boss simultaneously... P1 attacks the boss. Calculated damage is 10. The boss' current HP is saved to variable boss hp which is 100. It will now be boss hp 10. Which is 90. Before P1 updates the boss hp in database, P2 also damages the boss. P2 saved the boss' current HP to his her own boss hp variable which is 100 at the moment. P2 also performs step 2. boss hp 10. Which is also 90. P1 now updates the boss hp in database ( 90). P2 also updates the boss hp in database ( 90). The boss hp should be 80 but the damage of P1 has been neglected since P2 updates the boss hp last. How to avoid this problem?"} {"_id": 26, "text": "Handling increasing numbers of users (server) For this post, we'll assume my game is multiplayer chess as it essentially requires the same functions. User logs in to the server and requests a game the server provides a simple matching service and once done, they start the game. They get 30 seconds timed by the server per turn with 6 players in each game and however many spectators (probably very limited). I would like to know how you would scale this. I've considered two options Option 1 1) Main server to handle login match making (which regardless of user numbers should be a fairly easy task) 2) Start new Node servers for each game that close when the game ends. I'm not entirely sure how this could be implemented yet. (i.e. would the user connect to the main server still and the requests just be passed to the new server or would the user change connection to the new server and then back again when done? changing connection would reduce the load even further and as the two servers won't require communication between them, should be fairly simple) Option 2 Have 1 Node server and somehow scale it. Suggestions input? I'm planning on hosting on Amazon AWS and am well aware that the chances of my game even warranting this level of detail are probably nil but I'm taking this as a learning opportunity. Thanks."} {"_id": 26, "text": "Cocos2D v3 and Physics simulation on server I'm trying to develop a real time multiplayer game using Cococs2d v3. The game is basically a side scrolling racing game. I wanted to develop the client using Cococs2d for iPhone, and the server side using Java. I've read about real time networking and the difficulties I can encounter, but also how can I overcome it. The most helpful articles I read was Valve's, Glenn Fiedler's game networking article and Gabriel Gambetta's article on fast paced multiplayer games. I can attach links to those articles if anyone is interested ) I have come to the conclusion that the physics should be implemented both on the client side and the server side. Using cocos2d v3 this could be done without any problems on the client side, but how can I use the same physics simulation in my server written in Java? For example how could the server know if there's a hill the client player is climbing, or if there's an obstacle it need to collide with? The physics engine the client use is written in Objective C.. Am I missing something over here? If my question is not clear enough, please tell me and I will explain it in more details. Thanks in advance )"} {"_id": 26, "text": "Input and output of a server side game using web sockets I am having a look at redeveloping an old flash based top down zombie shooter game I made in highschool so that it supports multiplayer using socket.io. My experience over the last 5 years has been mostly writing server side code, so writing the game logic itself on the server isn't a huge concern. The places I am having trouble with due to my very limited experience with sockets specifically is What the most appropriate input and output should be to and from the server in a game context. How much data is appropriate to send. Off the top of my head, I imagine the process would look something like The server runs the game (using NodeJS). Clients that connect send their input to the server (key presses, clicks, etc). Those inputs are queued against the client ID on the server and interpreted to move their character or whatever it does. The server sends back the updated position of the client as well as everything else around the client in the \"world\". The last point is where I have the most doubts. Assuming a reasonable collection of objects in the world, I am not confident that sending through the position of everything every 30ms to every client would be sustainable (though I really don't know what is sustainable with web sockets). Then again, maybe it actually is perfectly fine to do this. Obviously I can limit the amount of objects by only sending ones who have actually been updated (so static objects would never come through, etc) but I am not sure whether that is necessary at all or whether that is something extremely crucial. I also don't see this working if we implemented something like everyone being able to fire 100s of projectiles (or some other massive collection of constantly updating objects). Are there any general guidelines or common knowledge around how much data you would expect to see come through a web socket and how frequently? Am I way off the mark or would this work okay for a moderate amount of clients? I realize this all sounds very broad so to try tighten it up a bit I am specifically interested in how much data is realistic to send through web sockets and how frequently. Any auxiliary information based on the above is a great addition."} {"_id": 26, "text": "Why can't cross platform multiplayer games exist? At least, why are they so difficult to make? assuming that's the reason why not even AAA studios accomplish this feat for their games. Especially with modern cross platform game engines like Unreal and Unity that can build on Xbox, PS4, and PC, why hasn't this been done yet on a large scale? For example, Diablo III is a game released on a variety of platforms. Despite it being a product of Blizzard, one of the wealthiest video game companies in the world, it does not allow an Xbox player to play with someone using a PC."} {"_id": 26, "text": "Efficient solution for multiplayer space partioning? This question is a little tricky, but I will try to make it clear. Lets say I am building an online game (not MMO scale), but that supports as many players as possible, in a authoritative server approach. I want really big worlds with lots of AI simulated enemies. I am aware of a few strategies to save server CPU by subdividing the space and not processing what doesn't need processing. I have already split the world by regions, that will require loading times and small transitions, which I think is important to maintain the quality of gameplay when playing locally (alone or even with a couple of friends). I don't expect the players to be in more than one or two regions. The problem is that a region can become pretty big, and have a lot of NPCs simulating at once. How do I handle this without affecting the players' experience? Approaches like one server per region and alike are not in the table. I am mainly looking for data structures to hold hordes of enemies, and even peaceful NPCs. To finalize the question, please note that vehicles exist, therefore its considerably fast to travel within a region, influencing the \"when\" to cull areas."} {"_id": 26, "text": "Is it possible to control the difficulty of a multiplayer game? I'm developing a multiplayer game, played between 2 players. But in these types of games, there can only be 1 winner and 1 loser for per match. So for each player who wins, another player had to lose. This means that roughly 50 of all players in the game are having a bad time (losing more than they win). In a single player game, it's easy to solve the problem of \"50 of players lose more than they win.\" You just make the game easier to beat (reduce difficulty). Unfortunately, you can't do this with a multiplayer game, since players' opponents are other players. I don't know if there's a way to control the difficulty of a multiplayer game, but is this even possible?"} {"_id": 26, "text": "How to solve \"server lag\" problems that break the game How do real time multiplayer games deal with latency problems (or server lag )? Imagine an online fighting game where 2 players battle head to head in real time. When a player performs an action, there'll be a short delay until that player's action appears on the opponent's computer screen. This delay causes many game breaking problems. Let's say 2 hypothetical players, Player A and Player B, are fighting against each other right now in the game, and the latency is 1 second. Player A is moving toward Player B, but then Player B places a wall (or something of the like) that stops Player A from moving toward Player B. Player A doesn t see the wall appear on his her computer screen until 1 second later, but by then Player A has already moved past where the wall was placed. In a more game breaking situation, Player B is just about to kill Player A. Right before that happens, Player A uses a special attack that instantly kills Player B. But on Player B s computer, Player B kills Player A, because it takes 1 second before Player A s special attack happens on Player B s computer. This makes it so both players die even though only Player B was supposed to die. One solution to deal with the latency issue is to implement an artificial delay so that when there s a discrepancy, one player s game is momentarily paused to wait for the other player s game state to catch up. This is not a good solution because it makes the game feel extremely laggy and unresponsive, and it also renders some reactive actions useless (like dodging) because of the artificial delay. What can be done to fix these latency problems?"} {"_id": 26, "text": "Is It Possible To Make Matchmaking System Without Server? I want to make a matchmaking system without a server, but I don't know much about matchmaking. First, let me list what I want to do Cheating is not important in the game, so that the architecture will be listen server. (One of the clients in the lobby will be host.) The players will be connected to each other by sending invitations. I will not list any lobbies in the game. All the data in the game will be sent via RPC functions. (I have already coded this.) The game will be published on mobile platforms. I wonder if I can connect 2 players to each other in the game without a server. Is that possible? Can I make this kind of system by using a library like socket.io?"} {"_id": 26, "text": "How well (or badly) does Minecraft SMP scale? Has anyone tested and collected some data about how well does Minecraft SMP scale, with an increasing number of players (up to large amounts of players)? I.e. the bottlenecks are mostly in the server or in the client or both if the players are all in the same area, or if they are in different areas, or it is irrelevant where they are"} {"_id": 26, "text": "Cocos2D v3 and Physics simulation on server I'm trying to develop a real time multiplayer game using Cococs2d v3. The game is basically a side scrolling racing game. I wanted to develop the client using Cococs2d for iPhone, and the server side using Java. I've read about real time networking and the difficulties I can encounter, but also how can I overcome it. The most helpful articles I read was Valve's, Glenn Fiedler's game networking article and Gabriel Gambetta's article on fast paced multiplayer games. I can attach links to those articles if anyone is interested ) I have come to the conclusion that the physics should be implemented both on the client side and the server side. Using cocos2d v3 this could be done without any problems on the client side, but how can I use the same physics simulation in my server written in Java? For example how could the server know if there's a hill the client player is climbing, or if there's an obstacle it need to collide with? The physics engine the client use is written in Objective C.. Am I missing something over here? If my question is not clear enough, please tell me and I will explain it in more details. Thanks in advance )"} {"_id": 26, "text": "Achieving smooth movement curves correct collision detection with a google app realtime multiplayer game server I'm an hobbist game developer. I'm trying to make a clone of a game like this http superhex.io to experiment with multiplayer online. First of all I'm not sure if there is a better way to implement server client comunication. So far I have implemented a server which updates the game state every 0.5 seconds and sends the information to all the clients. You can try my current prototype here https hexpose.appspot.com With respect to local development where the 0.5 seconds rounds are very regular, playing on the public server you see that the pace is not regular... I think this is due to a variable latency in server client comunication. Suppose I have many players moving on an arena like in this game. The superhex original gameplay is very fluid, you see enemies move on smooth curves. How this can be achieved? The position of enemies is known later (because of client server client latency) than the position of my player. But collision are anyway correctly detected. Is it just a matter of very slow latency and good server infrastructure or it depends on game logic implementation?"} {"_id": 26, "text": "Anti cheat How secure is the client? Let's say, theoretically, that I'm developing a first person shooter with, of course, a map with things like walls. In the client code, the player is obviously halted upon collision with these wall objects. The server, however, only receives the player's location coordinates. Without some sort of data encoding in the client, the player could easily read the network communication to the server and send false coordinates to the server, allowing them to go wherever they wanted. My question is, is there a way to encode this location message to the server before it exits the client binary such that it would be extremely difficult for someone to read? Even by someone who disassembles the code to try and break the encoding? Or do all player collisions have to be detected by the server?"} {"_id": 26, "text": "In what kind of variable type is the player position stored on a MMORPG such as WoW? I even heard J. Carmack quickly talk about it... How a software can track a player's position so accurately, being on a such huge world, without loading between zones, and on a multiplayer scale ? How is the data formatted when it passes through the netcode ? I can understand how vertices are stored into the graphic card's memory, but when it comes to synchronize the multiplayer, I can't imagine what is best."} {"_id": 26, "text": "Handling different version clients in a multiplayer game What are various ways of handling different version clients in multiplayer games? For example, when there's an update, some games allow you to play with people who have a different version of the client. How is this handled?"} {"_id": 26, "text": "How can I implement multiplayer cloaking with visuals that resists client side hacking? I've been thinking about implementing stealth in a multiplayer game. It's a MOBA style game, so think League of Legends (LoL) and Heroes of the Storm (HotS). Multiple clients connect to a single server, which broadcasts the game state to all clients. Clients send their input data to the server, which might reject it when encountering invalid commands, thus rendering cheating impossible (well, in theory). Now, I mention these games on purpose because both implemented stealth differently. LoL has stealth with two possible states you're either completely visible or completely invisible. HotS on the other hand, implements stealth in such a way that you can tell by a shimmer in the air I think this is a neat mechanic, as it promotes rewards paying attention to your surroundings. However, this being a multiplayer game made me realize that this might prove easily exploitable. When you implement stealth in 'the LoL' way, you can simply stop sending player coordinates to the other clients. When the player's character breaks stealth, the server can broadcast the location again. However, with the HotS model, a shimmer can be seen in the air where the character is moving about. This means that the server must be sending the player's location to the other clients. Which means that players that change the texture or model or even the game code itself could render the cloak mechanic useless. Here is a thread on the HotS boards about it. My question is whether there is some way to implement cloaking (with a 'shimmer', la HotS), without having the issue that crafty players can modify the game (data) and 'beat the system'. Is this possible, and if not, how do other multiplayer games with this mechanic deal with this? Is only the LoL style of invisibility uncheatable? I thought about having the server send bogus 'cloak' locations every now and then, but this also harms fair players that are just paying attention, so that won't do."} {"_id": 26, "text": "Will Geolocations for IPs ever change? I'm making a game where the geographic location of a user is used to give them a little flag icon next to their user name. To do this, I've been using the ipstack API. However, the API only allows up to 10,000 requests per month, and since I make a request every time a user connects, this could easily lead to overuse. Would it make sense to just store geolocation data on my server and only make a request when an unknown IP connects? Or will the geolocation data ever change for an IP?"} {"_id": 26, "text": "How do I manage multiplayer login? How is the typical login, loading the level and spawning handled? For example Client sends \"iwanttologinwithcharacterx\" Server does some validity checks and instantiates characterx Server sends back \"loadlevelx\" Client sends \"iaminloadingscreen\", when finished sends \"finishedloading\" Server sends \"spawnyourcharacterx\" OR just after the \"iwanttologinwithcharacterx\" the server tells the client to handle steps 3, 4, and 5 without interaction? I'm confused about what would be the ideal approach with the least room for errors. Some info The level in which players begin is always the same. Players can have multiple characters and during the game they often switch levels (this would be linked to my first question, how would I handle that cleanly? Don't destroy the playerobject between level load and just change their positions accordingly?)"} {"_id": 26, "text": "In what kind of variable type is the player position stored on a MMORPG such as WoW? I even heard J. Carmack quickly talk about it... How a software can track a player's position so accurately, being on a such huge world, without loading between zones, and on a multiplayer scale ? How is the data formatted when it passes through the netcode ? I can understand how vertices are stored into the graphic card's memory, but when it comes to synchronize the multiplayer, I can't imagine what is best."} {"_id": 26, "text": "Key mapping for a 2 players game I've been struggling for a while trying to figure out the best way to map two players on a single keyboard. Let's consider something generic Arrows Validation Cancel (optional) Some common actions shared between the two players (start, reset, etc.) So far, I used P1 WASD Space or Tab P2 Arrows Enter or Return Common R for reset The problem is that some configuration can be uncomfortable on certain keyboards (especially when there is no keypad). Plus some players like to have the direction on left hand (FPS style) and others on right hand (platformer style). Also SHIFT is usually not a good choice on windows because of the sticky keys feature. Also I'd like to avoid using a settings screen (kind of heavy for a small game). I guess a config file would be OK, but is there another way to handle this problem that would make every one happy?"} {"_id": 26, "text": "Multiplayer game with Cocos2d Javascript and Node.js It is possible to make a multiplayer browser based game using cocos2d javascript node.js? If so, is there any tutorial about that?"} {"_id": 26, "text": "Best way to go for simple online multi player games? I want to create a trivia game for my website. The graphic design does not have to be too fancy, probably no more advanced than a typical flash game. It needs to be secure because I want users to be able to play for real money. It also needs to run fast so users don't spend their time frustrated with game freezing. Compatibility, as with almost all online products, is key because of the large target market. I am most acquainted with Java programming, but I don't want to do it in Java if there is something much better. I am assuming I will have to utilize a variety of different languages in order for everything to come together. If someone could point out the main structure of everything so I could get a good start that would be great! Language choice for simple secure online multiplayer games? Perhaps use a database like MySQL, stored on a secure server for the trivia questions? Free educational resources and even simpler projects to practice? Any ideas or suggestions would be helpful..."} {"_id": 26, "text": "QT for lan game devleopment I am making a small game for a course in my school and was planning on using QT to build it. I have worked with pygame last year and turbo c about 5 years agao to make games, small easy stuff. This time I am planning to make a game that supports multiplayer over lan, the game idea is simple however, information about the game is here. I was hoping to know from you all, if it is a good choice to use QT for this! I am totally new to QT, but a decent c programmer. Also what problems would I encounter when it is a LAN game, for a start I just want it to support 2 players on the local network. Thanks"} {"_id": 26, "text": "Client side prediction on FPS game I've recently attempted to develop a simple client prediction for an FPS based on Gaffer on Games famous blog (http gafferongames.com game physics networked physics ). Now I've gotten to the point that everything works (more or less), my main problem is crossing the message sent from the server and finding the appropriate snapshot on the client. I can use the last average ping time to find a very near state, but it will never be exactly timed placed as on the server. So my question is how exactly can I sync and find the time stamp sent from the server to the client and find which snapshot is the correct one on the client?"} {"_id": 26, "text": "HTML5 multi player game data event validation best practices I'll start by saying that I am fully aware that this question might seem subjective at first, but I'll try and provide a specific test case scenario for it to be a clear question about validating the data received from 2 multiplayer game clients. Scenario Imagine we have a multi player Tower Defense (TD) game. And let's assume that the game is built using HTML5 Canvas, Javascript and a multi threaded web server, for example, Tornado running in the back end. And in this scenario both of the players have an option to place a turret anywhere they want. After a turret is placed, a bunch of enemies are released from both sides and move in a straight line towards the other side. As soon as an enemy reaches turret range, we can assume that it is destroyed in 1 5 shots. If it takes more than that, the enemy safely passes to the other side. Now, my problem lies in the fact that usually I would do all the validation server side, but it becomes increasingly difficult to do, because I would need to simulate every step of the game. Instead, I would like to depend on the event data (enemy destroyed enemy gets safe passage) received from both clients. Question The main question then is this What is the best and hopefully easiest way to implement these sorts of checks and would there be anything prohibiting me from continuing with the development using HTML5, Canvas and Javascript?"} {"_id": 26, "text": "Best way to go for simple online multi player games? I want to create a trivia game for my website. The graphic design does not have to be too fancy, probably no more advanced than a typical flash game. It needs to be secure because I want users to be able to play for real money. It also needs to run fast so users don't spend their time frustrated with game freezing. Compatibility, as with almost all online products, is key because of the large target market. I am most acquainted with Java programming, but I don't want to do it in Java if there is something much better. I am assuming I will have to utilize a variety of different languages in order for everything to come together. If someone could point out the main structure of everything so I could get a good start that would be great! Language choice for simple secure online multiplayer games? Perhaps use a database like MySQL, stored on a secure server for the trivia questions? Free educational resources and even simpler projects to practice? Any ideas or suggestions would be helpful..."} {"_id": 26, "text": "Hobbyist game dev, want to create async multiplayer game. Are server costs manageable? I want to make the game I want to play, and that game happens to be an asynchronous multiplayer game. Think Hero Academy or Hearthstone, where there are 2 players and each submits moves to a central server. Alternatively (and not ideally), clients connect to each other and play is limited to a fixed window of connection, but still there needs to be a central server to acquire new opponents. That said, this is very much going to be a hobby type endeavor I'm just one guy after all. This is not going to commercially support itself. If I have 100 players ever, that would be fantastic. Given that I'm going to have to eat server costs myself, what are my options for getting a server? I don't need much bandwidth or CPU, due to the nature of async games only the sending of the gamestate current move, and perhaps some checking of legal moves. Going to Amazon or getting dedicated hosting seems drastically overkill for what I want. If it makes a difference, I'm intending to learn and use Unity for this."} {"_id": 27, "text": "Is my Lua form scene loading setup efficient? At the moment, I'm working on a small game project using LUA and the love2d framework. Using this framework, I've made my own assets (i.e. button images, form images, etc), and using these assets I've been able to make a functional application, but not yet a game. In my project, I plan on having several scenes, and I'm not quite sure whether my method for scene management switching is efficient safe to use (safe, as in minimal bugs). So the process I'm using is as follows if scene selector.active scene \"splash\" then if sceneSplash.loaded false then sceneSplash.link.load() sceneSplash.link.update(dt) sceneSplash.link.draw() sceneSplash.loaded true else sceneSplash.link.update(dt) end elseif scene selector.active scene \"menu\" then if sceneMainmenu.loaded false then sceneMainmenu.link.load() sceneMainmenu.link.update(dt) sceneMainmenu.link.draw() sceneMainmenu.loaded true else sceneMainmenu.link.update(dt) end end where scene selector is a link to the follow file Misc Vars active scene \"splash\" version nil Resources cre nil xp nil End Vars Global Script Indicator calls calls.active scene active scene calls.version version return calls and sceneSplash sceneMainMenu are links to lua files which act as the scenes. Each file manages its own updates, which are passed through by the main.lua found by the love.update and love.draw functions which are passed through to the forms relevant load update draw functions. I'm aiming at using about 10 forms, 3 variable files and 2 misc function files (file management encryption IO operations logging etc). So the TL DR version is is it efficient safe (safe in terms of minimal bugs) to pass through draw and update functions from main.lua to other lua script files? So far, the process works without any bugs, even when I go back to a previously accessed 'scene', so I assume the process will work 'safely' when I'm using more scenes."} {"_id": 27, "text": "Efficient tile maps in Corona SDK I need to create a tile map based level system for Corona SDK that loads files created with Tiled 1 . It also needs to support user touch scrolling and zooming. I've searched the Corona forums for possible solutions but the ones they talk about don't convince me. They basically have a matrix of Sprite objects which have an image loaded and a given position. That makes scrolling and zooming a bit hard. Any better ideas? 1 http www.mapeditor.org"} {"_id": 27, "text": "Why can t this boolean stop the sound from playing 60 times a second? The code local dontPlayMoreThanOnceDammit false function Behavior Awake() local sound CraftStudio.FindAsset( quot motorbuson1 quot ) self.mySoundInstance sound CreateInstance() self.mySoundVolume 1.0 self.mySoundInstance SetLoop( true ) self.mySoundInstance SetVolume( 1.0 ) end function Behavior Update() if dontPlayMoreThanOnceDammit false and CraftStudio.Input.WasButtonJustPressed( quot on quot ) then self.mySoundVolume 1.0 self.mySoundInstance Play() dontPlayMoreThanOnceDammit true end if CraftStudio.Input.IsButtonDown( quot off quot ) then self.mySoundInstance Stop() dontPlayMoreThanOnceDammit false end end Error it gives"} {"_id": 27, "text": "Roblox script Can't get \"IntValue\"? I am new to Roblox scripting (Lua apparently) and was fiddling with a function that is called when one Part (dubbed the \"Sender\") is touched by another Part, which is actually a tool with a Part called \"Handle\" inside of it, and a third Part nested inside that. I have also added an IntValue to the latter to be read upon touching. The object tree looks like this Apple (Tool) L Handle (Part) L TouchInterest L Value (IntValue) L Apple (Part) L Handle to Part Strong Joint The function is called alright, and the part with the name \"Handle\" is correctly identified, but I cannot for the world get a hold of the IntValue using the following code function onTouch(hit) print(\"Sender touched by \"..hit.Name) local val hit FindFirstChild(\"IntValue\", true) if val not nil then print(\"Found IntValue \"..val.Name) if val.Name \"Cash\" then Get Money For Apple print(\"Players \"..game.Players.LocalPlayer.Name) game.Players.LocalPlayer.leaderstats.Money.value game.Players.LocalPlayer.leaderstats.Money.value val.value end else print(\"IntValue Not Found!\") end hit Destroy() end script.Parent.Touched connect(onTouch) In other words It keeps on logging \"IntValue Not Found\"! I have changed the name of the IntValue to \"Value\" and back to \"IntValue\" to no avail. I have been adding clones of it to several different layers of the composite object, but no results. Any help is greatly appreciated! BTW The object is a Tool, because the player is supposed to be able to pick it up and place it on the \"Sender\"."} {"_id": 27, "text": "Obscuring stored info in a flat text file I have an idea for an addon for World of Warcraft which would basically be a minigame within the game itself. Eventually, I'd like to have players be able to compete against each other directly. The game would have some RPG like elements, particularly statistics and abilities, which it would be undesirable for the end users to modify. So the fact that this is a client side script, where everything (logic and data storage) are all in flat text files, means that it's impossible for me to truly secure things. But I'd like to at least make it non trivial to alter things, e.g. so that you can't just open up a file in notepad and type in 'Strength 256'. I'm looking for any ideas on how I might obfuscate the data, preferably something which is easy to implement as it's not really what I feel like spending my time on, but probably more sophisticated than ROT 13. As an example, one idea I had, which I'm not sure if it's feasible (have never made an addon for WoW before) is to serialize the data in base 64."} {"_id": 27, "text": "Shortest rotation value I have a top down game. The player moves the avatar with WASD where W rotates the avator to 180, S rotates to 0, A rotates to 90 and D rotates to 270. I also do diagonal movement so if they hold SA it rotates to 45, WA it rotates to 135, WD it rotates to 225, and SD it rotates to 315. I smoothly rotate from the current rotation to the hardcoded desired rotation based on those key combo's. Of course what happens is if I'm rotating from anything 180 to 0 it goes the long way back to 0. So if I'm at 270 rotation and I press S key it sends it back to 0 but that goes from 270 to 0 vs going from 270 to 360 which would result in the same end result but how it got there would be shorter. I was looking at this (https answers.unity.com questions 556480 rotate the shortest way.html) and trying to translate it but it's not working. Below is my translation. function Script CalcShortestRot(current, target) if current target then return from end local dist target current 180 dist dist math.floor(dist 2 180) 2 180 180 System Print(\"Dist \"..dist) if dist lt 0 then System Print(\"Value 1 \"..target current) return current dist else System Print(\"Value 2 \"..current target) return current dist end end The usage is determine the model rotation based on direction we are going if move gt 0 then if strafe gt 0 then self.targetRot self CalcShortestRot(self.targetRot, 225) self.targetRot 225 elseif strafe lt 0 then self.targetRot 135 self.targetRot self CalcShortestRot(self.targetRot, 135) else self.targetRot 180 self.targetRot self CalcShortestRot(self.targetRot, 180) end elseif move lt 0 then if strafe gt 0 then self.targetRot 315 self.targetRot self CalcShortestRot(self.targetRot, 315) elseif strafe lt 0 then self.targetRot 45 self.targetRot self CalcShortestRot(self.targetRot, 45) else self.targetRot 0 self.targetRot self CalcShortestRot(self.targetRot, 0) end elseif strafe gt 0 then self.targetRot 270 self.targetRot self CalcShortestRot(self.targetRot, 270) elseif strafe lt 0 then self.targetRot 90 self.targetRot self CalcShortestRot(self.targetRot, 90) end self.rot Math Curve(self.targetRot, self.rot, self.damping) EDIT updated my CalcShortestRot() function per comments below but still not working. It spins all around"} {"_id": 27, "text": "L ve2d How can i select object with mouse if it's overlap? I have already some code but i can't solved this. How can i select one object with mouse if the objects are overlap? It's looks like solitaire game. I wish you can understand me... For example my code function love.load() love.graphics.setBackgroundColor(245, 255, 255) 1 carda carda.x 110 carda.y 5 carda.width 100 carda.height 150 carda.dragged false carda.dropped false 3 cardb cardb.x 110 cardb.y 20 cardb.width 100 cardb.height 150 cardb.dragged false cardb.dropped false end function love.draw() love.graphics.setColor(255, 255, 255) love.graphics.rectangle(\"fill\", carda.x, carda.y, carda.width, carda.height) love.graphics.setColor(255, 128, 128) love.graphics.rectangle(\"line\", carda.x, carda.y, carda.width, carda.height) love.graphics.setColor(0, 0, 100) love.graphics.print(\"Card nA\", carda.x 5, carda.y 5) 2 love.graphics.setColor(215, 255, 225) love.graphics.rectangle(\"fill\", cardb.x, cardb.y, cardb.width, cardb.height) love.graphics.setColor(255, 128, 128) love.graphics.rectangle(\"line\", cardb.x, cardb.y, cardb.width, cardb.height) love.graphics.setColor(0, 0, 100) love.graphics.print(\"Card nB\", cardb.x 5, cardb.y 5) end function love.keypressed(key) if key \"escape\" then love.event.quit() end end function love.mousepressed(x, y, button) if button 1 and x gt carda.x and x lt carda.x carda.width and y gt carda.y and y lt carda.y carda.height then carda.dragged true end 2 if button 1 and x gt cardb.x and x lt cardb.x cardb.width and y gt cardb.y and y lt cardb.y cardb.height then cardb.dragged true end end function love.mousemoved(x, y, dx, dy) if carda.dragged then carda.x carda.x dx carda.y carda.y dy end 2 if cardb.dragged then cardb.x cardb.x dx cardb.y cardb.y dy end end function love.mousereleased(x, y) carda.dragged false 2 cardb.dragged false end"} {"_id": 27, "text": "how to display current time as a static value in lua pico8 Pico8 has a function time() that when called displays the current time from start of program. i.e. print(time(),0,0,14) prints time at (0,0) with colour 14 However the function doesn't stop and keeps drawing the time each frame. I'm trying to figure out how I would draw the time without it increasing changing. So If I printed this 5 seconds from the start of the program I'd want it to display 5, but not change from that 5 value. https pico 8.fandom.com wiki Time I don't know how to store a static value of this time as a variable. Although according to the wiki, assigning var time() will cause time at 0 to be stored. Another way of phrasing this is...how would I display the time of 10 seconds when the following print is triggered? So after 10 seconds \"time's up\" is displayed. How would I display the current time 10, as well, as a static? Maybe I don't know what the time is when the event is triggered, so how can I count using time()? function init() last time() end function update() (empty update to use game loop) end function draw() cls() if (time() last) gt 10 then print(\"time's up!\", 44, 60, 7) end end"} {"_id": 27, "text": "How do I select a portion of the window using Love2d I want to be able to divide the window of the game in, lets say, 3 places, and when the mouse (or touch) click one of those places, execute some code. Do I have to make each portion a button like object? or is there a way for me to use love.mouse.getPosition() and give different instructions to specifics range of coordinates?"} {"_id": 27, "text": "Obscuring stored info in a flat text file I have an idea for an addon for World of Warcraft which would basically be a minigame within the game itself. Eventually, I'd like to have players be able to compete against each other directly. The game would have some RPG like elements, particularly statistics and abilities, which it would be undesirable for the end users to modify. So the fact that this is a client side script, where everything (logic and data storage) are all in flat text files, means that it's impossible for me to truly secure things. But I'd like to at least make it non trivial to alter things, e.g. so that you can't just open up a file in notepad and type in 'Strength 256'. I'm looking for any ideas on how I might obfuscate the data, preferably something which is easy to implement as it's not really what I feel like spending my time on, but probably more sophisticated than ROT 13. As an example, one idea I had, which I'm not sure if it's feasible (have never made an addon for WoW before) is to serialize the data in base 64."} {"_id": 27, "text": "How to automate baking pizza in Corona SDK? I'm writing a game about making pizza in Corona SDK. When you buy chefs, the new chef is supposed to make some pizzas on its own like automation. I tried everything I knew about, I couldn't think of anything that would do what I'd like so I ask you guys to help me. Here is the code I think is relevant local widget require(\"widget\") local pizzeria display.newImage(\"background.png\") pizzeria.x 160 pizzeria.y 230 pizzeria scale(1,1) local pizzas 0 local chefs 0 local pizzatext display.newText( \"Pizzas \", 100, 200, display.contentWidth 0.6, display.contentHeight 0.7, native.systemFont, 16) pizzatext setFillColor( 10, 0, 0) local pizzacount display.newText(pizzas,165,200,display.contentWidth 0.7,display.contentHeight 0.7,native.systemFont,16) pizzacount setFillColor(10,0,0) local chefstext display.newText(\"chefs \",320,200,display.contentWidth 0.7,display.contentHeight 0.7,native.systemFont,16) chefstext setFillColor(10,0,0) local chefscount display.newText(chefs,363,200,display.contentWidth 0.7,display.contentHeight 0.7,native.systemFont,16) chefscount setFillColor(10,0,0) local function pizzamaker( event ) if ( \"ended\" event.phase ) then pizzas pizzas 1 pizzacount.text pizzas end end local function addchef( event ) if(\"ended\" event.phase) then if(pizzas gt 5) then chefs chefs 1 chefscount.text chefs pizzas pizzas 5 pizzacount.text pizzas end end end local pizzamaker widget.newButton left 100, top 400, defaultFile \"button.jpeg\", overFile \"button.jpeg\", label \"Make Pizza\", height 50, width 100, onEvent pizzamaker local addchef widget.newButton left 100, top 100, defaultFile \"pizzachef.png\", overFile \"pizzachef.png\", height 50, width 50, onEvent addchef"} {"_id": 27, "text": "Lightweight lua objects vs. inheritance Although I did this a couple of times from scratch, still no solution really fits. I'm using lua for scripting in my games. Lua holds the \"prototypes\" of the game elements, that are copied to each entity on it's creation. A prototype represents a class of objects (\"Soldier with shotgun\"). Also, each prototype may hold event hooks (OnDie, OnSpotEnemy, etc). Clearly it's a prototype, not the object that will be handled. So, each time a hook is executed, I need to create an object to represent the calling entity (and any entities it interacts with) only for the lifetime of a single script execution. What it means is that a instance of the object lives in lua only for the time needed to run this script. Simple execution of this idea wasn't much work I used lightuserdata to hold the C pointer to the entity encapsuled in a being class. To access the fields of the C object, I overloaded the metatable of being. However, the fact that the fields of the object are handled by a metatable practically breaks any reasonable implementation of inheritance. I pondered with the usage of normal userdata, but I'm afraid that the dynamic allocation needed to run each script (some of them being ran each tick in the game loop) are going to ruin performance. Any suggestions? Or maybe a better solution altogether?"} {"_id": 27, "text": "How can i run my .L VE game directly from the lua interpreter? I've just started with LOVE and LUA , i'm interested in LOVE because i want to play around with something different from my dayjob(i'm a webdeveloper) and since it uses LUA and is interpreted , i though it would be a great way to try out the API. but i couldn't find how to run my .L VE game directly from the lua interpreter? i'm finding it bothersome to package the game each time i make a little test with the API."} {"_id": 27, "text": "L ve2d How can i select object with mouse if it's overlap? I have already some code but i can't solved this. How can i select one object with mouse if the objects are overlap? It's looks like solitaire game. I wish you can understand me... For example my code function love.load() love.graphics.setBackgroundColor(245, 255, 255) 1 carda carda.x 110 carda.y 5 carda.width 100 carda.height 150 carda.dragged false carda.dropped false 3 cardb cardb.x 110 cardb.y 20 cardb.width 100 cardb.height 150 cardb.dragged false cardb.dropped false end function love.draw() love.graphics.setColor(255, 255, 255) love.graphics.rectangle(\"fill\", carda.x, carda.y, carda.width, carda.height) love.graphics.setColor(255, 128, 128) love.graphics.rectangle(\"line\", carda.x, carda.y, carda.width, carda.height) love.graphics.setColor(0, 0, 100) love.graphics.print(\"Card nA\", carda.x 5, carda.y 5) 2 love.graphics.setColor(215, 255, 225) love.graphics.rectangle(\"fill\", cardb.x, cardb.y, cardb.width, cardb.height) love.graphics.setColor(255, 128, 128) love.graphics.rectangle(\"line\", cardb.x, cardb.y, cardb.width, cardb.height) love.graphics.setColor(0, 0, 100) love.graphics.print(\"Card nB\", cardb.x 5, cardb.y 5) end function love.keypressed(key) if key \"escape\" then love.event.quit() end end function love.mousepressed(x, y, button) if button 1 and x gt carda.x and x lt carda.x carda.width and y gt carda.y and y lt carda.y carda.height then carda.dragged true end 2 if button 1 and x gt cardb.x and x lt cardb.x cardb.width and y gt cardb.y and y lt cardb.y cardb.height then cardb.dragged true end end function love.mousemoved(x, y, dx, dy) if carda.dragged then carda.x carda.x dx carda.y carda.y dy end 2 if cardb.dragged then cardb.x cardb.x dx cardb.y cardb.y dy end end function love.mousereleased(x, y) carda.dragged false 2 cardb.dragged false end"} {"_id": 27, "text": "Open CryEngine console from lua script Is there a function in the CryEngine Lua API to open the Console? I cannot find it in the Lua (ScriptBind) API reference."} {"_id": 27, "text": "When PlayerRemoving event is fired, for loop does not work properly while I was implementing the Backback save feature in my Roblox Game (using game.Players.PlayerRemoving Connect(), I found that when I used a loop of any form (for, while,etc.), it would not run correctly. Here is a test program which I wrote to observe this issue game.Players.PlayerRemoving Connect(function(player) local testList \"Hello\", \",\", \"world\" for i 1,3,1 do print(testList i ) end end) However, when this code is ran, all I see in the output window is Hello And nothing else. This issue is causing a lot of issues with the rest of the code, can somebody please help? It would be very useful!"} {"_id": 27, "text": "How to use LuaJIT the same that Lua in a C program? I'm using Lua in my C program, as an library. But I read that LuaJIT is a better implementation. Is it posible to replace with LuaJIT with little change? How?"} {"_id": 27, "text": "How to make the character dash forward in Roblox? In my game I want to make a skill in a tool to dash forward for a specific range and if the character came in contact with a humanoid during the dash, it stops right on contact and stops the other humanoid from moving temporarly too and deal damage I don't know what functions should i do and where to look for them... i figured how to use onActivate and getting the mouse through Equipped Appritiate any help and guidance"} {"_id": 27, "text": "Love2d Failed to load tileset map I'm reading the Love2D Development book, which i think i will stop reading because is outdated and very instable, sometimes i got a lot of troubles. Backing to the question, i made a tileset map with Tiled and saved in .tmx with Base64 ( uncompressed ) then i used Advanced Tiled Loader and used the code from the book This is the main.lua file local loader require (\"Advanced Tiled Loader master Loader\") the path to our .tmx files and sprites loader.path \"map \" local map loader.load(\"tilemap.tmx\") function love.load() love.graphics.setBackgroundColor(255, 153, 0) load the level and bind the variable map loader.path \"map \" local map loader.load(\"tilemap.tmx\") end function love.draw() map draw() end When i tested the game, the result was this http i.imgur.com JM8EYrv.png The result was suposted to be like this http i.imgur.com W26XFjE.png So what it could be?"} {"_id": 27, "text": "Efficient tile maps in Corona SDK I need to create a tile map based level system for Corona SDK that loads files created with Tiled 1 . It also needs to support user touch scrolling and zooming. I've searched the Corona forums for possible solutions but the ones they talk about don't convince me. They basically have a matrix of Sprite objects which have an image loaded and a given position. That makes scrolling and zooming a bit hard. Any better ideas? 1 http www.mapeditor.org"} {"_id": 27, "text": "Create a game start up menu screen with Lua love 2d I just got started programming games and decided to try out love2d since I'm learning lua. I was wondering if anyone knows how I can create just a simple 2 3 button menu when you start up the game. All I want to do is make a start up menu. I have 2 files and nothing else main.lua, in which I have the game code and the level design conf.lua, in which I have the title screen code and the icon of the game I couldn't find any wiki page to help me for coding for the first time a splash screen and a overall game screen !! now i have only one screen the game screen and i want to have 3 screens 1 splash screen in wich i want to draw a image background and 3 buttons PLAY,EXIT,TITLE with coding mousepress! 2 game screen! 3 game over screen with an other background image!"} {"_id": 27, "text": "Is it possible to develop a game with Lua L ve and have the source code compiled? I've been looking at Lua and L ve for developing simple 2D games. But since Lua is interpreted and I know it can be compiled to some point, but how secure is that to decompiling. Or is there a better way to distribute the game?"} {"_id": 27, "text": "Corona SDK, do I need to pay for it? I'm a single dev making simple mobile games. I was looking at corona sdk for my next project. I don't understand what the difference between the paid version and the free version is. It seems that the whole SDK is free, so what does the paid version give you that the free version doesnt? I've been reading through the site, but I'm not quite getting it. I will need to interface with apple's game center etc.. is that not accessible to me without paying?"} {"_id": 27, "text": "What are the pros and cons of incorporating Lua into a C game? I have a C game programming book and it has a Lua section in it. I've started to read the Lua section, and it sounds interesting, but I can't determine the pros and cons of using Lua in my C game. The only benefit I can currently think of is that you can make some coding updates, via Lua, without having to recompile. Other than that, I can't think of anything. So what are the pros and cons of adding Lua to a C game? Examples would be appreciated."} {"_id": 27, "text": "Why is the button's code not running? My script for a slot machine isn't working. When the button in the Bilboard GUI is clicked, the below dosen't run. I am new to scripting and this is mostly based on wiki stack exchange Dev page info. local player game.Players.LocalPlayer local textLabel script.Parent local toggled false local button script.Parent textLabel.Text \"Click to Play for 5 Cash!\" slot1Combos \"Bar\", \"Seven\", \"Seven\", \"Seven\", \"Cherry\", \"Cherry\", \"Cherry\", \"Cherry\", \"Orange\", \"Orange\", \"Orange\", \"Orange\", \"Orange\", \"Lemon\", \"Lemon\", \"Lemon\", \"Lemon\", \"Lemon\", \"Banana\", \"Banana\", \"Banana\", \"Banana\", \"Banana\" slot2Combos \"Bar\", \"Seven\", \"Cherry\", \"Cherry\", \"Cherry\", \"Orange\", \"Orange\", \"Orange\", \"Orange\", \"Orange\",\"Orange\",\"Lemon\", \"Lemon\", \"Lemon\", \"Lemon\", \"Lemon\", \"Lemon\", \"Banana\", \"Banana\", \"Banana\", \"Banana\", \"Banana\", \"Banana\" slot3Combos \"Bar\", \"Seven\", \"Cherry\", \"Cherry\", \"Cherry\", \"Orange\", \"Orange\", \"Orange\", \"Orange\", \"Orange\",\"Orange\",\"Lemon\", \"Lemon\", \"Lemon\", \"Lemon\", \"Lemon\", \"Lemon\", \"Banana\", \"Banana\", \"Banana\", \"Banana\", \"Banana\", \"Banana\" local function onButtonActivated() if toggled false then toggled true x math.random(1,23) y math.random(1,23) z math.random(1,23) g false player.leaderstats currencyName .Value player.leaderstats currencyName .Value 5 if slot1Combos math.floor(x) \"Bar\" and slot2Combos math.floor(y) \"Bar\" and slot3Combos math.floor(z) \"Bar\" then player.leaderstats currencyName .Value player.leaderstats currencyName .Value 60 textLabel.Text \"You Got 3 Bars. You won 60 cash\" wait(5) textLabel.Text \"Click to Play for 5 Cash!\" elseif slot1Combos math.floor(x) \"Seven\" and slot2Combos math.floor(y) \"Seven\" and slot3Combos math.floor(z) slot2Combos math.floor(y) then player.leaderstats currencyName .Value player.leaderstats currencyName .Value 40 textLabel.Text \"You Got 3 Sevens. You won 40 cash\" wait(5) textLabel.Text \"Click to Play for 5 Cash!\" elseif slot1Combos math.floor(x) slot2Combos math.floor(y) and slot3Combos math.floor(z) slot2Combos math.floor(y) then player.leaderstats currencyName .Value player.leaderstats currencyName .Value 10 textLabel.Text \"You Got 3 of a Kind. You won 10 cash\" wait(5) textLabel.Text \"Click to Play for 5 Cash!\" elseif slot1Combos math.floor(x) \"Cherry\" and slot2Combos math.floor(y) \"Cherry\" and slot3Combos math.floor(z) \"Cherry\" then player.leaderstats currencyName .Value player.leaderstats currencyName .Value 20 textLabel.Text \"You Got 3 Cherries. You won 20 cash\" wait(5) textLabel.Text \"Click to Play for 5 Cash!\" elseif slot1Combos math.floor(x) \"Cherry\" and slot2Combos math.floor(y) \"Cherry\" or slot3Combos math.floor(z) \"Cherry\" and slot1Combos math.floor(x) \"Cherry\" or slot2Combos math.floor(y) \"Cherry\" then player.leaderstats currencyName .Value player.leaderstats currencyName .Value 3 textLabel.Text \"You Got 2 Cherries. You won 3 cash\" wait(5) textLabel.Text \"Click to Play for 5 Cash!\" elseif slot1Combos math.floor(x) \"Cherry\" or slot2Combos math.floor(y) \"Cherry\" or slot3Combos math.floor(y) \"Cherry\" then player.leaderstats currencyName .Value player.leaderstats currencyName .Value 3 textLabel.Text \"You Got 1 Cherry. You won 3 cash\" else textLabel.Text \"Sorry, you didn't win\" wait (5) textLabel.Text \"Click to Play for 5 Cash!\" end end button.Activated Connect(onButtonActivated) end) This is the explorer tree with the script highlighted"} {"_id": 27, "text": "Verb Noun Parsers and Old School Visual Novels Hi I'm working on a simple old school visual novel engine in Lua. Basically I have most of the code set up besides one important feature. The Text Parser. Lets get into how words are generally structured. In the screenshot I input the command \"my wish is for you to die\" How would a human understand this? my noun object wish verb is connective equator similar to for connective object (for all objects of ..) you noun object to connective action similar to do die verb the computer can then parse this and understand it like this (pseudo example) my user you get current label() you \"Lost Coatl\" wish user command user command for all objects of \"Lost Coatl\" do die() end execute user command() What other ways do videogames use text parsers, what would be the simplest way for a newbie coder such as myself?"} {"_id": 27, "text": "How to set speed based on screen size I am making a breakout clone for mobile and was wanting to make the ball speed to be related to the screen size. Larger screen would mean faster speed. Right now I have it set like so dirx math.random( 5,5) (maxx 320) diry math.random(3,7) (maxy 480) My reasoning for this is that 320x480 is iPhone resolution so I figured it would be a good base to start at. For the record, it actually runs pretty well on iPhone setting. Then for the actual movement I just add dir to the appropriate direction. ball.x ball.x dirx ball.y ball.y diry The problem is if I change to a device with a larger screen resolution, the ball is crazy fast and is very jumpy. Is some kind of formula that I can use to multiply to the random that will make the speed appear uniform across devices?"} {"_id": 27, "text": "Determine required camera pitch yaw change based on mouse movement and roll? I'm sure this is going to be a pretty simple answer but I can't quite figure it out on my own. Each frame, I'm getting the mouse's distance from the center of the screen (left up is positive) and using it to change the camera's pitch and yaw. Then, I added camera roll. Now, if the camera is rolled 45 left, moving the mouse left needs to change both the pitch AND yaw. I know I need to use math.sin and math.cos but I can't get it to work quite right. Pitch and yaw are relative to the world, not the camera's view. AddYaw and AddPitch are hypothetical functions that apply world yaw pitch to the camera. So if the camera is rolled 90 degrees left (so right is world up), applying yaw will appear to make the camera pitch \"up\", which is still left according to the world. Due to the functions available to me through the game's API, I can't just apply camera relative pitch yaw, I'm restricted to world relative pitch yaw only. Basically, it boils down to applying some trigonometry to the mouse x y input to \"rotate\" the pitch and yaw values added to the camera. change.x distance mouse moved left right in this frame change.y distance mouse moved up down in this frame Fix me! local yawChange math.sin(rollInRads) change.x math.cos(rollInRads) change.y local pitchChange math.cos(rollInRads) change.y math.sin(rollInRads) change.x Apply pitch yaw changes to the camera Camera AddYaw(yawChange) Camera AddPitch(pitchChange) A few examples of what it needs to return. For clarity, yaw left positive, right negative, pitch up positive, down negative. Situation 1 No roll. Moving the mouse left applies positive yaw to the camera, moving the mouse up applies positive pitch. No conversion needed since camera yaw world yaw, camera pitch world pitch. Situation 2 Camera is rolled 90 degrees left. Now, positive camera yaw (left) is actually negative world pitch (down). Therefore, moving the mouse left needs to apply PITCH, not yaw. And moving the mouse up needs to apply YAW, not pitch. Situation 3 Camera is rolled 45 degrees left. Now, the camera world axes are a bit mixed. Moving the mouse left should apply equal amounts of negative pitch AND positive yaw so the camera's view moves left relative to its own view."} {"_id": 27, "text": "Love2d Failed to load tileset map I'm reading the Love2D Development book, which i think i will stop reading because is outdated and very instable, sometimes i got a lot of troubles. Backing to the question, i made a tileset map with Tiled and saved in .tmx with Base64 ( uncompressed ) then i used Advanced Tiled Loader and used the code from the book This is the main.lua file local loader require (\"Advanced Tiled Loader master Loader\") the path to our .tmx files and sprites loader.path \"map \" local map loader.load(\"tilemap.tmx\") function love.load() love.graphics.setBackgroundColor(255, 153, 0) load the level and bind the variable map loader.path \"map \" local map loader.load(\"tilemap.tmx\") end function love.draw() map draw() end When i tested the game, the result was this http i.imgur.com JM8EYrv.png The result was suposted to be like this http i.imgur.com W26XFjE.png So what it could be?"} {"_id": 27, "text": "How do I get the player's position in Roblox Studio? In Roblox Studio, I have this code in a script file while true do wait(0.01) local PlayersService game GetService(\"Players\") local players PlayersService GetPlayers() for i, player in pairs(players) do print(player.Name) end end This successfully prints the player's name many times per second. However, I would like to know how I can get other properties, such as the player's position. player.Position doesn't work, and I have no idea what options are available because autocomplete is not working when I type player.. What properties are available on player and how do I get the position?"} {"_id": 27, "text": "Is it possible to generate Events and Hooks in Lua for any game without built in support? Does a game have to have built in functions to accept and run lua scripts, or can I design Events and Hooks using Lua on any game I please, akin to the days where C code could be used to hook into the WinAPI using dlls? The reason I ask is, I am trying to create a background application that will perform events and hooks on a particular game that does not currently support lua in game. Brief examples Events An action executed by the PLAYER is detected. For instance, hitting the Q key will normally make my character use an ability, but with my Lua script running in the background, will cause a sound to play on my computer (or something). Hooks An action within the GAME is detected. For instance, the game spawns an enemy every minute. When an enemy spawns, the script will detect this and perform an action, for instance playing a sound locally on the computer. I would like to do both, but I know for games like Garry's Mod, the game already has built in support for running lua scripts. Is there a way to do either events OR hooks using lua similarly to how C C can connect to a game using WinAPI dlls?"} {"_id": 27, "text": "How to connect a GUI button to function? I am developing a new Roblox game where you can setup and control you're own virtual machine using SurfaceGUIs on a modeled screen. I am trying to make a confirmation GUI where if you click YES, then it starts the VM, and if you click NO, then it closes the GUI and doesn't start a VM. But when I click on NO, nothing happens! Here is my code local gui script.Parent.Parent local button script.Parent local function cancel() gui.Visible false end button.Activated Connect(cancel()) Please help! P.S The confirmation frame is in the ScreenGUI, the button is in the frame, and the LocalScript is in the button."} {"_id": 27, "text": "Determine required camera pitch yaw change based on mouse movement and roll? I'm sure this is going to be a pretty simple answer but I can't quite figure it out on my own. Each frame, I'm getting the mouse's distance from the center of the screen (left up is positive) and using it to change the camera's pitch and yaw. Then, I added camera roll. Now, if the camera is rolled 45 left, moving the mouse left needs to change both the pitch AND yaw. I know I need to use math.sin and math.cos but I can't get it to work quite right. Pitch and yaw are relative to the world, not the camera's view. AddYaw and AddPitch are hypothetical functions that apply world yaw pitch to the camera. So if the camera is rolled 90 degrees left (so right is world up), applying yaw will appear to make the camera pitch \"up\", which is still left according to the world. Due to the functions available to me through the game's API, I can't just apply camera relative pitch yaw, I'm restricted to world relative pitch yaw only. Basically, it boils down to applying some trigonometry to the mouse x y input to \"rotate\" the pitch and yaw values added to the camera. change.x distance mouse moved left right in this frame change.y distance mouse moved up down in this frame Fix me! local yawChange math.sin(rollInRads) change.x math.cos(rollInRads) change.y local pitchChange math.cos(rollInRads) change.y math.sin(rollInRads) change.x Apply pitch yaw changes to the camera Camera AddYaw(yawChange) Camera AddPitch(pitchChange) A few examples of what it needs to return. For clarity, yaw left positive, right negative, pitch up positive, down negative. Situation 1 No roll. Moving the mouse left applies positive yaw to the camera, moving the mouse up applies positive pitch. No conversion needed since camera yaw world yaw, camera pitch world pitch. Situation 2 Camera is rolled 90 degrees left. Now, positive camera yaw (left) is actually negative world pitch (down). Therefore, moving the mouse left needs to apply PITCH, not yaw. And moving the mouse up needs to apply YAW, not pitch. Situation 3 Camera is rolled 45 degrees left. Now, the camera world axes are a bit mixed. Moving the mouse left should apply equal amounts of negative pitch AND positive yaw so the camera's view moves left relative to its own view."} {"_id": 27, "text": "Lua Unknown error when typing something in Zerobrane studio IDE What is this weird error that I am getting when I typing something in the Zerobrane studio IDE? It crashes my IDE. But The game project compiles and runs fine. When I turn off \"Autocomplete Identifiers\" from Edit menu, then the error doesn't come up. Also, I searched entire google and facebook for some help or solution but no luck at all."} {"_id": 27, "text": "Pathfinder is making my NPC follow my oldest position only I am trying to make a maze horror game. I used an online template in the Roblox library as my enemy. I used pathfinder as you will see in the code below. It's finding me like it's supposed to, except it only goes for my LAST position. As you can see in the image below, it completely skipped me, went to my LAST position, then started chasing me. I don't know why it only goes for my last position, and not my current position. local PathFindingS game GetService( quot PathfindingService quot ) local humanoid script.Parent WaitForChild( quot Humanoid quot ) local rootPart script.Parent WaitForChild( quot HumanoidRootPart quot ) local Players game GetService( quot Players quot ) game.Workspace.Fruity.Humanoid.WalkSpeed 60 To calculate the path while wait() do for i, player in pairs(game.Players GetPlayers()) do local character game.Workspace WaitForChild(player.Name) local characterPos character.PrimaryPart.Position local path PathFindingS CreatePath() path ComputeAsync(rootPart.Position, characterPos) game.Workspace.Fruity.HumanoidRootPart SetNetworkOwner(nil) local waypoints path GetWaypoints() for i, waypoint in pairs(waypoints) do local part Instance.new( quot Part quot ) part.Shape quot Ball quot part.Material quot Neon quot part.Size Vector3.new(0.6,0.6,0.6) part.Position waypoint.Position Vector3.new(0,2,0) part.Anchored true part.CanCollide false part.Parent game.Workspace humanoid MoveTo(waypoint.Position) humanoid.MoveToFinished Wait() end end end"} {"_id": 27, "text": "NLua How to implement Roblox like function security? Roblox uses Normal Identities, basicly they assign a lua block object to a certain number. They use 2 for Scripts and LocalScripts, which can only use non secured functions, while the command bar can access everything that is LocalUserSecurity and RobloxPlaceSecurity. How can I implement this type of Lua Security into NLua?"} {"_id": 27, "text": "Got unexpected results from perlin noise. Wondering what it is doing? I was just messing around with perlin noise and got this. Wondering if anyone knows what it is or has seen it before. Here is the code(LUA with love2d engine) function love.load() love.window.setMode( 1920, 1080, fullscreen false ) Assuming you called the module perlin.lua newperlin require(\"perlin2\") newperlin is a function that generates Perlin noise objects myperlin newperlin() 333 is seed myperlin newperlin(333) mapHeight 400 mapWidth 400 then, to create noise scale 0.007 map for x 0, mapWidth 1 do map x for y 0, mapHeight 1 do map x y 0 map x y map x y (myperlin noise(x scale, y scale) 1) 2.0 255.0 The following lines change it from a cloud to a weird image smin 0 smax 255 map x y math.floor(( map x y ( 0.5) ) 255 ( 0.5 ( 0.5) ) 0) end end end function love.draw() for x 0, mapWidth 1 do for y 0, mapHeight 1 do love.graphics.setColor(map x y , map x y , map x y , 255) love.graphics.point(x,y) end end end function love.update() end function love.keyreleased(key) if key \"escape\" then love.event.quit() end end and here is perlin.lua"} {"_id": 27, "text": "Lua script for World of Warcraft Get Quest Info I'm looking to make a very simple addon or even a macro where I can enter a quest ID and get the quest completion status. As it is, I know I can use IsQuestFlaggedCompleted to get the quest status, but I wanted to also get the name of the quest so the return in the chat log will show something a little more understandable. For example Enter questDone 43502 instead of just 43502 true as the output, I want it to look like A Change of Seasons Quest Completed. I see a function C TaskQuest.GetQuestInfoByQuestID that's supposed to return the quest's title, but it doesn't seem to work as expected. It always seems to return nil for the quest name..."} {"_id": 27, "text": "How to make the character dash forward in Roblox? In my game I want to make a skill in a tool to dash forward for a specific range and if the character came in contact with a humanoid during the dash, it stops right on contact and stops the other humanoid from moving temporarly too and deal damage I don't know what functions should i do and where to look for them... i figured how to use onActivate and getting the mouse through Equipped Appritiate any help and guidance"} {"_id": 27, "text": "When PlayerRemoving event is fired, for loop does not work properly while I was implementing the Backback save feature in my Roblox Game (using game.Players.PlayerRemoving Connect(), I found that when I used a loop of any form (for, while,etc.), it would not run correctly. Here is a test program which I wrote to observe this issue game.Players.PlayerRemoving Connect(function(player) local testList \"Hello\", \",\", \"world\" for i 1,3,1 do print(testList i ) end end) However, when this code is ran, all I see in the output window is Hello And nothing else. This issue is causing a lot of issues with the rest of the code, can somebody please help? It would be very useful!"} {"_id": 27, "text": "Sprite batching and dealing with isometric depth sorting So I'm using Love2D which uses SDL2 as far as I'm aware and I have a question about texture atlases amp spritebatching. I have an isometric chunk, with 2 layers, terrain and objects (trees, buildings, units). The terrain is not animated and the tiles are 32x16, they fit perfectly even in a 1028x1028 texture atlas. However the object spritebatch layer is a different thing. I have trees, that are animated and each frame uses up to 200x200 space in the atlas. You can see the problem. Now, I think I can fit all of it in a 8192x8192 texture and this is OK for my GPU, which is entry level (GT 720). It gets stored in the VRAM. So I conducted some test and imported a 10k x 10k image, the GPU could not handle it, and it was loaded onto the RAM. What exactly happens here? How much is the performance loss, I'm about to test, but is this going to cause any incompatibility problems? Other than the 300MB RAM usage instead of VRAM. Now, you might state the obvious, \"Why not use 2 or more texture atlases?\". I don't know if I'm doing things wrong, but I want to use sprite batches for the object layer, and the way I'm drawing it is this function update objects() object batch clear() for i 0,chunk width 1,1 do for o 0,chunk height 1,1 do object batch add( tile quads objects chunk i o , (i o) tile width 0.5, (i o) tile height 0.5 tile offset objects chunk i o ) end end object batch flush() end In order to deal with the depth issue that isometric games have, I simply draw furthest to closest. As far as I'm aware, sprite batches can only use 1 texture atlas, and I confirmed that by tests. Of course, there's a draw call that draws the sprite batch. I'm ok with several draw calls (units, buildings, environment in 3 separate batches for example), but I don't see how I will deal with the depth issue if I do go that way. (not OpenGL as I previously stated) Any ideas?"} {"_id": 27, "text": "Unwanted line between chunks in heightmap infinite terrain I can't figure out what is causing the line between my two chunks. They are completely aligned. It must be something to do with the algorithm. I am using lua with the love2d game engine. Here is a pic Here is the code seed 257 local canvas love.graphics.newCanvas() function Interpolate(a, b, x) ft x 3.1415927 f (1 math.cos(ft)) 0.5 return a (1 f) b f end function Noise(x, y) n x y seed n bit.bxor((bit.lshift(n,13)),n) return ( 1.0 ( bit.band((n (n n 15731 789221) 1376312589), 0x7fffffff) 1073741824.0)) end function SmoothedNoise1(x, y) corners ( Noise(x 1, y 1) Noise(x 1, y 1) Noise(x 1, y 1) Noise(x 1, y 1) ) 16 sides ( Noise(x 1, y) Noise(x 1, y) Noise(x, y 1) Noise(x, y 1) ) 8 center Noise(x, y) 4 return corners sides center end function InterpolatedNoise 1(x, y) integer X, fractional X math.modf(x) integer Y, fractional Y math.modf(y) v1 SmoothedNoise1(integer X, integer Y) v2 SmoothedNoise1(integer X 1, integer Y) v3 SmoothedNoise1(integer X, integer Y 1) v4 SmoothedNoise1(integer X 1, integer Y 1) i1 Interpolate(v1 , v2 , fractional X) i2 Interpolate(v3 , v4 , fractional X) return Interpolate(i1 , i2 , fractional Y) end function getExampleMap() mapWidth 400 mapHeight 400 mapMin InterpolatedNoise 1(0, 0) mapMax mapMin map amp 128 freq 32 octaves 6 for x 0, mapWidth 1 do map x for y 0, mapHeight 1 do map x y 0 for i 1, octaves do map x y map x y getNoiseValue(x, y, freq i, amp i) end mapMin math.min(mapMin, map x y ) mapMax math.max(mapMax, map x y ) end end scale the values between 0 and 255 for rendering in grey scale. mapMultiplier 255 (mapMax mapMin) for x 0, mapWidth 1 do for y 0, mapHeight 1 do map x y map x y mapMultiplier end end end function getExampleMap2() mapWidth 400 mapHeight 400 mapMin InterpolatedNoise 1(0, 0) mapMax mapMin map2 amp 128 freq 32 octaves 6 for x 400, (mapWidth 400) do map2 x for y 0, mapHeight 1 do map2 x y 0 for i 1, octaves do map2 x y map2 x y getNoiseValue(x, y, freq i, amp i) end mapMin math.min(mapMin, map2 x y ) mapMax math.max(mapMax, map2 x y ) end end scale the values between 0 and 255 for rendering in grey scale. mapMultiplier 255 (mapMax mapMin) for x 400, (mapWidth 400) do for y 0, mapHeight 1 do map2 x y map2 x y mapMultiplier end end end function getNoiseValue(x, y, freq, amp) return InterpolatedNoise 1(x freq, y freq) amp end function love.load() love.window.setMode( 1920, 1080, fullscreen false ) getExampleMap() getExampleMap2() end function love.draw() for x 0, mapWidth 1 do for y 0, mapHeight 1 do love.graphics.setColor(map x y , map x y , map x y , 255) love.graphics.point(x,y) end end for x 400, (mapWidth 400) do for y 0, mapHeight 1 do love.graphics.setColor(map2 x y , map2 x y , map2 x y , 255) love.graphics.point(x,y) end end end function love.update() end function love.keyreleased(key) if key \"escape\" then love.event.quit() end end If I use seed 345 there is no line."} {"_id": 27, "text": "Game state management (Game, Menu, Titlescreen, etc) Basically, in every single game I've made so far, I always have a variable like \"current state\", which can be \"game\", \"titlescreen\", \"gameoverscreen\", etc. And then on my Update function I have a huge if current state \"game\" game stuf ... else if current state \"titlescreen\" ... However, I don't feel like this is a professional clean way of handling states. Any ideas on how to do this in a better way? Or is this the standard way?"} {"_id": 27, "text": "Love2D how to zoom out map? I've set up a basic map with Tiled, imported it with STI library (https github.com karai17 Simple Tiled Implementation) and everything looks in place. How can i get a zoom out feature now? I can kinda zoom in using scalex and scaley and i tried the same procedure to zoom out. However, if i set i.e. scalex 0.5, scaley 0.5 the map actually scales in size but it only fit 1 4 the screen size, and the remaining 3 4 are just black space."} {"_id": 27, "text": "Verb Noun Parsers and Old School Visual Novels Hi I'm working on a simple old school visual novel engine in Lua. Basically I have most of the code set up besides one important feature. The Text Parser. Lets get into how words are generally structured. In the screenshot I input the command \"my wish is for you to die\" How would a human understand this? my noun object wish verb is connective equator similar to for connective object (for all objects of ..) you noun object to connective action similar to do die verb the computer can then parse this and understand it like this (pseudo example) my user you get current label() you \"Lost Coatl\" wish user command user command for all objects of \"Lost Coatl\" do die() end execute user command() What other ways do videogames use text parsers, what would be the simplest way for a newbie coder such as myself?"} {"_id": 27, "text": "Why can t this boolean stop the sound from playing 60 times a second? The code local dontPlayMoreThanOnceDammit false function Behavior Awake() local sound CraftStudio.FindAsset( quot motorbuson1 quot ) self.mySoundInstance sound CreateInstance() self.mySoundVolume 1.0 self.mySoundInstance SetLoop( true ) self.mySoundInstance SetVolume( 1.0 ) end function Behavior Update() if dontPlayMoreThanOnceDammit false and CraftStudio.Input.WasButtonJustPressed( quot on quot ) then self.mySoundVolume 1.0 self.mySoundInstance Play() dontPlayMoreThanOnceDammit true end if CraftStudio.Input.IsButtonDown( quot off quot ) then self.mySoundInstance Stop() dontPlayMoreThanOnceDammit false end end Error it gives"} {"_id": 27, "text": "Verb Noun Parsers and Old School Visual Novels Hi I'm working on a simple old school visual novel engine in Lua. Basically I have most of the code set up besides one important feature. The Text Parser. Lets get into how words are generally structured. In the screenshot I input the command \"my wish is for you to die\" How would a human understand this? my noun object wish verb is connective equator similar to for connective object (for all objects of ..) you noun object to connective action similar to do die verb the computer can then parse this and understand it like this (pseudo example) my user you get current label() you \"Lost Coatl\" wish user command user command for all objects of \"Lost Coatl\" do die() end execute user command() What other ways do videogames use text parsers, what would be the simplest way for a newbie coder such as myself?"} {"_id": 27, "text": "How to set speed based on screen size I am making a breakout clone for mobile and was wanting to make the ball speed to be related to the screen size. Larger screen would mean faster speed. Right now I have it set like so dirx math.random( 5,5) (maxx 320) diry math.random(3,7) (maxy 480) My reasoning for this is that 320x480 is iPhone resolution so I figured it would be a good base to start at. For the record, it actually runs pretty well on iPhone setting. Then for the actual movement I just add dir to the appropriate direction. ball.x ball.x dirx ball.y ball.y diry The problem is if I change to a device with a larger screen resolution, the ball is crazy fast and is very jumpy. Is some kind of formula that I can use to multiply to the random that will make the speed appear uniform across devices?"} {"_id": 27, "text": "NLua How to implement Roblox like function security? Roblox uses Normal Identities, basicly they assign a lua block object to a certain number. They use 2 for Scripts and LocalScripts, which can only use non secured functions, while the command bar can access everything that is LocalUserSecurity and RobloxPlaceSecurity. How can I implement this type of Lua Security into NLua?"} {"_id": 27, "text": "file write restarts Corona app I am attempting to implement an auto save feature into a mobile game. I have the following code writing to the save file function saveFunc(input) local saveData input local file io.open( \"saveFile.txt\", \"w\" ) for i,val in ipairs(saveTable) do saveData saveData..\" n\"..val end file write( saveData ) io.close( file ) end This writes to the file correctly. The problem is that after the function finishes, the whole app restarts. Watching the output console, it re prints the \"Copyright (C)...\" as if I had Relaunched the app. I know it is this specific function because if I comment out the call for this function the game continues as normal. I also tried commenting out the io.close(file) but the program still restarted. How can I write to a file and not restart the app?"} {"_id": 28, "text": "Mafia kill algorithm I'm making an Omerta clone mafia game and trying to work out a kill algorithm. Just a basic formula to decide how many bullets player A needs to kill player B. The inputs are players rank (out of 10), and a players kill skill (out of 100). The algorithm needs to return how many bullets are needed for that player to win. If you're shooting someone a higher rank, or higher kill skill, it should require more bullets. Anyone ever done anything like this and can offer some tips? Example chart"} {"_id": 28, "text": "algorithm for combining smaller tiles to balance the bigger ones I have a field of tiles basically each tile is a country that has some kind of sovereign. The tiles countries have different weight. For now I use some numerical value but in the future the weight will depend on tile size, produced resources and so on. So I want for those countries to make alliances if their sole weight is much lower or at least lower than a certain threshold than the weight of the neighborhood tile (each sovereign is basically a primitive AI at that stage that is able to make decision to create the alliance). Here is couple of scenarios Here are the examples for bigger maps with possible alliances So my question is is there some kind of algorithm that allows to achieve that or I have to create it myself or use training sets for AI to gain the ability to form alliances?"} {"_id": 28, "text": "Need help with algorithm for generating connected bricks in Pick A Brick clone I want to make a clone of an Amiga 500 game, Pick A Brick, a 2D game where the goal is to clear a table of bricks by matching them up, following certain rules. I am getting nowhere when it comes to the algorithm for generating the layout of the bricks. I have added the rules of the game (as I remember them) below. The player wins the game by clearing all tiles before the time runs out. Tiles are cleared by clicking on a pair of them and if the following is true The tiles must be of the same type (there is only one pair of each type). There is a clear path between them (more on path in the points below). The path from a tile must always start towards an (clear) edge of the screen. The path between the tiles must be u shaped. (edit) NOTE In the video the path is not always the u shaped. I do not recall if the path shown is just a shortcut or not, but regardless, in my version I do not want to allow removing tiles \"from inside out\". I have done some manual testing prototyping using both outside in and inside out approaches, with variations on both. So far, nothing I have come up with has really come close. I kind of dislike asking a question like this since it is so specific, probably not of general interest and may take up more than a little time for anyone interested in helping out. That being said, some people enjoy coming up with algorithms and \"solving stuff\", and the community may learn something from the answer, so, a post it is. (edit) Clarification. The algorithm must provide a solvable solution."} {"_id": 28, "text": "Generate 2D Triangular Mesh from Vertices on a Map Given a map of vertices (x1,y1), (x2,y2), ... (xn,yn) , how can I generate a 2D triangular mesh covering all vertices, and where the area of all triangles completely covers the map? The triangular areas may fully enclose other triangular areas, but no two triangles may intersect."} {"_id": 28, "text": "Split a grid into shapes that can be moved back from 4 directions Basically I have 4 grids Left, Right, Top, Bottom. Player can choose each of them and move all the blocks on that grid to the Middle grid to fulfill it, like tetris from 4 directions 0 0 0 0 0 0 (0 is empty, 1 is generated block) 0 0 1 Bottom gt Mid Right gt Mid Top gt Mid Left gt Mid 0 0 0 0 0 0 0 1 0 1 0 0 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0 1 1 1 1 1 1 1 1 1 gt Win! Generate 1 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 1 1 1 1 another game. 0 0 0 1 0 0 1 0 0 The point here is to make sure there is at least 1 way for player to combine all 4 grids. What I've tried so far is generate the right order first (Left Right Top....), then generate all the blocks 1 by 1. When a block is generated, i perfomn a check with the generated order (move all the blocks in Left to Mid, then Right then Top...) to see if its still working, the code is similar to this (left gt right, top gt right gt botttom gt left, top... it doesn't have to be all 4 directions) Random the right direction order. Generate all possible coordinates from all the directions from the path above. Initialize an empty list to store all chosen coordinates. While(!(Generate enough x x block)) Get one coordinate from all possible coordinates if (Perform a check with the right order and the chosen list) Add it into the chosen list. The problem here is a block can be wrong at this point, but it can become right when another block is generated 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 0 0 0 0 At this point the logic is wrong But if I add 1 more block to the with Top gt Left gt Bottom order. top grid, it'll become right. There is no way to check if the each block is right or wrong without re calculate all the generated blocks logic So i want to ask if there a better way, algorithm to do it."} {"_id": 28, "text": "How should a circuit or power system (like redstone in Minecraft) be implemented I want to implement a power system like the redstone system in minecraft. I have n power sources and m cables. If I disconnect the power source or a cable the circuit should turn off. How do I avoid circles? If each cable with the status \"on\" powers the nearby cables I can create infinite circles where there is no power source involved (see image). Plus site is that it runs in T m I could send power burst through the graph starting at every power source and in each update call I turn every cable off. Problem is it runs in T n m. Is there a best practice? In Minecraft the redstone system was very slow so I think I overlooked something. EDIT The system should work without a distance based decay."} {"_id": 28, "text": "Why can't my A implementation find a path out of an open room? I tried to follow this article with the following example, but in my attempts it always ends up with a dead end. If we take G being 10 in a straight line or 14 in a diagonal, and H the distance in horizontal or vertical to the target point, then we restart this search for every tile that is the nearest one to the target point. I have this result if we take one or the other direction with 54, it ends up with a dead end. For example, if we go up from 40 to 54, then to 60, when we restart the search with G and H, it ends up with \"4\" (second shema) and comes back in a dead end Why does this happen and how can I solve it? I also looked at the wiki, but I did not understand the system with the colors and the code shown."} {"_id": 28, "text": "AI for solving a Match 3 game Is there a known good way to have a \"computer\" opponent play a Match 3 game? It doesn't have to be fancy, or even considered fair. If the AI always takes the best move on the board that would be OK with me. Note that a valid move is one that doesn't make a match. Edit What I am currently doing is a brute force approach. I look at every tile on the board, and see what the best move that tile can do. I add it to a collection and give it a score (based on how many it will match 3 or 4). Once I have traversed the entire board I use the move with the best score. In the event of a tie I pick one. If a 5 match combo is found I short circuit out to that one. 5 is the highest combo you can get) I may not be able to improve it, but it feels like this should have been solved already."} {"_id": 28, "text": "Codify user progress I want to generate a string code for the user that represents his progress in the game (so he can load this state somewhere else). I don't want him to be able to guess the system and thus load a state which he hasn't yet achieved. The following variables are involved A number X between 1 30 representing the highest level he unlocked. For each level lower than X a boolean representing whether he made the level on hard or not. For each secret object he could have found (also roughly 30) another boolean. My idea was to just build a binary number from all these but that's just way too easy for the user to hack. If he beats level 1 and then saves, he will see his code being something like 0x1, while having bet level 10 will be something like 0x200."} {"_id": 28, "text": "How can I detect connected (but logically distinct) bodies of water in a 2D map? I have a 2D hexagonal grid map. Each hex cell has a height value used to determine if it's water or ocean. I'm trying to think of a good way to determine and label bodies of water. Oceans and inland seas are easy (using a flood fill algorithm). But what about bodies of water like the Mediterranean? Bodies of water that are attached to larger ones (where \"seas\" and \"gulfs\" differ only by the size of the opening)? Here's an example of what I'm trying to detect (the blue body of water in the middle of the image, which should be labelled differently from the larger body of ocean on the left, despite being technically connected) Any ideas?"} {"_id": 28, "text": "Algorithm Logic of identifying a circle in Go game I'm trying to create a 2 players Go like game. Unfortunately I can't get the capturing system to act correctly. At the moment the system is half done, however I cannot think of a perfect way for it to recognize a circle correctly. This is the logic that I'm planning at the moment (let say it's currently White's turn) 1.Using the newest placed piece as the starting point, run a flood fill (Up, Down, Left, Right) code to find all the affected nodes Black piece, and place them in a \"suspects list\". 2.Using the suspects list, find any White piece that is near them (Up, Down, Left, Right, UpLeft, UpRight, DownLeft, DownRight). Adds those pieces into a \"circle candidate list\". 3.Run through the circle candidate list and remove any piece that doesn't connect to at least 2 other candidates. Keep doing this until all candidate are connected to at least 2 other candidates or the number of candidates are less than 4 (which won't be possible to make a circle). 4.Using a recursive method checks whether we can make a circle using all the candidates. The last piece must be connected to the first one. 5.If a circle is identified, get all the nodes that are between the candidates, first checks from top to down then left to right. Records all the nodes that were identified in both checks as dead zones. Kill any Black piece inside the dead zone and any Black piece that is place inside there after this will automatically die. Here's where the problem is, I noticed that 3 pieces that are next to each other will still be connected to 2 other piece. Which means the system will still see them as a legitimate candidate even if they aren't part of a circle. And secondly the way I use to check if there is a circle can easily fail if there are more than necessary pieces to make the circle since it could turn the wrong way and then unable to get back to the starting point. I've been struggling with this capturing process for a week now, and tested a number of different ways. All of it will have a problem in certain scenario which resulted in a bug (either they're not capturing piece that should be captured, or capturing piece that should not be captured). So any help are greatly appreciated. Thank you."} {"_id": 28, "text": "Procedural river or road generation for infinite terrain I should say paths, not roads as I'm thinking more medieval like. Also, not looking for realism. The answer I'm looking for will be to fit into the mold I describe rather than realism. I am looking for a method to generate procedural roads rivers in a curvy sort of fashion, but I'm wanting to do so for a infinite terrain type system. Just like how perlin noise generates blobs, I'm wanting to generate random length line segments (possibly infinite length). I'm aware of strategies like the suggested answer found here, however it relies on a specified start and end point to work, I don't have a specified start and end point. I'd like to be able to simply call a function using arbitrary coordinates and have it return whether the specific coordinates are part of the river road. I am not wanting to require terrain to be generated in advance. That includes a heightmap (like used for rainfall simulations or similar). I would also not want to require a start end point. Is there such an algorithm or tweak to a noise algorithm someone might know of to accomplish what I'm trying to explain? The closest I've came to so far is multi ridged fractals, if I'm using the name properly. I'm just taking the absolute value of value noise (assuming it is scaled to 1 to 1) and setting a threshold. My primary issue with this is the lines overlap way too often, are mostly circular, sometimes converge to form large lakes which is neat but undesired, and often times the thickness of the lines vary too much. Here's a picture of what I have so far in 2D, but at a very high frequency to show more detail"} {"_id": 28, "text": "3D pathing finding with flying Does anyone know of a (free or paid) solution that enables 3D path finding? Basically something like CalculateRoute(input geometry, start pos, end pos, variance) I found a good paper on the topic, but I haven't found any solutions via Google or even searching sites like odesk, etc... I know recast detour is great for ground navigation, but I can't find anything that involves flying 3D space. Any suggestions would be great to existing solutions."} {"_id": 28, "text": "How to create a random, warped 2D grid? How do you create a random grid where the lines aren't orthogonal (and cells aren't a perfect square), but are warped? Here's an example of what I mean (Credit screenshot taken from a video by Silvarret about the game Townscaper.) Lines curve. Sometimes many cells come together in a single point. Yet, it still looks like a grid and the cells are clearly visible and roughly equal in size and shape. I have absolutely no clue how to go about something like this. How is this achieved? Is there an algorithm for this? How would you detect the cell over which the mouse hovers?"} {"_id": 28, "text": "Logic behind a bejeweled like game In a prototype I am doing, there is a minigame similar to bejeweled. Using a grid that is a 2d array (int , ) how can I go about know when the user formed a match? I only care about horizontally and vertically. Off the top of my head I was thinking I would just look each direction. Something like int item grid x,y if(grid x 1,y item) int step x int matches 2 while(grid step 1,y item) step matches if(matches gt 2) remove all matching items else if(grid x 1,y item .... else if(grid x,y 1 item) ... else if(grid x,y 1 item) ... It seems like there should be a better way. Is there?"} {"_id": 28, "text": "How would one determine the position of a participant in a racing game? Now, for the record, I'm currently not implementing any racing game whatsoever, but this problem just popped into my mind and now I'm curious. So how would one go about finding out which participant of a race is currently the first one? It can't be something trivial like just sorting by distance to the finish line because that would be highly inaccurate on most courses. I've thought about doing something like separating the route into straight segments, each of which has a direction vector. The game would then check for when someone outruns somebody else by projecting their positions onto that vector and checking which one is ahead. If the position has changed, the game would increment decrement them appropriately. But that does seem a little too complicated. Does anybody know of any established methods or has any experience in implementing some?"} {"_id": 28, "text": "Why is my bullet disappearing after I release the shoot button? I'm making a game using DirectXTK for my university project. When I press space bullet moves forward like I wanted, but when I let go it stops my bullet from moving. How do I keep the bullet moving when space was pressed? void update shooting if (kb.Space) Shoot(true) else Shoot(false) void Render() if (draw) for (int i 0 i lt 10 i ) m projectile i gt Draw(m bullet i , m view, m proj, Colors Red) bool shoot(bool test) shoot test draw true bool isShot false if (!shoot) for (int i 0 i lt 10 i ) m bullet i Matrix CreateRotationY(m ship. 42) m ship else m bullet 0 Matrix CreateTranslation( Vector3 Forward float(1)) Matrix CreateRotationY(0.f) m bullet 0 m bullet Matrix CreateTranslation( Vector3 Forward) return draw"} {"_id": 28, "text": "How to make score points based on time So the idea is simple. a) Players why finish the level faster, should get higher score. b) The levels (1 to N) where every next becomes more difficult should impact the score. So it's kind of mix of quot time to complete quot and quot level number quot . If would know the fastest possible time the user can complete the level, I would do the fallowing a) If player completes the level in fastest time, it gets max score 100. b) If it takes, for example, twice as long I divide by 2 and get 50. c) Then I multiple by the level number assuming that every next level is twice as difficult. Example Player completes level N two times slower than fastest time, so Score 100 2 N 50N But the problem is that I can't really figure out the this fastest time for each level, because my game is a complex randomized 4d maze and I have no idea how fast a pro gamer can complete it to define the max score. And without that I have no idea how to calculate the score. This question is all about quot Can we figure out the score without knowing the fastest time quot Any help appreciated."} {"_id": 28, "text": "What is the simplest method to generate smooth terrain for a 2d game? What is the simplest method to generate smooth terrain for a 2d game like \"Moon Buggy\" or \"Route 960\"? I got an answer at stackoverflow.com about generate an array of random heights and blur them later. Yes, it's quite okay. But it would be better to give some points, and get a smooth curve."} {"_id": 28, "text": "Integrating specular, diffuse reflection and refraction I am implementing an MLT bidirectional path tracer. I have a problem integrating diffuse, specular reflection and refraction. 1) The first problem is diffuse and specular reflection. Diffuse reflection is done by sampling ray in a hemishere. But specular reflection is done by finding the ray that have an angle to the normal equal to the incident ray with the normal. However, an object can have both diffuse and specular reflection. When to use specular reflection or diffuse reflection for a ray? 2) Same as the first question but this time integrating reflection with refraction. I've seen a few research papers and websites online where the scene have specular, diffuse reflection and refraction, but they have no tutorial on how to do this."} {"_id": 28, "text": "Checking whether moving object has reached target position So I have a fast moving object in my game, let's say a bullet. At each iteration of the main loop I update the object's position based on the delta time value dt and draw it at the new position. I also check whether the object's new position is close to a target position. In that case the object will be removed S.... ... .... .... ...... ... .... .... ... ..T.. X The object starts from location S, moving towards target position T. Each dot . represents one ms time. The vertical bars represent a game loop iteration, in which I check whether the object has reached its target destination. At X the object will be removed. Since these checks (ie. game loop iterations) might take place before or after the 100 exact target position (even if only a few pixels off), I perform this check with a distance between a line segment from the last position to the current position, and whether the target position is on that line. This approach works well. There is one issue though Since the check in which I recognize that the target has been reached happens after the real position of the target, the object moves a little bit further than desired. That's becoming more severe when the object is moving very fast. Now my question Is there kind of a \"best practice\" how to deal with this issue? I assume this is a common problem in game development. PS The only solution I could think of is to re position the object to the real target position as soon as the check succeeds. However, that can look a bit like a \"jump\" back, which does not look great."} {"_id": 28, "text": "Algorithm to select all cells inside rooms regions I have a 2d game map consisting of several 'rooms' For example, here is a 2D map grid (Brown cells wall tiles) If I click on a tile (that isn't brown), I would like to obtain an array of all the cells in the region that I clicked. (If the region is bounded by brown tiles, otherwise do nothing) For example, there are two regions in the image above, both colored in grey. If I clicked cell (4,4) I would get a 4x5 array of cells starting at (3,3). Does anyone know a good performance efficient algorithm for this? I need to account for non square rooms ideally."} {"_id": 28, "text": "How can I locate empty space next to polygon regions? Let's say I have the following area in a top down map The circle is the player, the black square is an obstacle, and the grey polygons with red borders are walk able areas that will be used as a navigation mesh for enemies. Obstacles and grey polygons are always convex. The grey regions were defined using an algorithm when the world was generated at runtime. Notice the little white column. I need to figure out where any empty space like this is, if at all, after the algorithm builds the grey regions, so that I can fill the space with another region. Basically what I'm hoping for is an algorithm that can detect empty space next to a polygon."} {"_id": 28, "text": "Object detection in bitmap JavaScript canvas I want to detect clicks on canvas elements which are drawn using paths. So far I have stored element paths in a JavaScript data structure and then check the coordinates of hits which match the element's coordinates. Rendering each element path and checking the hits would be inefficient when there are a lot of elements. I believe there must be an algorithm for this kind of coordinate search, can anyone help me with this?"} {"_id": 28, "text": "How can I create a random \"world\" in a tile engine? I am designing a game that is working on a classic tile engine, but whose world is generated randomly. Are there existing games or algorithms that do this? The procedural generation algorithms I have found are never using a tile system... What would be the best way to generate a whole \"world\" using a tile system? I am not talking about mazes of blocks, but an overall \"world map\" thanks"} {"_id": 28, "text": "Implementation of finding an index in a 1D array for a triangular grid Am using a while loop to find an index within a 1D array, is there an easier, less time consuming and or mathmatical way to find the index? Consider the next grid 4 o 3 o o 2 o o o 1 o o o o 0 o o o o o 0 1 2 3 4 To find an index in the triangular grid within a 1D array I have the next function int size 5 int getindex( int x, int y ) int columnCount size while( y gt 0 ) x columnCount return x The array (The numbers within the parenthesis are the coordinates and to simplify your view, in reality the (x,y) is in its whole the data) pointdata data 15 (0,0), (1,0), (2,0), (3,0), (4,0), (0,1), (1,1), (2,1), (3,1), (0,2), (1,2), (2,2), (0,3), (1,3), (0,4),"} {"_id": 28, "text": "How to track and find entities within radius in realtime game? What is best approach to implement tracking in real time for, say, 1000 npcs? Every frame update simple a square grid (remove or insert into linked list) and every time check in square radius? I tried kd tree but its really bad in real time updates even with 100 entities I can't reach 10 FPS."} {"_id": 28, "text": "How would one determine the length of a path? I have a game that requires each player to move along one specified path. I draw the path using B zier curves. How can I determine the total real (not linear) length of the path and the distance that each player had made? (The distance between the start point and a specified point on the path.) UPDATE The path is represented in a Cartesian plane (2D)."} {"_id": 28, "text": "Procedurally generating dungeons using predefined rooms Most attempts at procedurally generating dungeons I have stumbled upon do space out areas that will be rooms and connect them will corridors and hallways but what about instances where you have a collection of possible rooms in various dimensions and want to generate a dungeon that uses some of these specific rooms without those corridors and connections? To answer this question I found this particular video on the topic of generating levels in Path of Exile ( 5 20 7 20 about the dungeon part I am referring to) which left questions open on how to technically implement the algorithm described. In general I understand the idea but I am struggling to figure out how this would be translated into code (most efficiently) and therefore here are a few questions When he shows how the entire level is sliced up I could not come up with a graph that would allow to represent this structure. My naive approach would be to have the entire level consist of 1x1 rooms and arbitrarily merge nodes in the graph to form rooms of valid dimensions (valid there is a predefined room that can be inserted there later on). What would be a suggested approach to this? Coloring the rooms should be just assigning random distances (in a given interval) to edges of connected nodes and just applying Dijkstra to find the sequence of rooms from start to finish I presume? When he adds branching rooms I noticed that they do not allow another alternative path to the exit (which could be random of course) but how would one implement the branching? Just a recursive traversal with diminishing chances of continuing deeper into the graph? Description of the algorithm in the video Step 1. Place a start and end room arbitrarily into the level (presumably with a given minimum distance to prevent degenerate layouts) Step 2. Slice the entire level into areas that have exactly the sizes of your predefined rooms Step 3. Assign each room a random weighting distance which is depicted with colors in this example Step 4. Find a shortest path to get a nonlinear path from start to end Step 5. You have your basic layout with a single successful path in which you can place random rooms of corresponding sizes that have to be connected with appropriate doors Step 6. Finally, add some branching rooms"} {"_id": 28, "text": "Can you use A to make a unit move nonspecifically? A is typically used to calculate the best way to move towards something, and it's quite flexible when it comes to threats, extra movement costs, and 'refuelling' on the way to something. However, if you designate only threats, perhaps with a main threat first and foremost, can you use it for \"finding somewhere to go\"? What about adding both threats, safety, resources and other such heuristic influencers to determine what a unit does when idle?"} {"_id": 28, "text": "Checkers AI Algorithm I am making an AI for my checkers game and I'm trying to make it as hard as possible. Here is the current criteria for a move on the hardest difficulty 1 Look For A Block This is when a piece is being threatened and another piece can be moved in behind it to protect it. Here is an example Black Moves W W W W W W W W W W W W B B B B B B B B B B B B White Blocks W W W W W W W W W W W W B B B B B B B B B B B B 2 Move pieces out of danger if any piece is being threatened, and a piece cannot block for that piece, then it will attempt to move out of the way. If the piece cannot move out of the way without still being in danger, the computer ignores the piece. 3 If the computer player owns any kings, it will attempt to 'hunt down' enemy pieces on the board, if no moves can be made that won't in danger the king or any other pieces, the computer ignores this rule. 4 Any piece that is owned by the computer that is in column 1 or 6 will attempt to go to a side. When a piece is in column 0 or 7, it is in a very strategic position because it cannot get captured while it is in either of these columns 5 It makes an educated random move, the move will not indanger the piece that is moving or any piece that is on the board. 6 If none of the above are possible it makes a random move. This question is not really specific to any language but if all examples could be in Java that would be great, considering this app is written in android. Does anyone see any room for improvement in this algorithm? Anything that would make it better at playing checkers?"} {"_id": 28, "text": "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. Problem 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. How to calculate a similarity index to use as a threshold? Or how to transform a color to make it, say, less blue ish? Obvious disclaimer I know nothing about color theory, so I don't know if the above concepts even exists! I'm coding in python, but I'm looking for concepts and strategies, so pseudo code is fine (or just the theory). EDIT To clarify a few points Each 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) I'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) For 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. Background 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). EDIT2 TL,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"} {"_id": 28, "text": "How can I create a random \"world\" in a tile engine? I am designing a game that is working on a classic tile engine, but whose world is generated randomly. Are there existing games or algorithms that do this? The procedural generation algorithms I have found are never using a tile system... What would be the best way to generate a whole \"world\" using a tile system? I am not talking about mazes of blocks, but an overall \"world map\" thanks"} {"_id": 28, "text": "Raycast algorithm fails to collide with diagonal walls in specific locations I'm having a problem with my ray cast algorithm in a 2D tile based universe. I feel the situation would be best explained with a picture, so here it is The ray, represented by the blue line, is passing \"through\" the wall to hit its target when the wall passes through a point where the quantized line moves diagonally and the wall is perpendicular to it. The raycast function is as such def raycast(pos, direction, level) dx, dy direction t 0 x, y pos obj None while not obj and t lt 5000 t 1 x dx y dy obj level.get at((round(x),round(y)),True) pass return obj Is there a simple, efficient way to eliminate this kind of edge case?"} {"_id": 28, "text": "What could I use to search tiles in a game I'm creating a tile based game similar to Minesweeper. When a user clicks on a tile and its not a mine or a number space I need to search and expose the adjacent tiles that are empty and stop when it hits a number or the edge of the board. I have it working right now so that it will clear the row of the tile clicked and stop at a numbered tile or the edge of the board. What I have is going to get ugly quickly and I am sure there is a easier way of doing this. Is there a searching algorithm I can use that will find all adjacent tiles to the one the player click only stopping once it hits the edge of the board or hit a numbered tile?"} {"_id": 28, "text": "Pathfinding Search for Path of Specific Length I am creating a roguelike. This question applies to random map generation. First, I generate areas using a BSP algorithm, where I randomly divide the map into areas. Then, I generate a graph of the areas so that I can use search algorithms to generate paths through the map. It is easy to find the shortest path between two areas, but I would like to find a path with a specific number of steps(or path cost). So, my question is What is an algorithm that I can use to find a path that has a specific cost or cost range? An Example of why I think this is useful Say that I randomly choose two areas(start and end for example). These area might be next to each other, they might be on the opposite sides of the map. I want to force the player to travel through a minimum number of areas before reaching the end, let's say 5. I should be able to be like path startArea.findPathMinimumCost(endArea,5) And it will return a path of cost 5, or the shortest path, whichever has the greater cost. Thank you."} {"_id": 28, "text": "How do I produce \"enjoyably\" random, as opposed to pseudo random? I'm making a game which presents a number of different kinds of puzzles in sequence. I choose each puzzle with a pseudorandom number. For each puzzle, there are a number of variations. I choose the variation with another pseudorandom number. And so on. The thing is, while this produces near true randomness, this isn't what the player really wants. The player typically wants what they perceive to be and identify as random, but only if it doesn't tend to repeat puzzles. So, not really random. Just unpredictable. Giving it some thought, I can imagine hacky ways of doing it. For example, temporarily eliminating the most recent N choices from the set of possibilities when selecting a new choice. Or assigning every choice an equal probability, reducing a choice's probability to zero on selection, and then increasing all probabilities slowly with each selection. I assume there's an established way of doing this, but I just don't know the terminology so I can't find it. Anyone know? Or has anyone solved this in a pleasing way?"} {"_id": 28, "text": "Help understanding Simplex Noise Introduction This is less of a \"how to\" on using 2D simplex noise and more of a quest to understand what is happening both in the math and visually. I would rather not copy and paste the code I've found. I really would like to understand it. I have done my homework on the subject and have read through Stefan Gustavson's paper and other sources many times. I feel like I understand about 70 of what my sources are saying, but when I try to manually follow my code loop through to check my understanding I either get hung up on what the variables represent or the math just doesn't add up. I have begun to rename the variables in the code I've found in order to better understand what's going on. If someone with some knowledge of what is actually happening can cross reference the original code (basically Gustavson's code) with my code that would be most excellent. I'm not actually done with renaming the variables though, partly because I'm stuck. My Understanding Let's say I pass pixel (2, 3) into my noise function. At this point I'm working with a normal grid and my goal is to translate this normal grid into a simplex. This simplex is in the form of many triangles since we're working in 2D and supposedly this is better for various reasons. To translate this point from the normal grid to the simplex grid, I must scale the point along the main diagonal line. After doing that, I apparently don't care about the decimals because I then Floor the results putting it back near the closest previous grid point. Now I'm going to align the simplex cell to the normal grid by unskewing the simplex cell. Why I do all this work to get to the simplex cell, then undo it I'm pretty hazy on. Seriously, I think the best way for me to understand this is if someone could whiteboard out in steps what the heck is going on here. Super lost. I didn't walk away empty handed though. I now have what I believe to be the distance between the original grid point I passed in and the simplex point I translated from that original grid point. Woo. I think I'll stop here for now, just because I don't want this to turn into a huge wall of text. I'm pretty sure the rest of this will click once I understand the the beginning part. Weird Math Using the (2, 3) point from earlier, this is what I get by stepping through my own code on paper x 2 y 3 skewfactor 1.830 unskewFactor 1.479 unskewed x 1.520 unskewed y 2.520 simplexCell i 3 simplexCell j 4 x distance0 1.520 y distance0 1.520 i1 0 j1 1 x1 1.309 y1 2.309 x2 2.5207 y2 2.5207 ii no idea why this isn't i2 or something like that. No idea what this is. jj same Not sure if plotting on a graph would work, but I tried and it looks so bad. I used the original parameters (2, 3), simplexCell i amp j, i1, j1, x1, y1, x2, and y2. Doesn't make any sense visually. Not just visually, but mathematically as well. What's with (2, 3) returning negative numbers that go off the chart? What am I doing wrong here?"} {"_id": 28, "text": "Integrating specular, diffuse reflection and refraction I am implementing an MLT bidirectional path tracer. I have a problem integrating diffuse, specular reflection and refraction. 1) The first problem is diffuse and specular reflection. Diffuse reflection is done by sampling ray in a hemishere. But specular reflection is done by finding the ray that have an angle to the normal equal to the incident ray with the normal. However, an object can have both diffuse and specular reflection. When to use specular reflection or diffuse reflection for a ray? 2) Same as the first question but this time integrating reflection with refraction. I've seen a few research papers and websites online where the scene have specular, diffuse reflection and refraction, but they have no tutorial on how to do this."} {"_id": 28, "text": "AI discover algorithm I am curious as to what algorithm logic game AI NPCs would use when discovering information about their environment. There are two scenarios that I could envision. The NPCs are all knowing in regards to elements in the environment, but choose to ignore them unless certain conditions are met (e.g. the guard will not \"find\" his fallen comrade's body unless he is x feet from the body) The NPCs really do discover the environment by scanning it or something... (maybe similar to path finding?) Maybe these are both used in conjunction... Could anyone point me in the right direction towards any preferred methods? I tried googling for this information, but could not find anything that seemed relevant."} {"_id": 28, "text": "Randomly generating the hallways between a network of rooms So here's my base map (It won't necessarily be 5x5, just using this as an example.) It's kinda boring the way it is with all the rooms connected. I want it to be more of a randomly generated labyrinth, where every room is accessible like so I've tried setting the hallways randomly foreach(Room r) r.northWall randomBoolean() r.southWall randomBoolean() r.eastWall randomBoolean() r.westWall randomBoolean() But that almost always ends up with rooms that you're unable to go to, like this And often some rooms have no hallways at all. I tried saying each room must have a minimum of 2 hallways, but it still doesn't fix the problem that sometimes there an inaccessible areas. How should I go about doing this? I'm not too worried about the speed, as long as it's not ridiculously slow (Some levels will have 100 rooms)."} {"_id": 28, "text": "Swept AABB vs Line Segment in 2D I've been trying to get a swept collision detection up and running now for almost a week and I can't for the life of me get it working. There is a answer on this linked here below Swept AABB vs Line Segment 2D I've translated this into Go which will be running the game server and needs this logic func SweepRectLine(rectX, rectY, rectW, rectH, rectHSpeed, rectVSpeed, lineX1, lineY1, lineX2, lineY2 float64) (bool, float64) outVel 2 float64 hitNormal 2 float64 lineNX, lineNY lineX2 lineX1, lineY2 lineY1 lineMinX, lineMaxX, lineMinY, lineMaxY math.Min(lineX1, lineX2), math.Max(lineX1, lineX2), math.Min(lineY1, lineY2), math.Max(lineY1, lineY2) var lineMinX, lineMaxX, lineMinY, lineMaxY float64 if lineNX gt 0 lineMinX, lineMaxX lineX1, lineX2 else lineMinX, lineMaxX lineX2, lineX1 if lineNY gt 0 lineMinY, lineMaxY lineY1, lineY2 else lineMinY, lineMaxY lineY2, lineY1 r (rectW 2) math.Abs(lineNX) (rectH 2) math.Abs(lineNY) radius to Line boxProj (lineX1 rectX) lineNX (lineY1 rectY) lineNY velProj rectHSpeed lineNX rectVSpeed lineNY if velProj lt 0 r 1 hitTime math.Max((boxProj r) velProj, 0) outTime math.Min((boxProj r) velProj, 1) log.Println( quot start quot , hitTime, outTime) rectXMax, rectXMin rectX rectW 2, rectX rectW 2 if rectHSpeed lt 0 left if rectXMax lt lineMinX return false, 0 hitTime math.Max((lineMaxX rectXMin) rectHSpeed, hitTime) outTime math.Min((lineMinX rectXMax) rectHSpeed, outTime) else if rectHSpeed gt 0 right if rectXMin gt lineMaxX return false, 0 hitTime math.Max((lineMinX rectXMax) rectHSpeed, hitTime) outTime math.Min((lineMaxX rectXMin) rectHSpeed, outTime) log.Println( quot right quot , hitTime, outTime) else if lineMinX gt rectXMax lineMaxX lt rectXMin return false, 0 if hitTime gt outTime return false, 0 rectYMax, rectYMin rectY rectH 2, rectY rectH 2 if rectVSpeed lt 0 up if rectYMax lt lineMinY return false, 0 hitTime math.Max((lineMaxY rectYMin) rectVSpeed, hitTime) outTime math.Min((lineMinY rectYMax) rectVSpeed, outTime) else if rectVSpeed gt 0 down if rectYMin gt lineMaxY return false, 0 hitTime math.Max((lineMinY rectYMax) rectVSpeed, hitTime) outTime math.Min((lineMaxY rectYMin) rectVSpeed, outTime) else if lineMinY gt rectYMax lineMaxY lt rectYMin return false, 0 if hitTime gt outTime return false, 0 outVel 0 rectHSpeed hitTime outVel 1 rectVSpeed hitTime return true, hitTime I also put up a Gist with a executable UI here https gist.github.com KidLinus 3f847c46b0e6dc1addac7252d9cb54ab I can't for the life of me figure out what all class variables stand for. I think that some of them are native to Unity but that's just a guess. I've come so far as to figure out that the extent is half of the width height in said direction. What the quot line.n quot stands for is anyones guess, I assume its the direction and have no idea if it's normalized or not. There are also a couple of dead variables just laying there."} {"_id": 28, "text": "How can I divide a 3D mesh into small pieces? I'm considering a manufacturing game. A player should assemble parts of an object in given time. The object will be a 3D mesh model. I want to automatically split the 3D mesh into many small pieces to be provided to players. Each divided piece is needed to have area as similar as possible. And I want to control the number of pieces too within range about 2 6. How can I do this? I know the method to modify a given mesh like adjusting values of vertices, indices. All I need is the algorithm."} {"_id": 28, "text": "Chunked QuadTree creation handling I am new to LOD based techniques so please be lenient with your comments about my naive questions. Preface My aim is a simple terrain renderer (preferred C and OGL) that is to load a height map (say 990 x 990 x 8bit) organized into 33x33 vertex chunks. No on demand paging, just the sampling vertices from the height map data directly into the vertex buffers of the chunks. The rendering should be done via a quadtree whereas the leafs would render a whole chunk (33x33 vertices). After reading Thatcher Ulrich's \"Adaptive Quadtree\" article, as well as chunked LOD and quite many other articles and questions on stack exchange, I still seem to be too stupid to wrap my head around on how to actually proceed. Ulrich rendered leafs as triangle fans directly (in his demo code) which was appropriate at that time (I guess) but my prerequisite is a batch of triangles at once, hence the chunked approach. 1) Using a quad tree (which is easy enough to understand, at least conceptually, and will presumably not lead to patent wars later as with e.g. 'geo mipmaps'), at some point the tree will have to be created. My guess was to load (or generate) a height map first and then PRECALCULATE a quad tree based on this map. Would that be a viable approach? Various articles seem to expect the reader to know this fact a priori, so it is nowhere clearly stated. If pre calculated, then all possible child nodes would be pre allocated in the RAM and walked top down with some distance to node by width LOD criteria that would force the child nodes to take over. 2) If pre allocated, HOW would one render the chunks if lower LOD is required. I.e, the chunk being 32x32 quats 33x33 vertices, an index buffer holding 33x33 indices would render the whole chunk as is. Now, a neighbor node with one lower LOD level is not a leave anymore, and its index buffer would not only need to span the four chunks of it children, it would also have to have an index buffer that indexes every second vertex as well to maintain only a single level of difference (or so my understanding). So I guessed (again) that EVERY node (leaf or not) would have to have (at least) one index buffer, and this index buffer would also have to be created calculated during creation of the entire tree. (Which I would place in the engine's loading section, not anywhere close to the rendering loop). What I really don't understand is, how to do the rendering with the above approach (if it were the way to go, that is)... When nodes way above (in terms of lower LOD level, i.e. coarser resolution) must draw their content, would that mean that the vertex buffers of ALL chunks (in the leaf nodes way down) must be bound? And how would the index buffer of this node address the vertices in all the chunks?... Or, would one have an empty 33x33 patch standing to the ready to collect vertices from various chunks as indexed by this lower level node? (Sounds cheesy already whilst writing this...) I would love to see an answer to this. I would accept a NO CAN DO with quadtrees and alternative suggestions, but a quad tree solution is what I hope for. My own alternative solution (which is a whack job on my mind though) is a kinda 'Infinite Snapshot Quadtree' that starts with a root and creates nodes on the fly, but does only store as many nodes as required to render the visible world. A node however must carry all information to recreate its parent as well as to be able to create a chunck geometry. The subdivision depth with this approach is (virtually) infinite (not considering issues with precision here), but the neighbor linking mayhem is beyond good and evil... Best Regards. Edward"} {"_id": 28, "text": "How can I generate Worms style terrain? I'm working on a Worms styled game and want to generate some terrain procedurally. I've previously done a lot of terrain generation using perlin noise, and this is what I started out using for this game. The only problem with it is that it's too simple and boring, giving me some hills but not the complexity I want. I'd like to have features like caves and hanging mountains and I don't mind floating islands and such. Something like this, but even crazier would be ok I thought of first generating the terrain using classic perlin noise, then just removing parts to create caves and what not, but I'm having trouble guiding the removal of those parts. Are there any alternatives to generating such a terrain?"} {"_id": 28, "text": "Looking for a square to hex pixel coords algorithm So as the headline suggests, I am looking for an algorithm algorithms used for square to hex and hex to square pixel coordinates convertion. I have an image which looks kinda \"interpolated\", meaning some pixels are of one colour, while some have a slightly different shade etc. So pixel colour kinda stores offset or whatever. If you're interested, it's here It has to do with pathfinding, the logical part of map is made of hexmap while the visual part of map is made of squares. Here, size of the square 1 pixel, same hex size is equal to 1 pixel. So basically I will be trying to convert an image with hex pixel coords to image with square pixel coords and vise versa. I'm sorry if this was answered already somewhere, I couldn't find it anywhere. P.S. I reverse engineered the image, so in binary it was only X and Y coords stored plus a third byte value which I took as a greyscale colour (later compared with another image and it matched) Image"} {"_id": 28, "text": "Algorithm to produce 'Lady or Tiger' puzzles? What my problem is There is a puzzle by Raymond Smullyan that works something like this You are in a room with many doors. Behind some of those doors, there are ladies behind the others, there are tigers. Your goal is to pick one of the right doors (the ones with the ladies). On every door, there's a sign that says something like There's a lady behind this door or There is a lion behind door II and VI and so on. Now, you also have some additional information like Only one of the signs says the truth or The sign on a door is true only if there is a lady behind that door and so on. For example, the first puzzle goes like this There are two doors with one sign each. One of the signs is true, the other one is false DOOR I DOOR II There's a lady in In one of those this room and a rooms, there's a a tiger in the lady, in the other other one one there's a tiger Behind which door is a lady? Now, getting to the topic of this question I'm looking for possible ways to auto generate such puzzles. The (far away) goal is to build an algorithm that requires, as parameters, the number of doors (and maybe the difficulty of the resulting puzzle) and creates corresponding texts for the doors. What I have tried so far Not much, as I don't really know where to start. It's easy to create a pattern for the text on the signs and it's also easy to randomly assign true and false statements to those signs, corresponding to the true false rule you use (e.g. Only one sign says the truth). But that's the part where it get's tricky How to create a puzzle that is solvable and has a unique solution? My first idea was to create a random puzzle and use backtracking to search for solutions. But that way, it could take very long until the algorithm has finally found a working set of signs. Also, that way you can't easily determine how difficult a given puzzle is. So, summing it up Do you have any idea, any helpful links, etc.? Any help is appreciated, I don't expect anyone to post a perfect and complete solution for my problem. (Note I originally asked the following question on stackoverflow but was told there that I would be more likely to get an answer here!)"} {"_id": 28, "text": "How can I divide a 3D mesh into small pieces? I'm considering a manufacturing game. A player should assemble parts of an object in given time. The object will be a 3D mesh model. I want to automatically split the 3D mesh into many small pieces to be provided to players. Each divided piece is needed to have area as similar as possible. And I want to control the number of pieces too within range about 2 6. How can I do this? I know the method to modify a given mesh like adjusting values of vertices, indices. All I need is the algorithm."} {"_id": 29, "text": "Rendering mountains around a tile layer When making a 2D Pok mon game, I just faked elevation by putting mountain tiles underneath the land. Now my tiles are 3D models, so I'm using layer properties to define their elevation. What I don't know though is how to generate a 'mountain' around them. The tilemap is kinda' like this Layer 1 Layer 2 Layer 3 .... .... .. . .... .. .... Layer 2 has y offset set to 1, and Layer 3 has y offset set to 2. All they do right now is float in the air. What I'm trying to do is render a mountain around them."} {"_id": 29, "text": "What maps sizes did old 2D RTS games like C C and WarCraft support? I'm looking for the size (in tiles) of the maps for the old 2D games Command and Conquer and Warcraft 1 and 2."} {"_id": 29, "text": "Manually creating cycles in planar, procedural trees? I am creating a procedural map using delaunay triangulation and an MST. I'd like to have a bit more control over my final graph. Like when i was looking looking at the MST I wondered how I can connect specific points of the MST? The following image shows the MST in green and the points I want to connect in red. I was thinking about traversing from a dead end and counting the steps. When it gets within a certain treshhold add a connection. But this might add a connection when there is still a room closer to it. So I have to check for that as well. Same goes for entrance, exit and perhaps other important places on the graph. I want to end up with a random yet fun and playable dungeon. There must be proven concepts about controlling a graph for procedural dungeons and I would love to learn from it."} {"_id": 29, "text": "UNITY How do I use SetTile() with a tile asset scriptable tile? How do I use Tilemap.SetTile() with a tile asset? I want to use it for scriptable tiles in the 2d extras package, such as rule tiles, weighted random tiles, and animated tiles. How would I 1. get inspector reference of this scriptable tile, and then 2. use SetTile() with it? Thanks for your attention."} {"_id": 29, "text": "Is it bad practice to use the entire map image as a tilemap? I made a map in photoshop which I want to use as a map in my game. The question is should I try to cut it up to pieces, or is it bad (performance wise) if I use the way I made it. The picture itself is really specific without any repeatable part so I'm not sure if I can cut it up to smaller parts. I'm kinda new to game developement, so pls forgive me if I asked something stupid here."} {"_id": 29, "text": "Webgl pixel perfect tilemap rendering? The problem described below is a follow up of Seamless tilemap rendering (borderless adjacent images). I'm not sure to fully understand the rendering issue I have, so I'll try to describe as much as I can. I had \"seams\" when rendering a tile map of tiles of 16px by 16px, more precisely I was seeing the following I followed the recommendations describes in this answer. It solved entirely the previous problem. However I now have the following rendering issue As you can see, everything is blurry. I have also tried to do what is recommended in this answer, but it didn't change anything. I got the exact same output. Last note, this is not always visible. When changing the position and scale of the camera, the rendering can end up being correct. This is quite random though. If you are interested in seeing some code, please have a look on the following links This gives you a rough idea of the pipeline executed This is where the texture coordinates are generated This is where the buffers are instantiated This is the fragment shader This is the vertex shader If you think you need more details, please feel free to ask me."} {"_id": 29, "text": "Scrolling background in PyGame with Entity Component System I know this type of question has been asked to death for 'normal' games, however I am struggling with relating a scrolling background to an entity component system (ECS) approach. Generic samples here and here and here. What I struggle with is how to take a fairly procedural view of this problem and abstract it out to an ECS. I'm trying to get a roguelike game up and running in PyGame using Esper. I do have a proof of concept up and running where I generate a large map, however I'm having issues relating how to add a camera here as an entity that other objects would relate to. I'm guessing that I need to refactor my movement code to be based around a camera, and have each separate entity update their relative position as a result. At present, the background is being directly drawn and needs to be abstracted to an Entity in this system, but I was somewhat holding off on that until I figured out the camera. Here is a snippet of the Renderable class that each drawn entity has class Renderable def init (self, image, posx, posy, depth 0) self.image image self.depth depth self.x posx self.y posy self.curr row, self.curr col convert to cells(posx, posy) self.w image.get width() self.h image.get height() self.rect pygame.Rect(self.x,self.y,self.w,self.h) And here are the Movement processor and Render processors class MovementProcessor(esper.Processor) def init (self, minx, maxx, miny, maxy, game map) super(). init () self.minx minx self.maxx maxx self.miny miny self.maxy maxy self.game map game map def process(self) This will iterate over every Entity that has BOTH of these components for ent, (vel, rend) in self.world.get components(Velocity, Renderable) Check if movement is valid newx rend.x int(vel.x TILE SIZE) newy rend.y int(vel.y TILE SIZE) new row, new col convert to cells(newx, newy) if self.game map.data new row new col gt 1 Update the Renderable Component's position by it's Velocity rend.x newx rend.y newy rend.curr row new row rend.curr col new col class RenderProcessor(esper.Processor) def init (self, window, clear color (0, 0, 0)) super(). init () self.window window self.clear color clear color def process(self) Clear the window self.window.fill(self.clear color) This will iterate over every Entity that has this Component, and blit it for ent, rend in self.world.get component(Renderable) self.window.blit(rend.image, (rend.x, rend.y)) Flip the framebuffers pygame.display.flip() Later on in my main loop I iterate over my tilemap (Map class) and simply draw it to a surface, add some debugging overlays, and then assign that surface to the entity associated with the background (bg entity) Blit background directly this needs to be abstracted out for row in range(len(game map.data)) for col in range(len(game map.data 0 )) rect pygame.Rect(col TILE SIZE,row TILE SIZE,TILE SIZE,TILE SIZE) Blit a wall sprite if game map.data row col in 0,1 bg surface.blit(walls game map.data row col ,rect) Blit a floor grass sprite elif game map.data row col in 2,3,4,5 bg surface.blit(floors game map.data row col 2 ,rect) Here is the full listing https pastebin.com N7c4TXXB"} {"_id": 29, "text": "Find all tiles by ID in layer In phaser 2.6.2, is there a way to retrieve all tiles given their ID from a TilemapLayer? The method searchTileIndex on Tilemap works well to retrieve a tile. It has a skip parameter that allows to loop through the tiles, so I've come with the following code var walls var skip 0 do var tile map.searchTileIndex(Tiles.ID WALL, skip, false, wallLayer) if (tile ! null) walls.push(tile) skip while (tile ! null) but it looks very cumbersome to say the least. Am I missing a simpler method, kind of getAllTiles(id) or something?"} {"_id": 29, "text": "Hexagonal tilemap is being distorted So I made a hexagonal tilemap of ocean tiles and then picked a few tiles to be land. When I pick all adjacent tiles to the hexagon it usually works, but for tiles that are on certain columns it does not. Also, on these columns the tops and bottoms of tiles are missing. It's hard to explain but here's a screenshot that should clear it up As you can see, on every other column the top and bottom of hexagons are missing, when all adjacent tiles are filled in to the centre tile it works fine for those columns without a bottom and top on hex, but when it's on the other column one of the adjacent tiles is displaced. Any suggestions? Code baseLayer.setCell((int)islands currentTile .x , (int)islands currentTile .y, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y 1, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y, landCell) baseLayer.setCell((int)islands currentTile .x , (int)islands currentTile .y 1, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y, landCell) baseLayer.setCell((int)islands currentTile .x , (int)islands currentTile .y 1, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y 1, landCell)"} {"_id": 29, "text": "How can I generate a TileSet from an existing image of a level? Let say I have this level from Zelda ALTTP. I know that each tiles are 16x16. How can I generate a tileset and map from part of the original image? (Image source)"} {"_id": 29, "text": "Best practice for map coordinate system Are there any conventions and or best known methods around coordinate systems in game maps? Is the origin usually positioned in the center of the map? Or does it live in a corner and the map is built in a single octant of the 3D space?"} {"_id": 29, "text": "Find connected hex of same color I'm using Lua. I have a hex map. It is randomly generated into an table. hexmap y x .color \"red\" I wish to find each \"group\" of hex's. i.e. all hex's of the same color that connect to each other will belong to one group. As an example, in the following image The result should be 1 blue group (all hex's connect) 3 green groups 1 black group Any suggestions? Thank you."} {"_id": 29, "text": "Divide a tile map into multiple images So let's say I have a tilemap 5 x 5, which equals 25 tiles. How can I divide my tilemap into 25 different images? I'm using tiled, but I don't know if it is possible to do it on there or if I need to use one other program. Of course, my tilemap is bigger than 5 x 5, so it's why I'm asking because it would consume a lot of my time. Thanks."} {"_id": 29, "text": "Tilemap Object Placement I am looking for a way to select tiles within a bounding box for object placement within a scene world, similar to Roller Coaster Tycoon and other simulation games. (source tumblr.com) In the above screenshot of Theme Parkitect you can see that a 4x4 grid is used as the footprint for the object being placed. Given the bounding box and location of the mouse, how can I suitably determine the neighbouring tiles which fall into the bounding box? I have implemented a graph like structure of tiles, corners and edges by following Amit's fantastic articles on Red Blob Games. As of such, I have a graph of all tiles and their neighbours as well as associated tile edges and corners. These tiles are laid out diagonally against the world axis so simply selecting all tiles within a rectangular region isn't as simple (or maybe it is?) as i'd expected. This layout can be changed if necessary however. The main source of information used to steer my implementation has been from Amit's Thoughts on Grids and the graph structure implemented in his article about Procedural Map Generation As a bonus, I would like to implement a way to rotate the object being placed such that a footprint of 1x5 could be rotated to instead be 5x1. I would imagine that once the basics of multiple tile picking has been implemented this should be reasonably simple. Unfortunately, Amit's articles don't seem to cover this topic and the approaches I have found and tried so far haven't quite yielded the correct results. Any help that fits in with the graph like structure for connected tiles, edges and corners would be greatly appreciated. I have tried to implement the approach outlined in Raytracing on a Grid with a mixture of both Broad Phase collision and A Path Finding but neither of these two approaches cover selection of multiple surrounding tiles. I am not concerned with the viability of tiles for placing objects at this point (i.e. sloped edges of tiles or obstructions from other objects). The ideal solution for now would simply be to find the tiles included within the bounds. My initial forays into this have resulted in incorrect results whereby the bounding rect doesn't include all neighbouring tiles (sometimes missing entire rows columns) or returning neighbours outside of the bounds. I was pretty sure that I was close to a winning implementation but my vector math isn't strong enough to validate my findings."} {"_id": 29, "text": "Store metadata for tile in Tiled Map Editor In my tilemap based game, I need to associate lights with light switches, buttons with doors etc. I am using the Tiled map editor (mapeditor.org), but I have yet to find a way to store these associaltion. My idea is to store a number with each tile, so I can have groups of tiles that interact with each other. Is there a way to store custom data with each tile in the Tiled map editor? Just to be clear I don't want to store custom data with each tile type, but with individual instances of one tile type."} {"_id": 29, "text": "Is it possible to make a TileMap that adjust it self to multiple screens? I need to build a tile map that is supposed to fit nicely in several screen Sizes. However, Tiled the tile map editor I use allows only to produce absolute fixed size tile maps. Is there an easy way to make adaptable tile maps or should I build one for each screen size?"} {"_id": 29, "text": "Top down tile based game render order I'm making a simple top down (like this) tile based game (using JavaScript, for reference) I use Tiled for making maps. I have sprites that are more than one tile high, and so whenever they are in front or behind of some objects more than one tile high tiles will be displayed in front of the player. I am looking for a way to give certain tiles 'height' such that only characters of that height could appear in front of those tiles. Here is a screenshot showing my problem (the sprite is doge because it was the first image I found) The same tiles don't always equate to the same height, so I can't give tiles set height. I've thought of one way to give tiles height, and that is to have a (hidden) layer that describes the height level certain tiles are at. However, that solution would be slow and painful to implement. I'm wondering if there's a better way to do it. A few other potential ideas I've had Have a tile layer for each height, hackily guess the height of a tile at runtime based on tiles below (would be buggy) but I think that there would surely be a better way to do it."} {"_id": 29, "text": "Hexagonal tilemap is being distorted So I made a hexagonal tilemap of ocean tiles and then picked a few tiles to be land. When I pick all adjacent tiles to the hexagon it usually works, but for tiles that are on certain columns it does not. Also, on these columns the tops and bottoms of tiles are missing. It's hard to explain but here's a screenshot that should clear it up As you can see, on every other column the top and bottom of hexagons are missing, when all adjacent tiles are filled in to the centre tile it works fine for those columns without a bottom and top on hex, but when it's on the other column one of the adjacent tiles is displaced. Any suggestions? Code baseLayer.setCell((int)islands currentTile .x , (int)islands currentTile .y, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y 1, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y, landCell) baseLayer.setCell((int)islands currentTile .x , (int)islands currentTile .y 1, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y, landCell) baseLayer.setCell((int)islands currentTile .x , (int)islands currentTile .y 1, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y 1, landCell)"} {"_id": 29, "text": "How to handle tiles on top of players I am creating an 2d bird view tile game using the pixijs render framework. Like pokemon or oldtime zelda. In those games you sometimes walk behind buildings where the tile would be drawn on top of the player. I am using an multidimensional array for each tile properties. Where you can set ground level images and level on top of ground level images. The 'z index' can be changed. Should I create an new property to flag it as an tile that can be on top of the player? Where all those tiles with that property are drawn on top of the player. But there is an possibility that you can climb walk on the building and the player should than be drawn on top of the tiles. You should take the following into consideration the game is an multiplayer game. This could be an conflict if all the players characters (the player,npc, cpu) are one layer and the tiles that can be drawn on top of the player are one layer. Because for example one player is walking on top of the building and one is behind the building. You cant change the z index of the player one lower. Because the player behind the building wil look like he is on top of it because the player is drawn on top of it by the changed z index. you can be drawn on top of the tile level (like walking om top of the building or mountain) tiles can change (a building that is going to be destroyed for example) thus are not fixed So how can I handle tiles on top of a player which can be also beneath one player but not the other?"} {"_id": 29, "text": "Animal Crossing like Map Data Structure I've been looking closely at how Animal Crossing (for GameCube) creates town maps, and as far as I can tell, it's something like this The town is made up of a 5x6 grid of acres. Each acre is 16x16 \"tiles\" in size. That's the easier part. As for the actual map generation, it seems to use what I'll call \"acre templates.\" That is, the acres seem to be selected somewhat randomly from a predefined list, with predefined layouts. So there are, for example 2 different layouts of what an acre containing the Museum will look like. Or if an acre has a river running through it, top to bottom, there might be 3 4 different templates of how the river flows through that acre, with optional ponds nearby, etc. The question is... What is a good suggestion or method for how to organize the data structure to handle all of this? Another thing to keep in mind is that there's a \"second layer\" of objects on top of the basic terrain info, such as trees or rocks or inventory objects dropped buried on in the ground. How would I store that information in relation to the acre templates?"} {"_id": 29, "text": "Tilemap layer scaling and Camera issue in Phaser I'm working with the Phaser framework and I'm struggling with a camera rendering issue when scaling a tilemap layer to simulate a zoom feature in my project. The camera size is set to 1024x768px.(Same as the stage size) I then create a tilemap and a tilemap layer that is 3072x2304px. Create the tilemap and the tilelayer this.map this.add.tilemap() this.map.addTilesetImage('tiles') this.layer1 this.map.create('layer', 96, 72, 32, 32) this.layer1.resizeWorld() Code to zoom this.layerScaleGroup this.add.group() this.layerScaleGroup.add(this.layer1) this.layerScaleGroup.add(this.marker) this.layerScale 1 this.inputScale 1 In the update function if(this.input.keyboard.isDown(Phaser.Keyboard.Q)) this.layerScale .2 this.inputScale .2 if(this.input.keyboard.isDown(Phaser.Keyboard.A)) this.layerScale .2 this.inputScale .2 this.layerScale Phaser.Math.clamp(this.layerScale, .33, 1) this.inputScale Phaser.Math.clamp(this.inputScale, 1, 3) this.layerScaleGroup.scale.set(this.layerScale) this.input.scale.set(this.inputScale) When completely zoomed out I need the tilemap layer to be shown in the camera, but instead it seems like the camera or a camera follows the scale of the tilemap layer, even though the original camera is still 1024x768. Here is a video showing the issue. https youtu.be e2mRfigq98I When you are zoomed out you can still draw a tile onto the tilemap, but it is not rendered."} {"_id": 29, "text": "Hexagonal tilemap is being distorted So I made a hexagonal tilemap of ocean tiles and then picked a few tiles to be land. When I pick all adjacent tiles to the hexagon it usually works, but for tiles that are on certain columns it does not. Also, on these columns the tops and bottoms of tiles are missing. It's hard to explain but here's a screenshot that should clear it up As you can see, on every other column the top and bottom of hexagons are missing, when all adjacent tiles are filled in to the centre tile it works fine for those columns without a bottom and top on hex, but when it's on the other column one of the adjacent tiles is displaced. Any suggestions? Code baseLayer.setCell((int)islands currentTile .x , (int)islands currentTile .y, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y 1, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y, landCell) baseLayer.setCell((int)islands currentTile .x , (int)islands currentTile .y 1, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y, landCell) baseLayer.setCell((int)islands currentTile .x , (int)islands currentTile .y 1, landCell) baseLayer.setCell((int)islands currentTile .x 1, (int)islands currentTile .y 1, landCell)"} {"_id": 29, "text": "Touch Gesture Map Movement I really dig the way that the map is moved in Clash of Clans (https itunes.apple.com ca app clash of clans id529479190?mt 8)... I can recognize the pinch and finger movement needed for the zooming and the swiping around the map, what I'm looking for is a tutorial in any language that reveals how to test for the map going out of bounds when moved or scaled. My google fu has failed so far on this one, any hints? Right now I can perform the scale operations and the movement operations, but I can't figure out how to stop the map from going out of bounds when pinched or scaled. My code is a crazy mess and makes me think I'm missing the fundamental logic of how this is done. (I am using Starling with AIR, but a tutorial in any language if you have a link). Update this is what I'm basing what I have currently so far https github.com PrimaryFeather Starling Framework blob master samples demo src utils TouchSheet.as"} {"_id": 29, "text": "Godot How to get mouse button input for a Tilemap for Cellular Automata Conway's Game of Life I have been working with a tilemap for the implementation of a cellular automata game. My current method for getting mouse button input is using an Area2D as a child of the Tilemap and detecting mouse button input like that. I have done this and have since been wondering if there is something built in that I can use for this. I have looked into it and cannot find anything better. Is there something built in to Node2Ds or Canvas Items that I can use."} {"_id": 29, "text": "Cocos2dx v3 Problem with moving Sprite on tilemap after it was scrolled up I have a problem I can't solve so far. I have a scene with tile map on it. And there is a Sprite spawnpoint on map. This Sprite should do MoveTo() action to the point where TouchEnded(). It all works perfectly in the borders of the screen, but after I scroll my map up and do touch again my Sprite stuck in the max Y point of the screen. (Let's say there is max 480px of screen's Y, but 850px of tile map) Please help!"} {"_id": 29, "text": "Segmentation Fault using Allegro Tiled, function al open map() I have consistently segfaulted trying to load a TMX file into a map. int main(int argc, char argv ) ALLEGRO DISPLAY display NULL ALLEGRO EVENT QUEUE event queue NULL ALLEGRO TIMER timer NULL ALLEGRO KEYBOARD STATE keyboard state ALLEGRO MAP map al open map(\"data maps\", \"TestMap.tmx\") ... Active debugger config GDB CDB debugger Default Building to ensure sources are up to date Selecting target Debug Adding source dir home X Desktop Programming C AllegroRoboticsTest Adding source dir home X Desktop Programming C AllegroRoboticsTest Adding file home X Desktop Programming C AllegroRoboticsTest bin Debug AllegroRoboticsTest Changing directory to home X Desktop Programming C AllegroRoboticsTest . Set variable LD LIBRARY PATH . usr local lib opt opencascade lib Starting debugger usr bin gdb nx fullname quiet args home X Desktop Programming C AllegroRoboticsTest bin Debug AllegroRoboticsTest done Setting breakpoints Debugger name and version GNU gdb (GDB) 8.1 Program received signal SIGSEGV, Segmentation fault. In al get standard path () ( usr lib liballegro.so.5.2) 2 0x00005555555563ba in main (argc 1, argv 0x7fffffffe3a8) at home X Desktop Programming C AllegroRoboticsTest main.c 45 At first I thought, maybe I just didn't build the library right, so I rebuilt it 2 more times, once as a static and another as a shared library. The interesting thing is that it builds just fine when using the cmake files that came in the example. I cannot recreate it though. This is the callback after I moved the open map command into it's usual place, directly from the example that comes with allegro tiled. If MAP FOLDER is relative to the working directory and not the running executable, then add a call to al find resources as(RELATIVE TO CWD) before calling al open map() . al find resources as(RELATIVE TO CWD) map al open map(\"data maps\", \"TestMap.tmx\") int map total width al get map width(map) al get tile width(map) int map total height al get map height(map) al get tile height(map) Draw the map al clear to color(al map rgb(0, 0, 0)) al draw map region(map, map x, map y, screen width, screen height, 0, 0, 0) al flip display() ... Setting breakpoints Debugger name and version GNU gdb (GDB) 8.1 Child process PID 25749 In strtoll l internal () ( usr lib libc.so.6) 3 0x0000555555556615 in main (argc 1, argv 0x7fffffffe3a8) at home X Desktop Programming C AllegroRoboticsTest main.c 114"} {"_id": 29, "text": "Cocos2dx v3 Problem with moving Sprite on tilemap after it was scrolled up I have a problem I can't solve so far. I have a scene with tile map on it. And there is a Sprite spawnpoint on map. This Sprite should do MoveTo() action to the point where TouchEnded(). It all works perfectly in the borders of the screen, but after I scroll my map up and do touch again my Sprite stuck in the max Y point of the screen. (Let's say there is max 480px of screen's Y, but 850px of tile map) Please help!"} {"_id": 29, "text": "How to implement different shapes for an area of affect spell? Let W wizard Let 0 Cast range of spell, or AOE Here is the problem I have a 2D tile map of squares. Let's say I want to have a wizard cast a spell that surrounds his body equally. For this, it would be as simple as using a flood fill or Dijkstra's algorithm, and it would look like this 0 00000 000W000 00000 0 No problem! However, how will I implement a spell, that, for whatever reason, looks like a plus sign? 0 0 000W000 0 0 Or the spell goes longer in the direction the wizard is facing? 00000 00000 0W0 000 Or two different locations? 00 W 00 Or, even more awkward, its a ranged splash spell where the player can choose where they want to cast it? W 0 00 One way would be to have a list of all the locations relative to the wizard beforehand, and add them to the wizards location later. (E.g, for the affect to be 2 tiles north of the wizard, it would store (x 0, y 2), and later add them to the wizard's position, which could be at x 30, y 19, so the affect would be at x 30, y 21.) A limitation to this, unfortunately, is that it doesn't take into account where the wizard is facing, and it feels inelegant to manually typing in all the locations that the AOE will affect. Bottom line How should I approach this problem and create a good, easily adjustable AOE system for a tile based map, that takes into account different AOE shapes and cast positions?"} {"_id": 29, "text": "Divide a tile map into multiple images So let's say I have a tilemap 5 x 5, which equals 25 tiles. How can I divide my tilemap into 25 different images? I'm using tiled, but I don't know if it is possible to do it on there or if I need to use one other program. Of course, my tilemap is bigger than 5 x 5, so it's why I'm asking because it would consume a lot of my time. Thanks."} {"_id": 29, "text": "openTTD tileset atlas I'm trying to create an isometric game and would like to use some tiles from Open Transport Tycoon Deluxe newGRF library link The atlas I'm used to work with are basically a big image that can be splitted in 64x32 tiles, so I can use any Atlas import tool or just easily extract the tiles with a loop. However, OpenTTD uses atlas that I don't understand. The files look something like this, where each tile has a numer and starts at positions that are not evenly distributed. I assume it might exist some file with metadata that contains the locations and sizes of each tile, in order to be extracted and used. Has anybody experience with this type of Atlas? How can I extract the tiles so I can use them? Thanks"} {"_id": 29, "text": "Torque2D, Class vs Datablock I'm scripting my first game with Torque2D and have not fully understood the difference between \"Class\" and Datablock. To me it seems like Datablock is similar to a struct in C C or a Record in Pascal. If I create Datablocks with keyword new, are they instantiated in the same way as a \"Class\"? I have a large TileMap and need to attach some information to each Tile. I was thinking to use a Datablock, as a struct, to attach this information to the tile's CustomData property. The two questions are What is a Datablock and should I use a Datablock or a \"Class\" for this tile information?"} {"_id": 29, "text": "How to draw a character behind and in front of a building? (isometric map) how is it possible to draw the player behind and in front of some building in an isometric map should I slice them, replace the number in the map (one number for a tile usually) by an array of number (each being a piece of a bigger tile), and somehow add a Z order related to each small number (the pieces of building), something like this? replace var map 1,0,1 , 0,1,1 , 0,0,1 , 0,0,1 by var map \"2 zOrder 1\",\"3 zOrder 1\" ,0,1 , 1,1,1 , 1,0,1 , 0,0,1"} {"_id": 29, "text": "Tile tilemapping render error I'm having rendering issues in Tiled with a border tile I'm applying to shapes. In Tiled In game I'm using Tile Flipping to reduce work. I thought this may be the issue, so I tested out a few tiles by themselves Tiled In game They render as expected What may be the cause of this? My game engine is Melon JS"} {"_id": 29, "text": "Building placement in tilemaps (pattern matching) I'm building a small RTS and in my code I've given my buildings a pattern, much like you would pieces in tetris, i.e. I want to place irregularly shaped buildings on a map without overlaps. The map could be 100x100 and my structure that I'm placing could be as follows OXO XXX XXX I'm currently bruteforce checking each building cell individually against cells in a map. Is there an easier nicer way to check a tile map for a matching pattern?"} {"_id": 29, "text": "How to use multiple tilesets in a map? I'm currently looking at this phaser example http phaser.io examples v2 tilemaps blank tilemap Here, the author creates a simple tilemap editor. In line 33 he adds a preloaded image as tileset. The problem is the author adds only one tileset but I'd like to add multiple tilesets to the map (via map.addTilesetImage), switch between them and paint with the \"current one\". I've read multiple times on the internet that it is possible to add and use many tilesets on a single map, but so far I haven't found any examples of that and the phaser docs also don't give that away."} {"_id": 29, "text": "How to use 16 32 square pixel tiles in tilemap on arbitrarily sized canvas in Phaser My question is about Phaser and Tiled but I'm not quite sure how to ask it so please bear with me. Do I need to make the size of the canvas or area on which I want to display my tilemap a multiple of the size in pixels of an individual tile in my tileset? Or is there a way of scaling a tilemap to fit a particular screen area? I'm not really sure how to explain my question better so I will give an example of what I'm talking about. Because I'm using only freely available game art (such as that found on opengameart.org), most tilesets come with tiles sized 16x16 or 32x32 pixels. Does the game area I want to display the tiles in have to be a multiple of 16 or 32, respectively? Or put another way, if I wanted to have a grid of 32x32 tiles fit inside of a canvas of say, 900x900 dimension, must I have to draw design my tiles to be of size 28x 28 pixels? And if I want to use a tileset with tiles of size 32x32 must I make the canvas a multiple of 32, like 1024x1024 for example? Thanks for bearing with me and for any help."} {"_id": 29, "text": "Did old games like Golden Axe or Street or Rage use tilemaps? I am wondering if old games like Golden Axe (genesis) or street of Rage (genesis) used tilemaps or background bitmaps for the levels. I could not find any resource that explain this and searching around in the web I can find background images, but I never found any tilemap for the levels. This off course, does not answer the question, but it looks like they used background bitmaps for the entire level. But I am not sure if it was practical for those old consoles to store such \"big\" images and render those. Does anyone knows a bit of programming on those old systems and knows how those \"perspective\" levels were built?"} {"_id": 29, "text": "Did old games like Golden Axe or Street or Rage use tilemaps? I am wondering if old games like Golden Axe (genesis) or street of Rage (genesis) used tilemaps or background bitmaps for the levels. I could not find any resource that explain this and searching around in the web I can find background images, but I never found any tilemap for the levels. This off course, does not answer the question, but it looks like they used background bitmaps for the entire level. But I am not sure if it was practical for those old consoles to store such \"big\" images and render those. Does anyone knows a bit of programming on those old systems and knows how those \"perspective\" levels were built?"} {"_id": 29, "text": "How do I convert an image into a tile map? I am working on a game in Pygame Python, and I'd like to turn an image into a map. The idea is simple Pixels in the image are colored by tile type. When the program loads the image, I want the color (e.g. ff13ae) to be matched to a certain grass tile, and the color (e.g. ff13bd) to a different tile. I know that I may have to convert from hexcodes to RGB, but that is trivial. I just want to know the way I to go about loading an image file, mainly because all my other games don't do anything of this sort."} {"_id": 29, "text": "Manually creating cycles in planar, procedural trees? I am creating a procedural map using delaunay triangulation and an MST. I'd like to have a bit more control over my final graph. Like when i was looking looking at the MST I wondered how I can connect specific points of the MST? The following image shows the MST in green and the points I want to connect in red. I was thinking about traversing from a dead end and counting the steps. When it gets within a certain treshhold add a connection. But this might add a connection when there is still a room closer to it. So I have to check for that as well. Same goes for entrance, exit and perhaps other important places on the graph. I want to end up with a random yet fun and playable dungeon. There must be proven concepts about controlling a graph for procedural dungeons and I would love to learn from it."} {"_id": 29, "text": "Segmentation Fault using Allegro Tiled, function al open map() I have consistently segfaulted trying to load a TMX file into a map. int main(int argc, char argv ) ALLEGRO DISPLAY display NULL ALLEGRO EVENT QUEUE event queue NULL ALLEGRO TIMER timer NULL ALLEGRO KEYBOARD STATE keyboard state ALLEGRO MAP map al open map(\"data maps\", \"TestMap.tmx\") ... Active debugger config GDB CDB debugger Default Building to ensure sources are up to date Selecting target Debug Adding source dir home X Desktop Programming C AllegroRoboticsTest Adding source dir home X Desktop Programming C AllegroRoboticsTest Adding file home X Desktop Programming C AllegroRoboticsTest bin Debug AllegroRoboticsTest Changing directory to home X Desktop Programming C AllegroRoboticsTest . Set variable LD LIBRARY PATH . usr local lib opt opencascade lib Starting debugger usr bin gdb nx fullname quiet args home X Desktop Programming C AllegroRoboticsTest bin Debug AllegroRoboticsTest done Setting breakpoints Debugger name and version GNU gdb (GDB) 8.1 Program received signal SIGSEGV, Segmentation fault. In al get standard path () ( usr lib liballegro.so.5.2) 2 0x00005555555563ba in main (argc 1, argv 0x7fffffffe3a8) at home X Desktop Programming C AllegroRoboticsTest main.c 45 At first I thought, maybe I just didn't build the library right, so I rebuilt it 2 more times, once as a static and another as a shared library. The interesting thing is that it builds just fine when using the cmake files that came in the example. I cannot recreate it though. This is the callback after I moved the open map command into it's usual place, directly from the example that comes with allegro tiled. If MAP FOLDER is relative to the working directory and not the running executable, then add a call to al find resources as(RELATIVE TO CWD) before calling al open map() . al find resources as(RELATIVE TO CWD) map al open map(\"data maps\", \"TestMap.tmx\") int map total width al get map width(map) al get tile width(map) int map total height al get map height(map) al get tile height(map) Draw the map al clear to color(al map rgb(0, 0, 0)) al draw map region(map, map x, map y, screen width, screen height, 0, 0, 0) al flip display() ... Setting breakpoints Debugger name and version GNU gdb (GDB) 8.1 Child process PID 25749 In strtoll l internal () ( usr lib libc.so.6) 3 0x0000555555556615 in main (argc 1, argv 0x7fffffffe3a8) at home X Desktop Programming C AllegroRoboticsTest main.c 114"} {"_id": 29, "text": "Generating \"tile map\" by stamping a full map I'm building a game using Tiled tilemap editor. I was originally creating tilesets to stamp around and create my map in Tiled. Id prefer to create the base map in a Adobe Illustrator and stamp in the whole map as the level. Then stamp in trees or whatever on more layers as needed. What are the implications on performance doing it this way vs creating the tilemaps and stamping them in tiled? Example Tile Stamped Map"} {"_id": 29, "text": "Touch Gesture Map Movement I really dig the way that the map is moved in Clash of Clans (https itunes.apple.com ca app clash of clans id529479190?mt 8)... I can recognize the pinch and finger movement needed for the zooming and the swiping around the map, what I'm looking for is a tutorial in any language that reveals how to test for the map going out of bounds when moved or scaled. My google fu has failed so far on this one, any hints? Right now I can perform the scale operations and the movement operations, but I can't figure out how to stop the map from going out of bounds when pinched or scaled. My code is a crazy mess and makes me think I'm missing the fundamental logic of how this is done. (I am using Starling with AIR, but a tutorial in any language if you have a link). Update this is what I'm basing what I have currently so far https github.com PrimaryFeather Starling Framework blob master samples demo src utils TouchSheet.as"} {"_id": 29, "text": "What maps sizes did old 2D RTS games like C C and WarCraft support? I'm looking for the size (in tiles) of the maps for the old 2D games Command and Conquer and Warcraft 1 and 2."} {"_id": 29, "text": "How do you use these kind of rpg ground tileset ? Searching about some tilesets for a little RPG game, I've often found these kind of tileset Their structure are special, there is two upper tile and 4 others for the same material. I understand that, like that, you have all what you need to create more various shapes than simple rectangles of different sizes. But I don't get how they are used in practice. I'm talking about the two little upper tiles that are used to make some corners. for me the 4 corners are stored inside only one tile ? (hard to explain with my bad english but I'm sure you understand what I mean) Also, do you know if that tilemapping technic has a name ? And do you kown if it is possible to use them directly in Tiled ?"} {"_id": 29, "text": "Capping neighbour height difference on heightmap? I am generating a heightmap with some basic perlin noise but I need to cap the differences between each neighbouring value. A cardinal neighbour can only be 1, 0, 1 in difference while diagonal neighbour can range from 2 to 2. What is a good approach to make sure the map is generated within these rules? Does perlin or a small extension help me do this or should I make 2nd pass after the map is generated by perlin or simplex? I am currently doing the latter where I go over each tile and change it's cardinal neighbours according to it's own value but it is going over the same position number very often."} {"_id": 29, "text": "How exactly do you deconstruct the Tiled Map Editor exported tile ID? I am trying to build 2D maps with Tiled Map Editor for my game, and I export them under text format, so a tile can look like this 1,2,3,15,2,12,2 5,23,1,6,2,3,4,6 and so on, for many rows. In this link you can see an example of a map, to get a better idea. Now let's say I have 3 layers, each using its own tileset. The numbers in the layer represent the ID of the tile, basically the number of the tile in the sheet. If grass is the 2nd tile, then the ID is 2, and so forth. However, as you can see in the link, different tilesets will export different IDs per layer, notice how in the object layer I can have IDs such as 81, when in fact the ID is only 1, so it adds up 80 or so. Since I am trying to make my map system as flexible as possible, I need the real ID in order to make some calculations. How does tiled export these sort of IDs? I simply want to determine what number to substract in order to get the id, like so tile.id currentid something strange"} {"_id": 29, "text": "How are really big maps made? I'm interested in how huge games like The Witcher 3 and Skyrim create and save the open worlds. In my own game I used a system where I stored the map data in a file seperated by commas. For example 'stone' would code for a stone tile, and I just typed in codes for how I wanted my map to appear in the game. I feel like this was a really innefficient and incorrect way of doing things. But, I couldn't think of a different way to get past the problem. The creators of skyrim obviously used a level editor, but how did they actually save a map as big as skyrim's world? How is the data stored? Because with something as intricate as an amazing, 3D world, you can't store it like I did by just having codewords for different tiles that are all the same height and width. How is it done in 2D games as well? For example Ori and the Blind Forest, which does not use a tile based system. Or, in fact, do they not have files that hold data for the level layouts at all? Thanks )"} {"_id": 29, "text": "Store metadata for tile in Tiled Map Editor In my tilemap based game, I need to associate lights with light switches, buttons with doors etc. I am using the Tiled map editor (mapeditor.org), but I have yet to find a way to store these associaltion. My idea is to store a number with each tile, so I can have groups of tiles that interact with each other. Is there a way to store custom data with each tile in the Tiled map editor? Just to be clear I don't want to store custom data with each tile type, but with individual instances of one tile type."} {"_id": 30, "text": "What AI scheme is appropriate for a 4 player, Tic Tac Toe style game? I am about to release an android game that is like tic tac toe, but on a bigger board, and 4 player. Instead of winning when you get 3 in a row, you get points for chains, and the most points at the end wins. I'm going to have a later release that will include AI, but I'm quite new to this. Would minimax be a good choice, but does it work in 4 player? I'm worried that because there are around 90 possible moves for each turn then this would get slow too slow for large enough searches. Any suggestions?"} {"_id": 30, "text": "How to force a sub optimal path I'm currently trying to develop a \"Taxi Driver\" AI that intentionally makes sub optimal pathing decisions. I need to have my driver go from point A to point B using a sub optimal but still logical path. \"Logical\" in this case isn't a well defined condition per se but it is instead defined as a path that would make sense to a passenger (player). Here's an example where Green Optimal Red Suboptimal but \"logical\" Blue Suboptimal but \"illogical\" I'm currently using A so I tried modifying node weights but I couldn't find a way to come up with a logical value for the weight. I've also tried to sometimes pick a random open node (in the right direction) instead of calculating the closest node. However this (understandably) made the pathing look even more illogical. If it can be done I'd like an A solution but I'm open to other solutions as well (even non pathfinding solutions!). It is fine if a solution doesn't always give a sub optimal path for certain conditions (e.g. only one path possible all paths are the same length etc)."} {"_id": 30, "text": "How does pathfinding in RTS games work? crossposted from stackoverflow In a game such as Warcraft 3 or Age of Empires, the ways that an AI opponent can move about the map seem almost limitless. The maps are huge and the position of other players is constantly changing. How does the AI path finding in games like these work? Standard graph search methods (such as DFS, BFS or A ) seem impossible in such a setup."} {"_id": 30, "text": "Pokemon Artificial Intelligence I'm working on a thesis about programming an AI combat system for Pokemon (To be implemented in Showdown!). However, I would like to include historical information about the existing implementations of Pokemon AI. This information would offer valuable context to my thesis. I have been scouring the internet for some sort of algorithm that explains how the AI Trainers make their choices, but have found nothing promising. I realize the fan games have implemented some more interesting AI systems for their trainers, these would be interesting to see as well. What I am looking for is examples of the methods used for Pokemon Battle AI decision making used in Pokemon videogames, whether from main series by Nintendo or the many fan games out there. I realize most of these pose no challenge to an experienced player, but I don't mind, I only wish to compile historical information on previous Pokemon AI attempts."} {"_id": 30, "text": "approach for the system that record player actions and imitate it I am trying to implement some kind of system, that would allow AI to imitate player's action at certain points in similar cases. Case example Player (hp 10, mp 5) used skill BasicAttack when in battle When I set for a bot parameters like hp 10, mp 5 and state attack it should use BasicAttack skill because in same case player used that action. (I'd like to have ability to define similar cases like when hp 11, mp 6 then bot use BasicAttack too because it is similar to hp 10, mp 5 case but whatever) The question is that what are the basic approaches for such cases? Leaving aside snapshotting of player's state, how can such system be implemented? So far I have two ideas. My ideas are 1. order player parameters by priority and states and create tree where every node would be corresponding parameter value. For example node with name hp and value 10 will have a child note mp with value 5 thus I can create required paths to actions 2. I have event log with recorded player events. It keeps its record ordered. I iterate over it and using pattern matching I compare player parameters and retrieve corresponding player action The first approach seems much faster though. But I'd like to know if there already exist approaches for such systems, in order not to reinvent the wheel as I used to do. Are any?"} {"_id": 30, "text": "What are the possible options for AI path finding etc when the world is \"partitionned\"? If you anticipate a large persistent game world, and you don't want to end up with some game server crashing due to overload, then you have to design from the ground up a game world that is partitioned in chunks. This is in particular true if you want to run your game servers in the cloud, where each individual VM is relatively week, and memory and CPU are at a premium. I think the biggest challenge here is that the player receives all the parts around the location of the avatar, but mobs monsters are normally located in the server itself, and can only directly access the data about the part of the world that the server own. So how can we make the AI behave realistically in that context? It can send queries to the other servers that own the neighboring parts, but that sounds rather network intensive and latency prone. It would probably be more performant for each mob AI to be spread over the neighboring parts, and proactively send the relevant info to the part that contains the actual mob atm. That would also reduce the stress in a mob crossing a border between two parts, and therefore \"switching server\". Have you heard of any AI design that solves those issues? Some kind of distributed AI brain? Maybe some kind of \"agent\" community working together through message passing?"} {"_id": 30, "text": "What AI modding is possible in Civ 5? I'm interested in tinkering with the AI in Civ 5. I know there are XML files that can adjust the AI's strategies, but are there other easily moddable AI components? The XML files contain comments that reference some CPP files, are those available to end users or are those comments just aimed at internals?"} {"_id": 30, "text": "Roguelike game detect intent of other actors by observing their moves In grid turn based roguelike game, how can I detect the following scenarios other actor is following observing actor other actor is intentionally moving to block its path Path blocking can happen if for example player intentionally stops right in front of actor and then when actor moves to avoid player, player moves in front and that keeps repeating as long as player does it. I managed to detect that situation in hackish way and I would like to know if there is a better method for solving things like this."} {"_id": 30, "text": "Collaborative Diffusion vs. A for loose armies combat any clear winner? Collaborative Diffusion (CD) takes a lot of the work that A does and combines (writes) it cheaply for multiple agents to read cheaply. This is because the majority of CD's processing works via a simple CA diffusion approach that produces a single shared map for every agent to use on a given game update. Agents then perform hill climbing within that space, which is also very cheap. The primary downside is that the data structure created by CD must apply for all agents that is, each agent's subjective view of the environment is identical A OTOH needs a path calculation per agent, each frame. In spite of this, the relatively low cost associated with CD would seem to make it, on average, a far more suitable approach than A , even when we must create unique views for agents (comments experience on this are welcome). EDIT Consider the following example using Collaborative Diffusion Two armies are on a battlefield, each army emitting a uniform scent. They charge (climb the scent gradient), and as the two lines clash, each agent takes on the first, closest enemy agent on the opposing line. This happens because on each approach step for each unit, it checks whether it's yet adjacent to an enemy if so it locks on attacks indiscriminately. This is much freer than specific targeting, which is where A would seem to be a better choice. Am I correct in these assumptions? Are there other downsides to CD as opposed to insert your flavour of A , for selecting ANY target between large groups?"} {"_id": 30, "text": "How can I maneuver an AI pirate ship for a sea battle? I'm trying to picture in my head what would be required to make an AI controlled enemy do the following in a top down pirate sailing game Approach the player ship Bring player in line with port starboard guns Keep guns trained on player Be able to manoeuvre around obstacles Not cheat acceleration to achieve the above When I first started thinking about the idea it was quite simple, but the more I think about it, the more complex the requirements become with the major problem being the AI calculating perfectly the curve required to come up along side the player, or to better yet, make a pass along their bow stern before coming along side without needing to let them quickly speed up slow down to achieve this."} {"_id": 30, "text": "How much logic should be in an individual behaviour tree node? Let's say I have a condition node which has to spend a lot of time calculating something to finally return a bool to the behavior tree. But in the following action, we need this information again. I now have a few options I could just calculate the information again. That could unnecessarily take a lot of time and may result in redundant code. I could save the information into some kind of state data dictionary but now the action depends on calling the condition first. I could make it a single action that would just fail if the resulting calculation would end up being False. I would possibly end up with a bunch of very similar, very complex actions. Again possibly a lot of unnecessary redundancy. How do I tackle something like that? Is there a pattern that I could apply to the action condition design (or whatever) or inside the behavior tree implementation that solves this? Or am I using behavior trees wrong entirely?"} {"_id": 30, "text": "Is chess like AI really inapplicable in turn based strategy games? Obviously, trying to apply the min max algorithm on the complete tree of moves works only for small games (I apologize to all chess enthusiasts, by \"small\" I do not mean \"simplistic\"). For typical turn based strategy games where the board is often wider than 100 tiles and all pieces in a side can move simultaneously, the min max algorithm is inapplicable. I was wondering if a partial min max algorithm which limits itself to N board configurations at each depth couldn't be good enough? Using a genetic algorithm, it might be possible to find a number of board configurations that are good wrt to the evaluation function. Hopefully, these configurations might also be good wrt to long term goals. I would be surprised if this hasn't been thought of before and tried. Has it? How does it work?"} {"_id": 30, "text": "What should be created first in a video game? When starting developing a video game, should one focus on creating the environment (buildings, trees, mountains etc) first or the A.I. (Playable character, NPCs etc)?"} {"_id": 30, "text": "How would intensive AI pathing be done server side in an MMORPG? Take WoW or Runescape for an example. You have an incredibly large map, filled with cities and forests, each filled with people and monsters. Monsters roam around an area at random that is 25x25 tiles big (ambiguous). This is done server side, so every player than comes across this area sees the same location of the same monster, and when a player attacks kills that monster other players see it too. How is this calculated without being a massively intensive task? If you have 500 different types of monsters, all of which have 5 maximum spawned, you'll be calculating 2500 different paths continuously."} {"_id": 30, "text": "Python java framework for developing artificial intelligence for board games like Diplomacy Risk I am trying to pick a python java framework for developing artificial intelligence for board games like Diplomacy Risk for research purpose. I am specifically looking for multiplayer, multiple round games without any dominant strategies that require players to cooperate as well as non cooperate at certain times. The idea of the research is to not build the game itself or the AI bot, but to discover novel methods for game theory, specifically to deceive other players bots or humans. This research is specifically based on Deceptive Artificial Intelligence. Please share any frameworks(game code with stubs for decision making) that you may know about. It would be a lot of help for my work. If you have any ideas about some other game that I can pick, please mention that as well. I have tried a few frameworks but the lack of documentation is extremely annoying and I haven't been able to move forward in the process. Thanks and Regards!"} {"_id": 30, "text": "Doing a passable 4X game AI I am coding a rather \"simple\" 4X game (if a 4X game can be simple). It's indie in scope, and I am wondering if there's anyway to come up with a passable AI without having me spending months coding on it. The game has three major decision making portions spending of production points, spending of movement points and spending of tech points (basically there are 3 different 'currency', currency unspent at end of turn is not saved) Spend Production Points Upgrade a planet (increase its tech and production) Build ships (3 types) Move ships from planets to planets (costing Movement Points) Move to attack Move to fortify Research Tech (can partially research a tech i.e, as in Master of Orion) The plan for me right now is a brute force approach. There are basically 4 broad options for the player Upgrade planet(s) to its his production and tech output Conquer as many planets as possible Secure as many planets as possible Get to a certain tech as soon as possible For each decision, I will iterate through the possible options and come up with a score and then the AI will choose the decision with the highest score. Right now I have no idea how to 'mix decisions'. That is, for example, the AI wishes to upgrade and conquer planets at the same time. I suppose I can have another logic which do a brute force optimization on a combination of those 4 decisions.... At least, that's my plan if I can't think of anything better. Is there any faster way to make a passable AI? I don't need a very good one, to rival Deep Blue or such, just something that has the illusion of intelligence. This is my first time doing an AI on this scale, so I dare not try something too grand too. So far I have experiences with FSM, DFS, BFS and A"} {"_id": 30, "text": "How AI is balanced across different type of races in RTS games? There are some real time strategy games (like StarCraft 1 or 2) where AI needs to be balanced across different type of races (in SC it's Protoss, Terran, Zerg), so despite they've different type of troops to play, no specific type of opponent have any advantage. Not to mention that they need to consider different type of maps, so in overall each AI playing different race have the same changes of win. How in general this balance can be achieved by gaming companies? Is it just by playing massive amount of games headlessly with different setups? This study and this one plus this dataset may help answering it, but it could be not related."} {"_id": 30, "text": "Can Neural Network play tic tac toe? Is this have any common sense? I'm thinking about theoretical possibility of playing tic tac toe by neural net. Is this have any common sense? Let's consider tic tac toe which contains 3 rows and 3 cols (it's 9 cells). Ok, then the input vector is contains of all our cells 0..8 , where 0 is \"O\", 1 is \"X\" and 2 is empty cell. But what we have for the target vector? On every NN's step we need to know some target and make our distance to target shorter. But the target of this game is only win (or maybe draw), I don't understand how we can make shorter our distance to win. Is any suggestions? My goal is to learn more about neural networks in games that's why I consider such easy game. Maybe it's not the best choice for the NN and I need to consider some other game? )"} {"_id": 30, "text": "Single or Multiple Behavior Trees? I just finished coding a generic Behavior Tree structure for my games. My question is, when creating behaviors for enemy AI's, do I create one large behavior tree with every possible configuration as a node or do I create many multiple Behavior Trees and simply swap them in and out as I need them? To better understand my question here are some examples One large Behavior Tree might look something like this Multiple smaller Behavior Trees might look like this In the second tree I would simply swap out different trees depending on when I need them. This is more apparent for things like evading and backing away from obstacles, I feel like that would need to be done alongside many other behaviors like chasing and evading. I hope that made sense."} {"_id": 30, "text": "What are the most common AI systems implemented in Tower Defense Games I'm currently in the middle of researching on the various types of AI techniques used in tower defense type games. If someone could be help me in understanding the different types of techniques and their associated advantages. Using Google I already found several techniques. Random Map traversal Path finding e.g. Cost based Traversing Algorithms i.e. A I have already found a great answer to this type of question with the below link, but I feel that this answer is tailored to FPS. If anyone could add to this and make it specific to tower defense games then I would be truly great full. How is AI most commonly implemented in popular games? Example of such games would be Radiant Defense Plant Vs Zombies Not truly Intelligent, but there must be an AI system used right? Field Runners Edit After further research I found an interesting book that may be useful http www.amazon.com dp 0123747317 ?tag stackoverfl08 20"} {"_id": 30, "text": "How do I make NPC pathfinding look believable? Is there an \"academic\" way to have NPC walking randomly on a map, but having a believable comportment ? The obvious scenario is a armed guard who is walking around a basement to secure it. It's quite easy to set up a \"believable\" path. What I'm looking for is a way to simulation a crowd in a small town, in fact. How can I make their move look like they aren't goalless robots."} {"_id": 30, "text": "One AI object for each npc Let's think for a moment a game where you'll have around 1k npcs, each one has to take its own decisions. Should each one has an object that decides what to do, or maybe exist one to process every unit? Also, let's think about a complex ai, not just check if npc can see the player nor decides if npc will attack or not. Something like Dwarf Fortress does."} {"_id": 30, "text": "In MMO game, how to handle user characters, who are offline? In my medieval MMO game, players have their own character, that represents themselves inside game. Like a King. Players could have cities and armies, but King acts as main driving force. Then it comes to player, going offline vacation disconnect. How to deal with \"offline King\", to keep some sort of reality in game, without ruining everything for player. I have never liked unrealistic stuff in games, like appearing dissapearing from thin air, like in WoW or other MMO RPG's, when it comes to connect disconnect, like in Matrix movie, when you are disconnected, your \"avatar\" inside the system just vaninshes. Ok, if player char stays where it was left, other players who are online could kick his ass like offline player char was frozen? I see only one solution give player char, while offline, some sort of AI, that controls char. Is there any other solutions? May be, some sort of legend story, could make users only as inner voice, leaving King just passively controlled by user, or other stuff... Please, help! I hope you understand my question."} {"_id": 30, "text": "Are square or hex grids better for pathfinding? Is there any significant difference between using a square or hexagonal grid for the area searched by a path finding algorithm. In other words, is square or hexagonal better, and if so why."} {"_id": 30, "text": "Player Ai for games involving scoring goals like soccer, hockey, basketball? I've been working on a soccer game, and was thinking of different ways to program player AI's and was wondering how they actually work. The concept is probably similar to all games where there are balls and goals like Soccer, Hockey, Basketball etc. Which algorithm do they use ? I imagine if you have the ball, you can use A , to figure out a path passed other \"enemy\" players and score. That seems simple to implement. But if you do not have the ball then then it becomes really complicated you could either play \"zone\" in which case, you stay within a particular region on of the playing area, and orient yourself towards the ball. Or switch to playing \"man\", in which case you stick to some player on the other team. Was wondering what other algorithms people use, as machine learning for a simple mobile game seems like over kill."} {"_id": 30, "text": "How to create a reasonable AI? I'm creating a logic game based on Fox and Hounds game. The player plays the fox and AI plays the hounds. (as far as I can see) I managed to make the AI perfect, so it never loses. Leaving it as such would not be much fun for human players. Now, I have to dumb down the AI so human can win, but I'm not sure how. The current AI logic is based on pattern matching if I introduce random moves which make the board go out of pattern space the AI would most probably play dumb until the end of the game. Any ideas how to dumb down the AI in such way that is does not go from \"genius\" to \"completely dumb\" in a single move?"} {"_id": 30, "text": "Scripting a sophisticated RTS AI with Lua I'm planning to develop a somewhat sophisticated RTS AI (eg see BWAPI). have experience programming, but none in game development, so it seems easiest to start by scripting the AI of an existing game I've played, Warhammer 40k Dawn of War (2004). As far as I can tell, the game AI is scripted with some variant of Lua (by the file extension .ai or .scar). The online documentation is sparse and the community isn't active anymore. I'd like to get some idea of the difficulty of this undertaking. Is it practical with a scripting language like Lua to develop a RTS AI that includes FSMs, decision trees, case based reasoning, and transposition tables? If someone has any experience scripting Dawn of War, that would also help."} {"_id": 30, "text": "Prevent instances from overlapping gamemaker studio I have a game where multiple instances of an enemy move towards a player in their step process. There can be as many as 50 instances on screen. The issue is that the instances all end up in 1 big group as they follow the player. I would like to prevent them from getting more than 2 pixels of each other. the code is as follows if distance to object(player) lt 160 direction ppoint direction(x,y, player.x, player.x, player.y) p potential step(x,y, player.x, true) If I put a distance check of 2px in this code, the instance starts making jerky movements and spins. I would like the instance to continue following the player, but just not allow themselves to overlap."} {"_id": 30, "text": "Approaches to partner trick taking card game AI I am creating an android game out of a partner based trick taking card game. What are some generic approaches to AI players for these types of games and what are the advantages disadvantages of each?"} {"_id": 30, "text": "Chess Artificial intelligence with python and pygame I created chess game with python and pygame. Now I'm trying to make Artificial intelligence, but what is actually best way to do it? Some tips, tricks, links? Thanks"} {"_id": 30, "text": "Positive Evaluation Function Territory AI Help I am trying to implement some positive evaluation into my game. Let me explain. I have a series (anywhere from 5 to 25 (might vary)) of circles (three sizes, big medium small). And each player starts with a main circle which gains 1 every turn (like risk the circles gain at different speeds, the big one gains the fastest and the small one gains the slowest). You can use these numbers to take over other circles, if the \"enemy\" is on this circle it does a risk thing (you fight to see who takes it over, who ever has more wins most of the time, I'm not getting into this logic as it is rather irreverent). So this is a very basic overview of what occurs, now what I need some help with is how I can create an AI which will look at all available (and taken) circles and determine where it wants to move to. There would be circles closes to it, and circles in the enemies area and circles available and circles taken over. And it would need to determine where to move it's forces too next, and so on and so forth. So after some research I read a lot about Positive Evaluation, which it takes all possible moves and determines the best one. So I am wondering if anyone could help me out or give me some direction as to where to go from here. I think what I need to do is take all the circles with any forces on them, throw them into a table array with the cords of each circle and determine which would be best, then I would need to determine how many forces I want to send and where from. Help! ADDITION Allow me to explain a bit, http imm.io 4Xwy see that diagram lets assume the circles are sections of forces, and you gain a new force each \"time interval\" and lets say I want to take all my forces (I'm pink) the circle directly below me and capture it, well the AI would need look at all available circles and pick for example the big green on in the top right (since big would make more troops and its close to the \"main\"). I'm assuming what you said would still work? Weighted options?"} {"_id": 30, "text": "Simultaneous AI in turn based games I want to hack together a roguelike. Now I thought about entity and world representation and got to a quite big problem. If you want all the AI to act simultaneously you would normally(in cellular automa for examble) just copy the cell buffer and let all action of indiviual cells depend on the copy. Actions which are not valid anymore after some cell before the cell you are currently operating on changed the original enviourment(blocking the path) are just ignored or reapplied with the \"current\"(between turns) environment. After all cells have acted you copy the current map to the buffer again. Now for an environment with complex AI and big(datawise) entities the copying would take too long. So I thought you could put every action and entity makes into a que(make no changes to the environment) and execute the whole que after everyone took their move. Every interaction on this que are realy interacting entities, so if a entity tries to attack another entity it sends a message to it, the consequences of the attack would be visible next turn, either by just examining the entity or asking the entity for data. This would remove problems like what happens if an entity dies middle in the cue but got actions or is messaged later on(all messages would go to null, and the messages from the entity would either just be sent or deleted(haven't decided yet) But what would happen if a monster spawns a fireball which by itself tracks the player(in the same turn). Should I add the fireball to the enviourment beforehand, so make a change to the environment before executing the action list or just add the ball to the \"need updated\" list as a special case so it doesn't exist in the environment and still operates on it, spawing after evaluating the action list? Are there any solutions or papers on this subject which I can take a look at? EDIT I don't need information on writing a roguelike I need information on turn based ai in respective to a complex enviourment."} {"_id": 30, "text": "Entity's FSM and exposing internals of the entity I'm trying to implement FSM according to Programming Game AI by Example, it is a pretty standard and straightforward FSM that goes like similarly to this (some stuff omitted and translated from C to C , hope it's fine) class StateMachine lt Entity gt Entity owner State lt Entity gt state void StateMachine lt Entity gt (Entity entity) owner entity void Update() state.Execute(owner) class State lt Entity gt Entity owner void Execute(Entity owner) if (owner.Foo) owner.Bar() class Entity() public type Foo private StateMachine lt Entity gt stateMachine public void OnStart() stateMachine new StateMachine lt Entity gt (this) public void Bar() My problem with this state machine is that the because the state machine is not part of the class anymore (as opposed to, let's say, the naive \"switch\" \"if else\" implementation), it is necessary to expose internal logic of the Entity (e.g. variable Foo, method Boo()). Is this the right way to do it? What if the the Entity class grows, how does it scale. Is it really necessary to keep exposing more and more variables creating getters setters? How are these FSMs implemented in larger projects?"} {"_id": 30, "text": "AI Agent realistic leap to a player in a MMO In the last month I have been struggling with an issue, movement synchronization of a leap of an AI agent in a MMO. I know some theory and basic movement was not a problem with interpolation and stuff, the difficult part is implementing a leap move. My current setup has a server and multiple clients connecting to it. The movement of the AI agent and its behaviour is computed on the server, the AI client receives position updates and interpolates between the current position and the position received from the server. When the server decides that an AI has to attack, it sends an attack command to clients and, to make the thing more realistic, the clients stops their agents as soon as they receive the message and start an attack animation. The important part now during this attack animation, the agent quickly (0.6 s approx) translates (the translation is not in the animation) toward the targeted player. The client of that player then sends the landing position to the server which does some validation and hit checks and then resumes its behaviour computation sending new attack commands or position updates to clients. This creates a very pleasing effect on the client of the player being attacked but may cause weird translations (due to the error in the position of the agents and the players) on other clients. I tried predicting the \"landing position\" on the server but it's always somehow too wrong as it depends a lot on the target direction from the agent, and small changes in both the agent position and target position often lead to big errors. Having a good look and feel of the leap on the client is imperative. My questions are is there a better way to handle this in my case? is there a good practice to follow in this that I am completely disregarding?"} {"_id": 30, "text": "How to ensure a condition in a behaviour tree when processing following nodes? Example tree (Source) As far as I understood, a sequencer iterates over the children until one failed or all are successful. If one children returns \"running\", the sequencer will start to process from that child on the next tick. Let's say \"Do I have food?\" takes longer than one tick because the AI has to walk to the fridge. When \"Am I Hungry\" was successful, it won't be processed anymore. Now while walking to the fridge, the hunger magically disappears. How do I prevent the tree from processing the other nodes even though I am not hungry anymore? Should every following node check the condition again? That doesn't seem to fit the idea of a behaviour tree. How do I implement a condition that has to stay true while following nodes are processed?"} {"_id": 30, "text": "Unit turning in navmesh based pathfinding I'm working on an RTS game, and I'm using navmeshes for unit pathfinding. I do know how to find a general path within a navmesh, but how do you determine if the unit have enough space to turn? I have units of different shapes (mostly rectangles with different dimensions), and with different turn radii. Additionally some of units can turn in place, and some can move in reverse. So, how to find a path which unit can follow, considering that it can not rotate easily?"} {"_id": 30, "text": "Game Maker Studio Make objects avoid other instances of same object with A pathfinding I have a game where there are multiple enemies who must chase a single player. I have pathfinding set up using the GML A pathfinding with mp grid and a path. However, these enemies can walk on top of each other when seeking the player. To fix this, I also told the path to ignore enemies as well with mp grid add instances, but then they stop moving altogether because they see themselves as obstacles, thus trapping themselves within a bounding box. Is there a way I can add \"all other enemies BUT self\" with mp grid add instances? Here's my grid creation code (in a CONTROLS class for initializing variables) global.zombie ai grid mp grid create(0, 0, room width 50, (room height sp dashboard.sprite height) 50, 50, 50) mp grid add instances(global.zombie ai grid, obj obstacle, false) This is my path initialization code (in Zombie class) path path add() alarm 0 5 This is my path creation code in Alarm 0 (path updates every 2 seconds) mp grid path(global.zombie ai grid, path, x, y, nearest.x, nearest.y, true) path set kind(path, 1) path set precision(path, 8) path end() path start(path, MAX SPEED, 0, true) alarm 0 room speed 2"} {"_id": 30, "text": "To what extent are video game bots NPCs artificial intelligence ? Wikipedia says In video games, this usually means a character controlled by the computer through artificial intelligence. https en.wikipedia.org wiki Non player character In video games, a bot is a type of weak AI expert system software which for each instance of the program controls a player ... https en.wikipedia.org wiki Video game bot However as far as I know such bots amp NPCs are way too hard coded or explicitly coded to be accurately called \"artificial intelligence\". Mainly most often they lack the ability to learn dynamically from the player. Arthur Samuel calls \"artificial intelligence\" The \"field of study that gives computers the ability to learn without being explicitly programmed\" (1959). So to what extend can bots and or NPCs be called \"artificial intelligence\" if they (or a subset of them) can be designated as such?"} {"_id": 30, "text": "Path tables or real time searching for AI? What is the more common practice in commercial games path lookup tables or real time searches? I've read that in many games path lookup tables are pre calculated and baked into each map, so to speak, then steering behaviour is used to handle dynamic obstacles. or is it better practice to use optimised hierarchical A searches? I understand the pro's and cons of each, I'm just curious as to what is most often used in the industry."} {"_id": 30, "text": "What should be created first in a video game? When starting developing a video game, should one focus on creating the environment (buildings, trees, mountains etc) first or the A.I. (Playable character, NPCs etc)?"} {"_id": 30, "text": "Problems with Obstacle Avoidance steering behavior I learned how to implement the Obstacle Avoidance steering behavior from this tutorial. The approach depicted in this tutorial (simplified) is this (note that I'm using rectangular OBBs for obstacles, not circles) The entity that avoids obstacles will have a 'ahead' vector, representing the entity's 'sight'. It will be equal to the velocity vector, but scaled to some length (the \"sight distance\"). For each entity in the \"sight distance\" radius from the entity, we check if it contains the the 'edge' of the ahead vector, marked with a red dot (actually the vector itself treated as a point) For an entity that contains the red dot, we calculate the vector from the center of the entity to the red dot This vector (scaled by a scalar MAX AVOIDANCE FORCE) is the avoidance force. We apply it on our entity, and it should avoid the obstacle. However, what happens in practice after applying the force is this As you can see, the entity is about to get stuck on the obstacle. That's because it doesn't sense it's about to collide, because the obstacle doesn't contain the edge of the 'ahead' vector. So what would be a good solution to this problem? How should I implement the algorithm?"} {"_id": 30, "text": "Best next step for game AI implementation I have recently finished a small framework that employs agents governed by a small hierarchical finite state machine, however I have quickly discovered the drawbacks of this approach. Namely the fact that increasing numbers of behaviours call for an exponentially complicated rule base to govern the switches. It occurs to me that there is probably a much better way of coding AI, where they have overall goals and can assess new information with regards to this. I did some research but was a little overwhelmed by the amount of methodologies, and for that matter the lack of information about which techniques are more commonly used and which are best for certain situations. what would be a good next implementation methodology for a 3rd 1st person shooter? such as a neural network or GOAP."} {"_id": 30, "text": "Scripting a sophisticated RTS AI with Lua I'm planning to develop a somewhat sophisticated RTS AI (eg see BWAPI). have experience programming, but none in game development, so it seems easiest to start by scripting the AI of an existing game I've played, Warhammer 40k Dawn of War (2004). As far as I can tell, the game AI is scripted with some variant of Lua (by the file extension .ai or .scar). The online documentation is sparse and the community isn't active anymore. I'd like to get some idea of the difficulty of this undertaking. Is it practical with a scripting language like Lua to develop a RTS AI that includes FSMs, decision trees, case based reasoning, and transposition tables? If someone has any experience scripting Dawn of War, that would also help."} {"_id": 30, "text": "Pokemon Artificial Intelligence I'm working on a thesis about programming an AI combat system for Pokemon (To be implemented in Showdown!). However, I would like to include historical information about the existing implementations of Pokemon AI. This information would offer valuable context to my thesis. I have been scouring the internet for some sort of algorithm that explains how the AI Trainers make their choices, but have found nothing promising. I realize the fan games have implemented some more interesting AI systems for their trainers, these would be interesting to see as well. What I am looking for is examples of the methods used for Pokemon Battle AI decision making used in Pokemon videogames, whether from main series by Nintendo or the many fan games out there. I realize most of these pose no challenge to an experienced player, but I don't mind, I only wish to compile historical information on previous Pokemon AI attempts."} {"_id": 30, "text": "Good way to handle offscreen AI? For example sake Let's say there are 10 rooms in the world. And let's say the world is inhabited by 10 entities. And each entity has it's own \"daily routine\" where it performs certain actions in the room and also might navigate between the rooms as well. Given that the player can only be in one room at a time, what is a good way to keep track of the actions the other entities are performing in other rooms offscreen? The most straightforward option is to check on each of the 10 entities on every frame, check their position state and determine whether or not the entity should be in the room where player is located in at any given time. ( This however feels really resource heavy especially as the room entity amount is increased. ) Another option is to keep track of the time that has passed since the start of the game, then each of the entities checks whether its pattern intersects with the room the player is on, and if it does it checks against the time whether or not the entity is supposed to be in the same room at this particular time, entities whose patterns do not intersect with the current room the player is located in do nothing until the player enters a room which their pattern intersects and only at that point calculate whether or not they should render. ( But if they interact with the room, then they will have to always check the state of the rooms which intersect their route in order to determine their location at that point in time, which is not that great. ) The third option I came to would be to first of all only look at the routes which intersect the player location (as described previously), secondly upon entering a room, check if the player is in that room, if not then to only check the state of the room and how long will it take to proceed to the next room. For example a janitor NPC enters the room, checks the state of the room, sees that there is a spillage made by player, calculates how much time it will take to clean that up and how long the pathing will take etc. And until the mentioned time is due to enter the next room we only check if the player is in the room. The exact location of the NPC for rendering purposes would only be calculated when the player enters the room. After brainstorming a while I came to the third option, but I was wondering if perhaps there is a known or better way to handle things like these?"} {"_id": 30, "text": "Interrupt on behaviour tree I'm using a custom Behaviour Tree library (not UDK or any other engine) so I'm wondering on the best way to cause an interrupt to a currently running node. I don't have decorators or parallel nodes in this library so looking for a different way to do it. I don't care about the specific reasons as to why the interrupt is needed. In general it just needs to tell the currently running node to stop running so the tree can be transversed again and that would find out the reason as the main \"threats\" would be checked. I'm trying to think of a clean way to cause such interrupts in the tree. Generally the conditions that are already in the tree would be the reason for the interrupt (IsEnemyInRange, IsThirsty, IsHungry, etc) but if a node is running over multiple frames these don't get checked. Any ideas given the above limitations I listed?"} {"_id": 30, "text": "Dealing with multiple prerequisites in goal orientated action planning using A I'm currently having difficulty reasoning about how multiple prerequisites are satisfied using the A algorithm during planning. Assuming the following actions (with prerequisites in brackets) Get Material Make Gloves (need material) Get Iron Make Axe (needs iron) And the following goal (prerequisites in brackets) Chop Tree (needs gloves, needs axe) Now, assuming I am doing a backward search from the goal, as I understand it, I would start considering actions that have effects that directly correspond to the prerequisites of the node (this is where I think I'm going wrong). The problem with that is, the first 2 actions to consider are Make Gloves and Make Axe. However, for this goal to be satisfied they both need to be done. If I only build my graph by linking effects to prerequisites, I only consider each of those actions once, and only choose one. I.e. if I arbitrarily choose Make Axe that leads me to Get Iron, I don't have anything making me reconsider Make Gloves as Get Iron has no prerequisites. For the actions and goal I had above there are many routes to solving it, below I have highlighted one to illustrate my point. As you can see, in this case I would need Get Iron to be done after Make Gloves even though their effects prerequisites don't match in any way. Can someone tell me where I'm going wrong in my thinking?"} {"_id": 30, "text": "Conditional priority in behavior trees I want to trigger behavior based on certain conditions. I currently just have a sequence that runs different behavior, it triggers on condition but always in sequence. When the first condition is met it runs that. Let's say I have 2 behaviors. Flee from threat and find food if hungry. Usually the flee from stronger threat prevails and thus is placed early in the sequence. But what if the entity running the behavior is starving, it can take more risk. Since the flee from threat comes first in sequence and triggers on a threat it will never pick to gather food if there is a threat present. I guess I need something like a scoring system and let the tree pick the best option. Is this common in behavior trees? How is it called or best implemented? I'm using gdx.ai in particular and perhaps there is something out of the box I can use. I can make a task in the behavior tree that weighs all the possible actions but this ties everything together and bt's are widely used for the opposite."} {"_id": 30, "text": "Snake AI Is a Hamiltonian approach valid for all grid sizes? So, as has been done many times before, I am designing an AI that can play Snake as effectively as possible. It didn't take me long to find this extremely useful thread here How to find a safe path for an AI snake? where the top answer first and foremost recommends forming a Hamiltonian circuit for the grid and begin by just having the Snake follow this route. However, after attempting this, I realised it didn't work with my initial grid size (23x23), at least I don't think it does. My understanding may be incorrect, but from what I gather, with m rows and n columns, if mn is odd, then there is no Hamiltonian circuit possible. If this is the case, then should I abandon this method? Or is there any way of implementing it in some case?"} {"_id": 30, "text": "Understanding the Seek steering behavior I'm currently studying steering behaviors. Have recently learned about Seek. I have a question about this. Seek is supposed to turn the agent slowly in the direction of it's target, and then move in that direction. However, I don't understand how Seek turns the agent around slowly. It seems to me like it should make the agent change direction immediately. This is the code for a Seek function Vector Seek(Point target) Vector toTarget new Vector(target agent.getPosition()) Vector desiredVelocity toTarget.normalize() agent.getMaxVelocity() return desiredVelocity.subtract(agent.getVelocity()) And then here is the update() function of the agent. void update() Vector force seek(target) Vector acceleration force.divideBy(mass) mass 1. velocity velocity.add(acceleration) position position.add(velocity) Anybody mind explaining to me where the gradual change of velocity takes place? Thanks"} {"_id": 31, "text": "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. Are 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. The 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. Has this solution been done by any other games, or is there a better way of handling the problem?"} {"_id": 31, "text": "udp over cellular networks? I'm starting to build a multiplayer iOS game using UDP. I want the game to be playable over cellular networks, but I can't really find that much information on it. Many people say that it's dependent on your carrier whether or not it will work. I tried searching but I can't really find much info on this topic. I know carriers must allow UDP because of things like video streaming, but what about custom game protocols? Will UDP work over a cellular network? If anyone has a definitive answer or can point me to some resources that'd be great"} {"_id": 31, "text": "When to stop taking items from ever growing queue and start processing them? I am developing a fast paced multiplayer shooting game and following instructions from this source http www.gabrielgambetta.com entity interpolation.html. In the article it says that several clients may be sending inputs simultaneously, and at a fast pace (as fast as the player can issue commands, be it pressing arrow keys, moving the mouse or clicking the screen). Updating the game world every time inputs are received from each client and then broadcasting the game state would consume too much CPU and bandwidth. A better approach is to queue the client inputs as they are received, without any processing. Instead, the game world is updated periodically at low frequency, for example 10 times per second. The delay between every update, 100ms in this case, is called thetime step. In every update loop iteration, all the unprocessed client input is applied (possibly in smaller time increments than the time step, to make physics more predictable), and the new game state is broadcast to the clients. now I am wondering how to implement such a queue system? I can have an in memory queue where each input is added. and after say 100ms how many number of inputs do I process? i.e when should I stop popping events from queue and apply simulation? from my point of view clients are sending inputs constantly which are being added to the input queue. below is the psuedocode. queue inputQueue gameloop() while (inputQueue not empty) lt obviously i cannot use this condition, what should i use then? inputEvent inputQueue.front() updateState(inputEvent)"} {"_id": 31, "text": "P2P synchronization can a player update fields of other players? I know that synchronization is a huge topic, so I have minimized the problem to this example case. Let's say, Alice and Bob are playing a P2P game, fighting against each other. If Alice hits Bob, how should I do the network component to make Bob's HP decrease? I can think of two approaches Alice perform a Bob.HP , then send Bob's reduced HP to Bob. Alice send a \"I just hit Bob\" signal to Bob. Bob checks it, and reduce its own HP, then send his new HP to everyone including Alice. I think the second approach is better because I don't think a player in a P2P game should be able to modify other players' private fields. Otherwise cheating would be too easy, right? My philosophy is that in a P2P game especially, a player's attributes and all attributes of its belonging objects should only be updated by the player himself. However, I can't prove that this is right. Could someone give me some evidence? Thanks )"} {"_id": 31, "text": "Which toolkit to use for 3D MMO game development? Lately i've been thinking about which path to follow for developing an 3D Online game. I have googled a lot but i couldnt find a good article that covers both game development and online server amp client development in same context. This question has been in mind for about 2 weeks now. So.. yesterday i started developing a game from scratch by using Irrlicht.Net Wrapper to use Socket library of .NET which im already familiar. But i found out .Net wrapper of Irrlicht is not totally finished yet and still have lacks from the original. So i lost all my motives . So i thought why not to ask the experts before i run into another dead end... What Game Engine and Networking Library is best way to go for 3D MMO Development? Here is some of my early conclusions Please let me know the ones im wrong. C Best Performance for 3D Graphics. Most Game Engines has native C Libraries. Lacks a Solid Socket Library .NETC Lacks Intellisense Support. C Intellisense Support NET Socket Library Lacks 3D Graphics Performance Lacks a native solid 3D Game Engine"} {"_id": 31, "text": "Components in a client server network game? Behavior and logic are executed on the server. The clients are mostly for rendering, audio, and gathering input. It looks as though most of the a components architecture benefits are only realized on the server. Is it still beneficial to design the client with an component based architecture? Or is there a different approach that better fits a client."} {"_id": 31, "text": "How do I prevent identity spoofing in a multiplayer game? I'm thinking about clients spoofing IP addresses, tricking other clients that they are the server that sort of stuff. (I don't know much about this, so if this is completely wrong, please correct me.) What should I do to prevent this? Because it is a real time game, if I were to use encryption, I would use something fast and secure like RC4. Should I encrypt packet data with a key, that the server gives to the client? If it makes any difference, I'm using UDP."} {"_id": 31, "text": "How to make a multiplayer game work reliably behind NAT? Even games that are 100 client server sometimes have issues when the client is behind NAT. Peee peer games are even a bigger issues. Some games need to use multiple transports (such as UDP and TCP) or multiple connections (such as a different UDP port for voice). What are some ways to make sure a game works reliably when running behind a NAT router? Peer Peer No centralized server exists. Player A starts a game and Player B wants to join Client Server A centralized server on a well known address (hostname) accepts all incoming connections. Each client only communicates with that server. Combo Where the server is just matchmaking, but game updates are peer peer. Different peers may see each player with a different IP port potentially (e.g. some clients are behind the same NAT and some are on a different router)"} {"_id": 31, "text": "How can I handle sharing storage units in multiplayer? I have recently come across a certain problem in programming my MMORPG the synchronization of shared storage units. With shared storage unit I intend something like a \"chest\" that can be accessed by multiple users. Any user can take items from it or put items in it or even move items around and merge items stacks in the chest. To get the idea, think about the guild chest in WoW. At the moment my approach with non shared storage is to apply any transaction on the client (move split merge they take place instantly on the client) and then communicate to the server the change which also does validation and stuff. This works just fine it's rather impossible that one client issues a transaction that would conflict with another of its transactions as he always sees an updated state of the storage (because he she is the only one issuing transactions on that storage). How do you keep a storage synchronized among its co owners when they share a storage unit and therefore can issue conflicting transactions? For example two players issue at the same time a move transaction of the same item. An approach I was thinking about is scratching client side prediction for shared storage but that adds some overhead to my work as clients at the moment are not aware (code wise) that a storage unit is shared. Is there a smarter way to do it?"} {"_id": 31, "text": "Do UDP game clients servers block for receive calls? One way to implement a client server relationship is to have the server simulate the whole game based on the clients input and send updates back to each client, while the client is is simulating the game for the player and sending back input and game state messages that the server can use to process the whole state of the game. My question is, since a ReceiveFrom() call blocks till it receives data and a Select() call blocks for a set period of time, does that mean all clients and servers block for a certain amount of time each frame? I am aware that a call to Select() can be set to zero which would be an effective poll to the read write states of the current sockets, but wouldn't you miss out on new data if it comes in just microseconds later? How is this problem solved now a days? Pro select() method handling? Asynchronously? Separate thread completely? Other? I may be over thinking this, but I would like to know more information so I can write an effective client sever relationship. Haywire"} {"_id": 31, "text": "RTS game How to handle disconnects in a fully connected peer to peer architecture? I'm currently working on a game in which I am considering implementing a networking architecture as described in this article http www.gamasutra.com view feature 131503 1500 archers on a 288 network .php In order for the implementation as described in the article to work, all peers need to be interconnected without any exceptions. Like so This works fine when everything is well. But I am wondering how to agree on disconnects in such a network. (Sadly something the article does not go into). It is relatively easy if one client goes down. Just give every client a timeout, and if a client does not respond for a certain time, it is removed from that client. However, how should the system solve a case in which one client does not respond to another, but still responds to all others. In such a system the following could happen, resulting in a invalid state Of course this can be solved by giving one of the clients some kind of \"master\" role. It being the only one that can decide whether or not to disconnect other clients. But I'm wondering if it can be achieved in a pure p2p network. Note I realize this case is not one that can likely occur \"naturally\". But I want to prevent players from being able to ruin a networking game for others by playing a trick like this by using the firewall for example."} {"_id": 31, "text": "Authenticate player on backend server with google login I would like to create a mobile game which communicates with my own backend server. For authentication I want to use google Sign in(https developers.google.com identity sign in android backend auth), so users don't need to create an account. My backendserver uses a TCP connection to communicate with the client and I don't want to send the google login auth code unencrypted over the network. I read alot about SSL encryption, but I'm not sure if it is the thing I need and if this is sufficient. Another question I would like to ask is do I need to encrypt all packets my client is sending to the server. Because when I just do authentication over an encrypted connection, potential hackers could simply perform a man in the middle attack to access the account of a player after they logged in. So what would be the best way to send this token to the server, is SSL sufficient for this and do I need to encrypt the whole traffic my game creates?"} {"_id": 31, "text": "Networking in a strategy, city management game I'm developing a city management mobile game with its' share of multiplayer elements (leaderboards, achievements, social interactions). It's built using Unity and GameSparks as a backend. I'm a little bit confused on how I should be implementing the networking. At the end of every in game month, the game should go through every business building, calculate the revenue (each building generates different amounts of money depending on the number of workers), then add this value to the player's funds. These funds can then be used to continue building more businesses and houses, which increase the population. I have to save the states for the city (buildings, population, etc) and player (funds, premium currency, etc) in the cloud. I'm afraid people will exploit the game (due to the leaderboards) if I entrust data with the client, and I feel it would be best to keep the system deterministic, but I'm not completely sure I'm doing the right thing. How would you solve the problem?"} {"_id": 31, "text": "How to prevent game client version spoofing Basically I have a c server that will use a binary protocol to talk to my client (unity game). As part of the login process I want to send the client version to the server. The server then responds saying (assuming login credentials are correct) they are okay to connect, or if the client version is outdated it returns a client version outdated. My question is, how can I prevent people using old client versions and spoofing as the latest version. As this could potentially lead to server bugs as it is handling an outdated client thinking it is up to date... Thank you )"} {"_id": 31, "text": "Network game like MMO TPC or UDP I saw this subject several times, however I will wish better understand. I am working on the development of a 2d game like a little MMO. (Currently I only do research). I see people who says it's easier to use TCP for all the game. But is it really viable ? In my mind, what I would have made is to use UDP in multicast. What about this solution ? Thank you !"} {"_id": 31, "text": "How do I create game rooms using Kryonet? I'm currently about to create my first networking game, and it's supposed to be two player and turn based. I wrote the client using the LibGDX library, and the server with Kryonet. It should be possible for multiple users to play the games, at once, I feel the need to create something like a \"game room\". I thought about creating a class with two connections (the two players), adding a listener to each, and to handle the messages within the game room. However, I am not sure how to permanently update the game rooms. At the moment, my server only listens for new connections, and registers them in a list of connected clients. Maybe, I should create a new thread for each match? How do I create such game rooms within the game server, itself? Edit So after doing some more research, this is how I currently do it I store the players, that are currently searching for a game in a LinkedList (more precise, their Connections) and once there are more than two, I do this in my Server class if (connectedPlayers.size() gt 2) GameRoom newGame new GameRoom(connectedPlayers.removeFirst(), connectedPlayers.removeFirst()) gameRooms.add(newGame) some list, storing all the current games newGame.start() and my GameRoom looks like this public class GameRoom implements Runnable Thread t Connection playerOne Connection playerTwo more variables your GameRoom might need public GameRoom(Connection playerOne, Connection playerTwo) this.playerOne playerOne this.playerTwo playerTwo whatever more variables you need to use can be declared here, e.g. Override public void run() while (true) Game logic goes here public void start() t new Thread(this) t.start() I am not really into threading and this is what I set up after a little more reading into that topic, but I assume this is not really scaleable because 1000 games would mean 1000 more threads, which I think is not so good. Please let me know, whether this is the correct approach and if not, just stick to my question and help me with it, if you can and feel like it."} {"_id": 31, "text": "How to prevent a hacked server from spoofing a master server? I wish to setup a room based multilayer game model where players may host matches and serve as host (IE the server with authoritative power). I wish to host a master server which tracks player's items, rank, cash, exp, etc. In such a model, how can I prevent someone that is hosting a game (with a modified server) from spoofing the master server with invalid match results, thus gaining exp, money or rankings. Thanks. Cody"} {"_id": 31, "text": "Using Unity's uNet to create a turn based RPG I've been checking some tutorials about uNet and it seems pretty powerful. The NetworkManager is a great tool when you want to make generic games, but what is troubling me about it is the need of spawning a \"Player\". I intend to create a turn based RPG, and for that, during the battle there's not a \"physical player entity\", there's two players which have a set of monsters and the players can select a monster to attack the opponents', but the player itself doesn't exist, in the end it sums up to a trade of commands between the clients. How can I achieve such an architecture with uNet? Should I discard the use of the default NetworkManager? Should I simply create a bodyless Player and go along with it?"} {"_id": 31, "text": "How do MMO servers handle a large concentrated number of players? I have a pretty good understanding of how to scale servers but there's one thing I can't quite be sure about is how to manage a lot of players in a concentrated area. If I have a server which is using multiple threads and processes as long as you limit the amount of players that can join a single game instance then this can scale indefinitely by adding more servers and placing it behind a load balancer. But MMO games don't work that way because it's broken down into zones that anyone can connect to. So if a massive amount of players all decided to connect to the same zone it would put all of the stress on 1 server. If you tried to spread the load across multiple servers then you'd run into problems of having to share information between the servers (Such as if player X was connected to sever 1 then all of his movements would also have to be passed on to the players connected to server 2 since server 1 and 2 are managing the load for the same zone). So I was wondering how do you go about solving this problem? Do you just keep on ramping up the specs for the server on heavily populated zones? Or is there a fast and efficient way for multiple servers to manage the load for the same zone and efficiently share data between the two servers?"} {"_id": 31, "text": "I'm making a networked game for mobile. Should I worry about cheating? I'm in the process of making a racing game for Android iOS. I'm thinking of implementing a server client model, should I worry about cheating and make all players communicate with a server of mine, or will I be good by letting one of the players host the game? I'm not sure how much memory editing or packet editing is possible in Android iOS, and that's the main reason why I'm asking this."} {"_id": 31, "text": "Client Server RTS networking with lockstep and lag The peer to peer lockstep networking model would seem to indicate that everyone's input is delayed the same amount. And so this would indicate that everyone would feel the same lag in response to their input. But in Warcraft 3 from playing many custom games it is clear that the creator of a custom game has much faster response time to their input. How can this be given the lockstep model?"} {"_id": 31, "text": "Sending changes to a terrain heightmap over UDP This is a more conceptual, thinking out loud question than a technical one. I have a 3D heightmapped terrain as part of a multiplayer RTS that I would like to terraform over a network. The terraforming will be done by units within the gameworld the player will paint a \"target heightmap\" that they'd like the current terrain to resemble and units will deform towards that on their own (a la Perimeter). Given my terrain is 257x257 vertices, the naive approach of sending heights when they change will flood the bandwidth very quickly updating a quarter of the terrain every second will hit 66kB s. This is clearly way too much. My next thought was to move to a brush based system, where you send e.g. the centre of a circle, its radius, and some function defining the influence of the brush from the centre going outwards. But even with reliable UDP the \"start\" and \"stop\" messages could still be delayed. I guess I could compare timestamps and compensate for this, although it'd likely mean that clients would deform verts too much on their local simulations and then have to smooth them back to the correct heights. I could also send absolute vert heights in the \"start\" and \"stop\" messages to guarantee correct data on the clients. Alternatively I could treat brushes in a similar way to units, and do the standard position velocity client side prediction jazz on them, with the added stipulation that they deform terrain within a certain radius around them. The server could then intermittently do a pass and send (a subset of) recently updated verts to clients as and when there's bandwidth to spare. Any other suggestions, or indications that I'm on the right (or wrong!) track with any of these ideas would be greatly appreciated."} {"_id": 31, "text": "How to properly handle sending arrow key movement data to a authoritative server? I've made a little C server which receives UDP packets and shows me the incoming information. I want to make an authoritative server in C which simulates character movement and interaction in a 2D real time world and sends information back to a Unity game client where the information is then represented. My question is How does my server know how long a button is pressed in real time (example right arrow key to move character right)? My guess is that the client would send a UDP packet to the server on key press saying move this direction. The server would then simulate the character moving and new positional information is constantly sent back. When the Client releases the key a new UDP packet is sent to the server saying the movement key has been released thus stop moving this direction. BUT the problem is UDP unreliability and the lag between letting the key press up, and the server knowing that the key press is up which would make the character keep moving for a period of time after letting go of the key is this solved with proper movement interpolation?. Any ideas or information sources how to properly handle sending arrow key movement data to a authoratative server?"} {"_id": 31, "text": "Game clock Synchronization in python I am working on a network game project in python which we want to keep synchronized. I would assume we should use Network Time Protocol to cater for different levels of lag. That being the case, is there an implementation for Network Time Protocol in python?"} {"_id": 31, "text": "How to measure packet latency? In the context of lag compensation, one needs to know when the command is instantiated on the client (this can be named as \"command execution time\" as well). AFAIK, there can be 2 methods for this Client sends a timestamp with the command. Client doesn't send any timestamps, but server does a smart thing to calculate the command's instantiation time. About 1 Is this safe in terms of cheating? About 2 According to Valve's paper, command execution time is as following Command Execution Time Current Server Time Packet Latency Client View Interpolation This means, server must know the packet latency. Another paper from Valve confirms this and says Before executing a player's current user command, the server Computes a fairly accurate latency for the player ... How can the server compute \"fairly accurate latency for the player\"? Most naive and easiest approach would be sending pings regularly (less frequent than game commands and updates though) to find out an average of the latency and use it. Busy network traffic, latency fluctuation and naiveness of this method makes me feel there must be a more elegant way. EDIT Would UDP vs TCP change anything in this context?"} {"_id": 31, "text": "Lightwight cross browser library for server side push? I am looking for a lightweight javascript library that allows the server to push update information to the client reliably and regularly. We use a fixed turn time of 300ms and often there are only about 20 bytes of changes. So doing polling using XMLHttpRequest would imply a huge overhead (3 way tcp handshake, http request headers, http response header). There area number of alternatives, but they have limited browser support streaming lt script gt tags in another frame (does this work on IE?) MIME multipart x mixed replace responses (Firefox, Safari, Opera only?) WebSockets (removed from recent beta version of Firefox and announced to be removed from Opera 11 because of security issues) Server sent events (only Opera?) Java Flash relays (requires the users to have those plugins installed) Polling using XMLHttpRequest (huge overhead) Is there a website which has recent information on which technology works in which browser? Are there javascript libraries which provide a common cross browser interface that hides the messy details? (Yes, i know that it still requires me to write multiple server sides, but that is rather easy. And more important it is easy to write automatic tests for the server sides)."} {"_id": 31, "text": "How do we make online games deterministic? I am trying to understand how networking in games work as I am trying to make an online game myself. I can't grasp how it is possible to synchronize the players, in order to make the game deterministic. I found an article saying this in order to ensure that the game plays out identically on all machines it is necessary to wait until all player s commands for that turn are received before simulating that turn. This means that each player in the game has latency equal to the most lagged player. This makes sense and I also came to the same conclusion after hours of drawing graphs with various scenarios. However, there are some games where one player can have 500ms delay, and another player could have 40ms delay. In this case, how is the game deterministic ? Lets name players with 40ms, 500ms delay Player40, Player500 Lets say that Player40, shoots Player500 with an instant laser shot at T1 0ms. Exactly 40ms after the Player40 actually clicked with his mouse to shoot (so T2 40ms), The \"laser shooting event\" registered on the server and returned \"ok, you can execute laser shoot\" to Player40. So, the shot is being applied on Player40's machine and on his screen he sees that he killed Player500, and the corpse is lying on (x1,y1,z1). Meanwhile, what happened on Player500's machine, was that Player500 was running straight. A few moments later he sees a laser a few feet behind him, he dies even though the laser didn't hit him, and his corpse is lying on (x2,y2,z2). Since this scenario never happens in some games, does this mean that those games are deterministic ? How is something like this possible, without forcing all players to get a delay equal to the delay of the most lagging player ?"} {"_id": 31, "text": "Need help choosing the right networking approach platform for an RTS I have been thinking for a while about making an online 2D RTS like game. (2 6 players in a match, up to 50 60 units, no AI). The key thing here is that I want the game to be playable in a browser, so it'll have to be either flash or java applet, both using TCP sockets. At first I was entirely focused on flash because of a higher market penetration and accessibility. However, after reviewing different networking approaches I am unable to make a choice. I really liked lock step simulation approach where server and every client are running the exact same simulation, until I realized that it's going to be tough as hell (if not impossible) to implement exactly the same logic in two different languages, one of them being actionscript. This is where java comes in. With java client and server can share simulation related code that may as well cut the development time in half. But then there is another approach, where clients try to simulate (or rather extrapolate) the game state correctly as long as possible, but they don't have to do it right at some point they are going to receive the full state snapshot an adjust accordingly. Flash looks like a viable option again, but still, lock step simulation seems so much more straightforward, as there is no \"adjusting\" part. So are my assumptions correct? What would you suggest?"} {"_id": 31, "text": "Kryonet Open a server locally only On the game I'm working on I wanted the singleplayer mode to use an integrated server to make adding more players via networking easier. The way I have it right now is I open a server and connects the client to my local address which works fine. But the problem is that if I play the game Singleplayer I don't want to leave anything exposed to the internet while only playing locally. Is there any way to limit the \"range\" of the server to only let communication happen via LAN? Thanks in advance! EDIT I am using kryonet for networking. The game is written with LibGDX."} {"_id": 31, "text": "how to guarantee the order of response in a service oriented mmo server cluster i'm working on a mmo server these days. it's a service oriented architecture, every service is one process which processes a specific type of request, and i have inventory service, battle service, etc. when received a request from client, the request will be dispatched to some corresponding service, based on the request type. let's assume we received two requests from one client in the cluster side request message queue, first request1 and then request2, then the two requests will be dispatched to service1 and service2. so request2 may be handled first and the client will receive response2 first and then response1, which will not be what the client expect. so i'm wondering how to guarantee that response will go back in the same order request come?"} {"_id": 31, "text": "How does delta compression reduce the amount of data sent over the network? Many games use the technique of delta compression in order to lower the data load sent. I fail to understand how this technique actually lowers the data load? For example, let's say I want to send a position. Without delta compression I send a vector3 with the exact position of the entity, for instance (30, 2, 19). With delta compression I send a vector3 with smaller numbers (0.2, 0.1, 0.04). I don't understand how it lowers the data load if both of the messages are vector3 32 bit for each float 32 3 96 bits! I know you can convert each float to a byte and then convert it back from a byte to float but it causes precision errors which are visible."} {"_id": 31, "text": "Does StreamPeerTCP guarantee received packet is same from server? I'm making simple Godot project that works with Node.js server. To receive and send packet to Node.js server, I used StreamPeerTCP. First seems works, but after 2nd transmission from server, extract data from packet were broken and mess all other logics. This wasn't happened when same logic tested with Unity C https github.com rico345100 unity multiplayer with nodejs blob master Assets Scripts Network NetworkManager.cs Here's the repo I'm currently developing https github.com rico345100 godot multiplayer with nodejs https github.com rico345100 nodejs tcp server for godot Used Godot 3.1.2 but also works with 3.2.rc6. Tested with Godot 3.1.2 and macOS 10.13.6."} {"_id": 31, "text": "Solution for lightweight LAN peer discovering? I built a library for purely cross platform programming. My games made with it run fine in Android , Pc, Linux, Mac etc. The networking capabilities are provided by ENET library, therefore all communication between my apps is not TCP or UDP compatible, but only in the custom protocol, even tough its based on the UDP ultimately. I don't think its possible to do what i want with ENET, thats why I ask here for help! Lets say I have the same game running in my Android phone, my laptop and my pc. They are all in the same wifi network, and therefore in a LAN, whether its Wifi hotspot(?) or the household router. I need each of those 3 peers to discover the other two in the network. This is meant only to find the IP of alive apps in the LAN network, to be able to host multiplayer games between them. I can only think of one effective way to do this, UDP broadcast, wait responses, but if that is the solution, i need something small, since its the only purpose of the implementation. Other way could be to try to connect to all IPs in the LAN address subrange, but I don't think the OS would be with me on this one p"} {"_id": 31, "text": "Handling packet impersonating in client server model online game I am designing a server client model game library engine. How do I, and should I even bother to handle frequent update packet possible impersonating? In my current design anyone could copy a packet from someone else and modify it to execute any non critical action for another client. I am currently compressing all datagrams so that adds just a tad of security. Edit One way I thought about was to send a unique \"key\" to the verified client every x time and then the client has to add that to all of it's update packets until a new key is sent. Edit2 I should have mentioned that I am not concerned about whether the actions described in the packet are available to the client at the time, this is all checked by the server which I thought was obvious. I am only concerned about someone sending packets for another client."} {"_id": 31, "text": "How do I determine how far to move an object in the client when using client prediction? I have a game server which, for testing purposes, is updating once per second, or 1hz so I can correctly implement client side prediction. Everything is running locally at the moment so there is no lag issues to deal with, but this setup replicates potential packet loss, or if the server somehow is behind on processing. I am using Unity for the client. I have a tunnel where the position is updated on the server and then broadcast to each client each tick (once per second). The client simply then lerps between its current position, and the new position received from the server, and this seems to work nicely. However, as I have set the tick to 1hz, there are unexpected results where the position seems to pulse, rather than smoothly transition. An example can be seen below. It can perhaps be seen more clearly without lerping I have tried constantly increasing the tunnel's position in the client, but if it's moved too far in the client, once the server's position is received, it is snapped back to that position which creates some weird rubber banding like effects even though there is no lag. How can I determine how much to move the tunnel in the client to create some seamless movement, even when the tick rate is so low? Baring in mind this movement is variable, so it can move faster slower at times so the movement in the client cannot be a fixed number. Yes, I can just increase the tick rate which gives smooth movement, however, there is no lag to account for as it's all local so I am just preparing for when I move the server to actual hosting. Instead of lerping between the current position and the received position, should I be trying to lerp between the current position and the next received position? Lerp Vector3 currentPosition transform.position Vector3 newPosition new Vector3(currentPosition.x, currentPosition.y, tunnelPositionZ) transform.position Vector3.Lerp(currentPosition, newPosition, Time.deltaTime) DMGregory's solution attempt If I decrease the 1.0f for the blend variable, the tunnel will move very slowly and then jolt forward when a snapshot is received. Decreasing the 1.0f to around 0.1f seems to align the speeds but there is still a noticeable jolt. I'm using the same velocity for the currentPosition and newPosition because the velocity never changes. float dT Time.time latestSnapshot.arrivalTime float blend Mathf.Clamp01(dT 1.0f) Vector3 currentPosition transform.position Vector3 currentVelocity rigidbody.velocity Vector3 newPosition new Vector3(currentPosition.x, currentPosition.y, latestSnapshot.tunnelPositionZ) Vector3 newVelocity new Vector3(currentVelocity.x, currentVelocity.y, latestSnapshot.tunnelVelocityZ) Vector3 velocity Vector3.Lerp(currentVelocity, newVelocity, blend) Vector3 position Vector3.Lerp( currentPosition velocity dT, newPosition velocity dT, blend) transform.position position"} {"_id": 31, "text": "Only send moves for P2P 2 player LAN game? I am making a 2D network game. The concept is simple, a player have to shoot the other player to win. I'd like to improve this game ( add a map, items, monsters, w e ), but later. This is my first network programming experience. I have little theorical knowledges about packets, sockets, client server side, what is dangerous to do client sided, but I've never really used them. Goals set This is a 2 players LAN game, no more no less. No server. Player 1 starts the game waiting for player 2... ... which leads the game open for reverse engineering or packet editing, but w e, for this kind of game I prefer simplicity over security. Pretty basic. For a first network game that will never be shared, I take off problems and will see later. This is where I am each player is a square that can move in four directions. The approach TCP Packets. Each movement ( each frame a key is pressed to be accurate ), a packet is sent to the other player with his position. Packets are received each frames before drawing and updating game elements, in the same thread, with a non blocking receive() function. And that's it. My questions Is sending a packet for each moves overkill? Will I have problems with this later? What kind of problem can I meet? mono thread non blocking function will be a problem later, assuming the goals I've set?"} {"_id": 31, "text": "RTS game How to handle disconnects in a fully connected peer to peer architecture? I'm currently working on a game in which I am considering implementing a networking architecture as described in this article http www.gamasutra.com view feature 131503 1500 archers on a 288 network .php In order for the implementation as described in the article to work, all peers need to be interconnected without any exceptions. Like so This works fine when everything is well. But I am wondering how to agree on disconnects in such a network. (Sadly something the article does not go into). It is relatively easy if one client goes down. Just give every client a timeout, and if a client does not respond for a certain time, it is removed from that client. However, how should the system solve a case in which one client does not respond to another, but still responds to all others. In such a system the following could happen, resulting in a invalid state Of course this can be solved by giving one of the clients some kind of \"master\" role. It being the only one that can decide whether or not to disconnect other clients. But I'm wondering if it can be achieved in a pure p2p network. Note I realize this case is not one that can likely occur \"naturally\". But I want to prevent players from being able to ruin a networking game for others by playing a trick like this by using the firewall for example."} {"_id": 31, "text": "Which game logic should run when doing prediction for PNP state updates We are writing a multiplayer game, where each game client (player) is responsible for sending state updates regarding its \"owned\" objects to other players. Each message that arrives to other (remote) clients is processed as such Figure out when the message was sent. Create a diff between NOW and that time. Run game specific logic to bring the received state to \"current\" time. I am wondering which sort of logic should execute as part of step 3 ? Our game is composed of a physical update (position, speed, acceleration, etc) and many other components that can update an object's state and occur regularly (locally). There's a trade off here Getting the new state quickly or remaining \"faithful\" to the true state representation and executing the whole thing to predict the \"true\" state when receiving state updates from remote clients. Which one is recommended to be used? and why?"} {"_id": 31, "text": "What's the performance benefit of saving all logged in characters in MMOs in regular intervals? The majority of MMORPGS have a Worldsave system that will save all the characters once every X hours. I guess the reason is performance. So why is this better, performance wise, than saving a character on disconnection?"} {"_id": 31, "text": "Implementing Multiplayer entire world ticks or just changes? i'm working an a very simple multiplayer experience (for now node.js, later will probably remake all in c , but my question is more about theory). All guides and tutorial i saw about making something multiplayer Always speak about sending all the \"world\" information, once per tick, deciding optimal tickrate, making smooth movements on client side with interpolation or stuff like that. Honestly i thought of another way, and i really cant see why its never mentioned. My idea would be the following Client sends to server when input happens eg if you move with arrows, you send to the server a message only when your moving status changed. If you was moving right and then start moving upright, then you send a message about you changing your movement. Server recives the messages, sets variable on player object for its movement, and sends to all other clients information about the change. Also sends current time and current position in the server at the moment of movement change. Clients recive a movement status update, place the player object in recived coordinates moved by the new movement ping delay. That way position in all clients should Always be up to date with the server. Why should i send hundreds of positions to each client per each player every x milliseconds when i can just send the changes? I feel like its about polling vs interrupt... (yeah i know its not polling anyway, but the concept is sending the change vs keep sending everything)"} {"_id": 31, "text": "Client Server RTS networking with lockstep and lag The peer to peer lockstep networking model would seem to indicate that everyone's input is delayed the same amount. And so this would indicate that everyone would feel the same lag in response to their input. But in Warcraft 3 from playing many custom games it is clear that the creator of a custom game has much faster response time to their input. How can this be given the lockstep model?"} {"_id": 31, "text": "Secure login for a game that is open source I am making a game which i will be open sourcing. Its a simple arcade like game but requires a network connection because it is meant to be played with other people. The thing i am worrying about is how would i be sure that the client is the one that i put out for the end user to play with? Kind of a like of sv pure for Team Fortress 2. I was thinking of different ways to combat this such as the server requesting the client's version or even it's md5 hash but people with simple java knowledge could just force a method to always return what the server wants."} {"_id": 31, "text": "LAN game in Actionscript 3 I know this may be a somewhat dumb idea, but is there any \"easy\" resource that anyone can point me towards that shows how to set up a simple LAN connection in an Actionscript application? I only need to have two clients connected. Nothing extremely robust. This is not an AIR application. It's for a game idea that I have that will need two players essentially. It will be local, so having each other's IP addresses will be an option. So no need to find or detect any IP addresses. Thanks."} {"_id": 31, "text": "Should I consider a cloud based networking solution? In my spare time for the past few years, I have been working on both the front end and back end for a space based online game. This game is initially designed for the PC, and is hopefully able to host thousands of players in a massively playable universe. Along with the development of the game, I have been building the networking solution almost entirely from scratch. The architectural design of the networking solution is based on a fairly traditional master server sub server model. I recently was able to run some fairly decent scale tests on this model and was pleased to see that both my expectations and goals were met. Which leads me to my current fear. The basic idea behind the current solution is that the master server acts as a router. It knows about all of the currently active sub servers, including their load (cpu, memory, bandwidth etc) and what the sub server is assigned to handle. The master server has literally no other purpose. Each sub server is designed to handle one (or more) solar systems. The idea being as a player, you connect to the master server and tell it which solar system you want to go to. The master server looks to see if there is a sub server already assigned to this solar system and sends you there, otherwise it finds the sub server with the least load and assigns that sub server to the solar system before sending you there. The part that I am worried about is that this is pretty much as much as I can get out of this model. Once you have been sent to a solar system, you (and everyone else in that solar system) are on that sub server until you leave that solar system. Although I am happy with my testing so far, and that it looks to be able to handle around 300 fairly active peers, fairly comfortable on a well fitted server, I am worried if I ever end up in the situation where this isn't enough. I discussed this recently with a few acquaintances of mine. The discussion lead to a cloud based network maybe being a better solution than single server machines acting as sub servers. Atmittedly, cloud commputing is fairly unknown territory for me. With that being said I've spent some time looking into this and I am fairly confident with the basics, but I have the following questions I assume that if I were to re design the networking solution to work within a cloud based network, I would no longer need the master server sub server model, since I could build a single application that would handle all solar systems and peers, and that the cloud would scale based on the number of solar systems and peers? Any and all advice is welcome!"} {"_id": 31, "text": "Using peer to peer for prediction in a client server network model By implementing peer to peer connections between clients in a client server network model I should be able to increase the prediction fidelity as this theoretically would provide the client with other clients commands for a given tick earlier than it would receive the servers game states for the same tick. One problem I can think of is that clients would have to be able to interpret other clients commands (usually they just have to listen for game states, not commands). This would be a little bit like an RTS model I guess. This should be solvable without any negative effects on gameplay. Another problem is that clients could cheat by sending fake data to their peers when it is beneficial to them. This can be mitigated by having the client aware of the real commands through the server and have them immediately stop listening to any clients that fed it false data. This should therefore be solvable with different degrees of negative effect on gameplay depending on the design of the game and how impactful a few ticks of wrong command info is at the worst possible moment. (Unfortunately, you can't have the server punish any client because it has no idea who's lying, it can only help clients themselves understand if they are being lied to by providing them with correct data). Am I correct in assuming that this would increase prediction fidelity or is there something I'm not accounting for? The idea is that this allows the client access to some information about the other clients faster than in a traditional non peer to peer model where it would base predictions solely on its own commands."} {"_id": 31, "text": "I know that my super simple multiplayer setup is probably not a good idea, but why? I'm making a simple little MOBA just for fun. I was making everything single player then I realized \"oh crap I should probably add multiplayer, huh.\" I've never done anything with networking before, so learning how to integrate Lidgren into my game was fun and awesome. The thing is, I pretty much know the way I'm doing things is wrong, because it's not robust enough for mainstream games to use, as far as I know, but what's wrong with it? What I'm doing is, basically, whenever a player does an action, it sends a message to the server saying \"hey, I just did this thing.\" The server and the client are both running the same simulation. The server then sends a message to all other clients telling them that that guy did that thing. For the most part, except in a few cases, when a player does a thing, the client assumes it's cool and goes ahead with it on its own. So when you right click somewhere to move there, that player's client just starts moving his guy there, and then sends a message to the server telling it about it. So basically Player 1 casts a spell to make him move 100 faster for six seconds Player 1's local client adds that buff to his Unit object Player 1's client sends a message to the server saying \"hey I just cast this spell\" The server makes sure he really did have enough mana to cast that spell, and if so, adds that buff to the server's copy of that Unit object The server sends a message to all other clients saying \"hey this guy just cast this spell\" Every other client receives the message and goes \"ah okay cool,\" and adds that buff to their local Unit object for that player I've been skimming through stuff to see how big games do multiplayer, and it's kind of confusing for someone who's just starting to dabble in this stuff, but it looks like the Source engine sends a packet containing all of the changes to everything in the world every tick? Again, totally new to this stuff, but can you really push that much data that frequently? Sorry if this is a bit rambly, but basically, I was wondering why my simpler system isn't the right way to go, because if it was, other games would use it, right?"} {"_id": 31, "text": "How ID's work in FPS games I am wondering how games generate IDs GUIDs for their entities (along these lines), and which entities specifically get them. To narrow the scope of the question down, I am just focusing on FPS games such as Halo. This was an earlier question that helps explain how state is synced across clients in an FPS The state that is synced when a window is broken in a FPS game The goal with that question was to learn what kinds of data is sent around to sync clients. The piece that is still missing for me is what entities in the game actually get an ID of some sort (either a GUID, or a scoped ID such as some incremented integer or something). Some of the game \"entities\" I am considering are Particles of light, individual pixels, physical forces, etc. (the lowest level vectors points for calculating light or physics stuff). Topology (mountains, roads, etc.). Landscape features (grass, bushes, trees, rocks, water, rain drops, etc.). City features (cars, signs, buildings, windows, shards of glass from a broken window, etc.). Tools items (weapons, potions, etc.). Other players. It seems that some of these \"entities\" you can interact with (e.g. destroying a car in GTA, or the other players in the game), some you can to some degree (i.e. bushes might sway when you walk by, but you can't shoot them for example), and some you cannot (like the sun in a skybox). I am thinking in terms of state syncing, it seems like there must be IDs somewhere in the picture so you can map a game entity from computer A to the same game entity in computer B. Even without syncing, it seems like you might want some sort of IDs on objects to allow for easier handling of events and tracking objects. But at the same time I don't really see \"IDs\" in simple \"game engines\" like these JavaScript game engines, so that is why I'm asking the question. The question is, for large games like Halo, what the entities are that have IDs (or some of the main ones), and if the IDs are GUIDs (or generally what kind of ID they are incremented integers, random numbers, UUIDs, etc.). Like I'm wondering, maybe bushes have IDs. Maybe the individual leaves on the bushes have IDs. Maybe every single triangle in the graphics has an ID. That's what I'm wondering. Maybe the shards of glass have IDs because you can pick them up. Maybe only the players have IDs for some reason. Etc. I am interested because (a) it seems like IDs are necessary in different ways (for state syncing, for tracking player behavior with different entity types to improve the game experience, etc.), and (b) there is a lot of variation in performance when it comes to using IDs. For example, I just tried generating 1 million particles like this and got these results crypto.getRandomValues 5.7 seconds to generate 1 million IDs. Math.random() 18ms to generate 1 million IDs. i 5ms to generate 1 million IDs. In addition, there is the space constraint, so by using i you can use fewer bits for the ID until it gets very large, but they don't work as GUIDs so you need to do extra work to create ID \"scopes\" or things like that. Anyways, I would like to figure out how to deal with IDs in games, and looking to FPS as an example to demonstrate where the IDs might be used. Any help would be appreciated. Thank you. If it is a complicated topic (I'm not sure), then just knowing roughly an outline of how it is typically done, or even a place to look for more information, would be helpful. Also, just saw how Unity is a good example of a Component Entity system, so maybe instead of FPS a better example is how generic game engines do it. Either way, whatever helps explain how it works."} {"_id": 31, "text": "In a 2D multiplayer game should I send the position of user to the server all the time? In a 2D game where the user moves with the keyboard arrows, should the user send all the time he moves his position (x, y)?. If the user has some speed, the user would send (x, y) like 50 times pixel by pixel in just a second."} {"_id": 31, "text": "TCP Slow Start in Network Games I'm getting latency issues in bandwidth intensive level transitions part of my game that are proportional to the distance to the server. I believe I'm hitting TCP Slow Start issues. It's also fine when I spam level transitions in quick succession but the problems re appears. Note that I'm not breaking the TCP connection. Effectively the transfer rate of my game is very bursty and remote users are experiencing a high latency (0.8 second) during these events. Some of the data I need to send during these bursts are dynamic so I can't pre exchange it. Is there anything I can do to mitigate the problem? Sending dummy data to keep the TCP window size is pretty much not a solution. All the data needs to be received in order so UDP isn't really appropriate here."} {"_id": 31, "text": "Is RPC Safe and what is security layer of RPC? We're creating a MMO and I wonder is RPC safe or not ? Isn't RPC easily hackable by injecting to client and what is the security layer of RPC on Unreal Engine ? For example a player is walking and sending that information (new position, rotation etc) to other players, can't that player change movement speed or position with injecting ? What is validating is that movement is valid or it was a hack ? I checked on Google but didn't get answer for my questions. Thanks o"} {"_id": 32, "text": "How to properly protect a flash game? If I understand correctly, the main point of protecting a single player flash game is to keep it sitelocked. How to do this right and are there any other reasons to do this?"} {"_id": 32, "text": "Water simulation in Isometric game I'm creating a game in Flash AS3 in which the player needs to modify land in order to direct the water in the right direction. However, water simulation is a new topic for me and I'm kinda stuck. It doesn't have to be like realistic water, with ripples and stuff, but it has to flow, and if there's enough water, it needs to rise. I've thought up two different types of water A Spring Infinite source of water. Used for simulating seas and stuff. Water block Just one unit of water. My current implementation shows how I'd like the water to spread, but it doesn't rise, and doesn't allow for finite water. Also, the spreading isn't accounting for any amount of water, it just duplicates instead of actually moving units of water. I'm curious to how you guys would solve this problem. Any examples pseudo code is always appreciated. Current version http dl.dropbox.com u 319897 ProjectWater.swf You can manipulate the land by pressing left mouse. And can simulate one step of water at a time by pressing A. Source of the water part http pastebin.com Js2kYt4y"} {"_id": 32, "text": "Internationalization (i18n) in Flash games? Is there an easy way? I want to internationalize some texts in a flash (not flex) game I'm working on and I can not find an easy way to achieve that... I have found some libraries and other solutions, but I expected something a lot easier (it is really easy with other technologies). Do you have experience in this? How do you do it?"} {"_id": 32, "text": "How to achieve smooth sprite movement with a scaled up canvas? I'm developing a simple 2d platformer using haxe amp 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. So my question is how to be smooth amp old school at the same time? Thank you for your time."} {"_id": 32, "text": "Are there any sample projects for Flashpunk? Are there any open source games using Flashpunk? The other big flash game library Flixel has a number of example projects, are there any equivalents for Flashpunk?"} {"_id": 32, "text": "How does MMO flash games works? I want to know how does MMO flash games work, for example Dofus and Club Penguin. I want to know if by ony using Adobe Flash and ActionScript you can do MMO games, or if there is other way to work with ActionScript and Flash beyond Adobe Flash."} {"_id": 32, "text": "Pixel perfect collision against rotated sprite in Flixel I've got a roughly 500x50 graphic of a lockpick that I need to be able to rotate very finely while doing pixel perfect collision detection against the lock object. There's no way to do pixel perfect collision detection in Flixel, so I'm using the Power Tools' FlxCollision class to accomplish this. The problem is that this class only works with rotated sprites if they were loaded with loadRotatedGraphic. ...the problem with that is that it only allows you to rotate to discrete angles. You pass it how many angles you need to be able to rotate to and it, I think, pre prepares all the frames for you. And the reason that's a problem is because I need such fine rotation. I need at least 128 different angle values, but when I do that I get Error 2015 Invalid Bitmap, which I'm assuming is because the resulting 128 frames of a 500x50 lockpick results in a bitmap larger than AS3's limit. I can load the graphic using loadGraphic instead, which I think just calculates the rotated image real time, but then FlxCollision won't notice that it's been rotated. Another problem is that with the pre rotated graphics, you can't rotate about a specific point, and I need the lockpick to rotate around the tip of its handle. ...so how the heck do I do pixel perfect collision against a rotated sprite? I'm trying to mod FlxSprite so that FlxCollision will see the rotated sprites even when they're calculated in real time, and to do this I Ctrl F'd through the class looking for appearances of \"angle\", the variable that you set to rotate a sprite, but all I can find is some obscure calculation in it's used to compute a frame number, and I can't find a single call to any function that looks like it's doing real time bitmap rotating. So, I was able to solve this problem. All FlxSprites hold the bitmap for their currently visible frame in an internal variable called framePixels. If you load a graphic using loadGraphic, then you can do real time rotation in this case, the draw() function rotate s framePixels \"at the last minute\", right before rendering it. Meaning the rotated bitmap is not stored, and FlxCollision has no way of seeing it. FlxCollision runs its collision checks against the unrotated bitmap. So this is what need to be done Get the sprite to store its rotated graphic somewhere rather than just sending it to the renderer and then abandoning it. Get FlxCollision to use that stored rotated graphic rather than framePixels. This is summarized in the following diagram. Flixel's default logic is in black, my changes are in red. I applied all of this in a sub class of FlxSprite that I called PerfectCollisionSprite. Here's my code."} {"_id": 32, "text": "Change the tilemap shown on stage in Flixel I am building a simple platformer using Flixel, beginning with the source code from Flixel creator's EZPlatformer . I would like to adjust the level's tilemap when the player sprite enters overlaps with a sprite representing a door. I use Flixel's built in function to track if the player overlaps the door sprite. exits is a class level variable public var exits FlxGroup I call this function in the Update event to check for overlap FlxG.overlap(exits,player,UpdateScreen) I successfully catch when they overlap, however when I try and load the new tilemap, the old one continues to show. I use this function to attempt to update the tilemap on the screen public function ChangeScreen() void load the screen and locations of sprites(e.g. player, exits) based on current screen switch(currentScreen) case 1 load tilemap level new FlxTilemap() level.loadMap(FlxTilemap.arrayToCSV(data1,40),FlxTilemap.ImgAuto,0,0,FlxTilemap.AUTO) add(level) break case 2 load new tilemap level new FlxTilemap() level.loadMap(FlxTilemap.arrayToCSV(data2,40),FlxTilemap.ImgAuto,0,0,FlxTilemap.AUTO) add(level) break I thought that I would need to first call remove on level to take it off the stage, and then call add on it, however, when I do that, the tilemap does not show up at all. What is the correct way to do this?"} {"_id": 32, "text": "AS3 Starling in Fullscreen Mode cuts off most of the screen I have a mixed mode (classic Flash Renderer Starling) AIR AS3 project that I'm switching to fullscreen with stage.align StageAlign.TOP LEFT stage.scaleMode StageScaleMode.SHOW ALL Swtich to Fullscreen with stage.displayState StageDisplayState.FULL SCREEN INTERACTIVE When I do this, I have a callback on the Event.RESIZE event to resize my Starling instance to fullscreen private function resizeStarling(e Event) void var size Point new Point() if(this.stage.displayState StageDisplayState.FULL SCREEN INTERACTIVE) size.x Capabilities.screenResolutionX size.y Capabilities.screenResolutionY else size.x WIDTH size.y HEIGHT RectangleUtil.fit( new Rectangle(0, 0, stage.stageWidth, stage.stageHeight), new Rectangle(0, 0, size.x, size.y), ScaleMode.SHOW ALL, false, Starling.current.viewPort) The set to FULL SCREEN INTERACTIVE turns all my normal flash Stage object based UI and visuals to full screen mode. However, while the Starling graphics are correctly upscaled, they only occupy the upper left corner of the screen, and the remaining three quadrants are cut off. I haven't validated yet, but I suspect that the segment being displayed is the same dimensions as the original windowed stage size. Any ideas on what I'm forgetting to do to achieve fullscreen Starling displays that are actually fullscreen? This is on OSX."} {"_id": 32, "text": "As3 Character movement in diffrent directions with labels? I hope you can help me with the following problem I made a character in Illustrator. The player sees the character from above. When you press the left arrow key character.gotoAndStop('left') the character moves to the left. (Same goes for the right direction with label 'right' When you release the left or right arrow key (upKey) the character goes back to the label 'up'. I'm trying to accomplish the following When the character is facing down ('down'). the left key should go to the (\"facingdownleft\") label and on release back to the label ('down'). (Same for the right direction) stage.addEventListener(KeyboardEvent.KEY DOWN, downKey) function downKey(event KeyboardEvent) if(event.keyCode 39) isRight true character.gotoAndStop('right') if(event.keyCode 37) isLeft true character.gotoAndStop('left') if(event.keyCode 38) isUp true character.gotoAndStop('up') if(event.keyCode 40) isDown true facingdown true character.gotoAndPlay('down') if( facingdown true amp amp isLeft true) character.gotoAndPlay('downleft') stage.addEventListener(KeyboardEvent.KEY UP, upKey) function upKey(event KeyboardEvent) if(event.keyCode 39) isRight false character.gotoAndPlay('up') if(event.keyCode 37) isLeft false character.gotoAndPlay('up') if(event.keyCode 38) isUp false if(event.keyCode 40) isDown false I made a boolean for facingdown and an if statement for downleft if( facingdown true amp amp isLeft true) character.gotoAndPlay('downleft') But before I make numerous amounts of if statements again, I would like to know if I'm on the right track and if you can help me accomplish this? Thank you so much in advance and feel free to ask questions."} {"_id": 32, "text": "Flash server, protocol protection I am making a flash game that will interact heavily with the server. For quite some time already I am using 'request hashing' technique to make sure that request data hasn't been tampered with. This works pretty well. However, in this game I'd like to go a little bit further and completely hide the protocol from the observer (right now it's plain JSON). I imagine that I could zip and encrypt data (using one of symmetric algorithms). That would make it pretty unreadable by human, right (also smaller)? And SWF encryption obfuscation should protect the encryption key (it is being done anyway). As a side benefit that will also protect dynamically loaded resources from directly saving them to disk (or copying from the cache). Questions are there tools that allow you to simply dump the SWF with all its content, received and decrypted? If yes, this will render 'the side benefit' invalid. do you think it's worth it to burn all that CPU power? To support my point, I will say that I like to inspect data being exchanged between client and server. And occasionally I find a bug or two which I can use to my benefit. But then there was a game that was sending and receiving some binary data. Being a lazy attacker, I decided not to analyze further. Otherwise, who knows what I could find ) Comments, ideas, criticism, suggestions? )"} {"_id": 32, "text": "Using timer to reverse enemy movement in Flash game made with Flixel I am creating a 2d flash game using Flixel 2.5 in Flash Builder. I am trying to reverse enemy movement on an interval so that they will move back and forth over a set space. I felt that a timer would be best for this situation. The enemy class extends FlxSprite. I have three class level variables to help with managing the sprite's direction private var movementTimer Timer private var movementTimerEvent TimerEvent private var forward Boolean public var directionSet int 0 In the constructor, I instantiate the timer like this create timer for movement movementTimer new Timer(3000) set listener for movement movementTimer.addEventListener(TimerEvent.TIMER,SetDirection) start timer movementTimer.start() set initial direction forward true The function called on the timer interval is as follows Reverse direction of this sprite public function SetDirection() void directionSet increment direction set for debug purposes FlxG.log(\"direction set\") FlxG.log( directionSet) if(this. forward) this. forward false set the direction the sprite is facing this. facing RIGHT else this. forward true set the direction the sprite is facing this. facing LEFT Then, the update function evaluates the forward flag to determine direction of movement Update this sprite override public function update() void super.update() if(this. forward) this.acceleration.x this.maxVelocity.x .5 else this.acceleration.x this.maxVelocity.x .5 However, my sprite is not reversing direction, it just continues forward. What am I missing? EDIT I added additional variables and calls to FlxG.log for debugging purposes, and it seems that SetDirection is never called, but I am not sure why."} {"_id": 32, "text": "Sprites are sometimes blurry in Flash I am playing around with drawing an SVG sprite (imported in through Embed ). Depending on the coordinates of the image, sometimes it appears more crisp than others. The following image shows how at different locations is it rendered differently (Image link You may have to download and zoom in with an image editor to see it) You'll notice that the middle sprite is more blurry than the ones on the sides. Does anyone know why this is? Any help would be appreciated."} {"_id": 32, "text": "Affect movieclip scale from a .as doc to another I've been working on a game following a tutorial on the internet, the game is an avoider where you have the Avatar, that has to avoid the objects that fall. The way it is made is I have a DocumentClass which addChild's the screen you should be seeing and removeChild's the screen that you were. For example first it loads the menuScreen, then when you press play unloads menu and loads playscreen. When you die it loads the gameoverScreen and loads the playscreen. And from the gameOverScreen you can press the SHOP button to go to the shop. From here on I'm on my own and not following any tutorials. The shop has a button that is supposed to alter the Avatar's X and Y scale to 0.5, but the problem is how do I make that work? I tried creating a sharedObject.data.avatarSize, on the store's size button the code would be something like sharedObject.data.avatarSize 0.5 And on the AvoiderGame.as, which is the most of the actual game, on the part where the avatar is created I tried putting this after it's creation scaleX.avatar sharedObject.data.avatarSize scaleY.avatar sharedObject.data.avatarSize This did not work since it gives me the error 1009 saying can't access something that is null. I tried this before \"using\" the sharedObject if( sharedObject.data.avatarSize null ) sharedObject.data.avatarSize 1 But it did not work... So now I'm not sure on what to do. I know we should reduce global variables as much as we can but how do I do it? EDIT Also, if it helps, I'm using Flash CS5 and working with AS3.0 and if you don't know about flash, you can also tell me how you would do it on any other language and I would try to convert it to flash."} {"_id": 32, "text": "Large Sprite Performance I've got a large Sprite generated using a set of vertices(x,y coordinates) and a bitmap pattern (using moveTo, lineTo, beginBitmapFill, endFill ...etc). It's about 15000 pixels wide and between 1500 2000 pixels high depending on the level it's the terrain for a 2D game. My question is what is the best way to display move it on the stage performance wise? Currently I'm just adding it to the stage as is...I get decent frame rate memory cpu usage but I want to optimize it for slower PCs. Any ideas? I've been reading a little about blitting but I'm not sure how to implement it in my case. Thanks."} {"_id": 32, "text": "How should I do my collision response? I'm making a small lockpicking simulator. Obviously I'll need the pick to not pass through the lock, and I'll need the pins to move when you tap or push them with the pick. Here's what I have so far, just to give you an idea. http megaswf.com serve 2433982 As you can see, the collision detection is pixel perfect. I've looked into a couple of different ways of doing collision response, but it seems like such a vast and complicated field. Any time I come up with a possible solution I start noticing flaws like what would happen if more than two objects collided and so on. I've looked into physics engines like Box2D, but it seems like such overkill considering the, I think, simple nature of the game I'm trying to make. I don't like the idea of using a huge library that I don't even begin to understand just because I can't figure out how to do collision response. But I just don't know where to begin. Maybe I will have to use a library. If anyone with experience could, based on that demo and what I'm trying to do, suggest a course of action, I'd really appreciate it."} {"_id": 32, "text": "Fixed timestep with interpolation in AS3 I'm trying to implement Glenn Fiedler's popular fixed timestep system as documented here http gafferongames.com game physics fix your timestep In Flash. I'm fairly sure that I've got it set up correctly, along with state interpolation. The result is that if my character is supposed to move at 6 pixels per frame, 35 frames per second 210 pixels a second, it does exactly that, even if the framerate climbs or falls. The problem is it looks awful. The movement is very stuttery and just doesn't look good. I find that the amount of time in between ENTER FRAME events, which I'm adding on to my accumulator, averages out to 28.5ms (1000 35) just as it should, but individual frame times vary wildly, sometimes an ENTER FRAME event will come 16ms after the last, sometimes 42ms. This means that at each graphical redraw the character graphic moves by a different amount, because a different amount of time has passed since the last draw. In theory it should look smooth, but it doesn't at all. In contrast, if I just use the ultra simple system of moving the character 6px every frame, it looks completely smooth, even with these large variances in frame times. How can this be possible? I'm using getTimer() to measure these time differences, are they even reliable?"} {"_id": 32, "text": "flash hitTestObject() mafunction? Is there a way that even though two objects that have different y co ordinate collide? In my game, I wanted to make my object rotate as explained in previousquestion. When I added the code, the object now dissapears from the scene even though it's x and y co ordinate are in the scene. I traced(in the function that kills the characer if it touches it. i.e hitt) the x and y value of the object and found that it is still there on the scene. The code is ground.addEventListener(Event.ENTER FRAME, hitt) function hitt(event Event) if (green.hitTestObject(ground) blue.hitTestObject(ground) brown.hitTestObject(ground) black.hitTestObject(ground)) dead true else if (kill.hitTestObject(black) kill.hitTestObject(green) kill.hitTestObject(blue) kill.hitTestObject(brown)) dead true trace(\"here\",kill.y,green.y,green.x) The output is SWF hello.swf 519178 bytes after decompression here 608.95 401 62.55 I don't know what's going on? Please Help..!!"} {"_id": 32, "text": "Is flash game development not considered 'proper' game development? I've come across this a couple of times. That flash game development is not 'proper' game development when compared to XNA or even Unity. Mentioned here Need guidelines for studying Game Development Also here in some comments Where to start with game development? This judgement also befalls java, according to some. Is it because in flash its so easy to draw graphics and to import and add on to the stage any element we want and also because flash needs a 'container program' to run and others don't? But flash is by far way easier to 'distribute' than any other of those mentioned above. Maybe except for iphone or android games."} {"_id": 32, "text": "Need help in determing what, if any, tools can be used to create a free Flash game Yes I proudly and sadly declare that I am a complete nincompoop when it comes to Flash, and I have been fishing around the big wide web for information. The reason for this is that I have been contracted to create a game(s) for a website the usual flash based games caveat. Please I do not mean things like by those gaming generator websites, I mean small yet professional games but the caveat, as always, is that impossible dream it needs to be done all for free. The budget...well imagine it as not there. Annoyingly is that I am a game designer yes, but with a ridiculously tight deadline I haven't got much time to re learn (ah the heady days of programming at uni) everything by the end of March, so I'd like to ask some people who know their stuff rather than keep looking at a gazillion different things. This is my understanding with the flash sdk you can create a game, albeit you need to be pretty programming savvy. FlashDevelop helps there yet I am not entirely sure how. Yet even FD says to use Flash for the animation graphics. Yes its undeniably powerful but as I said there is the unattainable demand of no money. The million dollar question what, if any, tools can I use to create a free flash game?"} {"_id": 32, "text": "Tile based maps in AS3 I want to make a tile based platformer in AS3. I want my game to read an external maps file (in xml or json or somethimg similar) to draw a tile based map. I've seen loads of tutorials for this in AS2 and other languages, and the few I've found in AS3 are either incomplete or filled with extra unnecessary features. I just want to be able to draw a basic map from sprites in Flash. Any links or information to point me in the right direction would be appreciated."} {"_id": 32, "text": "How to add a ramp in a flash game? I am a huge novice and this isn't really a programming question, but here I go, say I want to make a game that involves rolling up a ramp like this one to move upwards, similar to how it would work in an old Sonic the Hedgehog game or something, how would I go about doing that, where could I find a good recourse to learn this?"} {"_id": 32, "text": "Required Security Precautions for Flash AS3 Multiplayer Game I have created a couple of games in Flash AS3 and am playing with programming a flash based multiplayer (possibly mmo?) game where the application will communicate with a server over a socket connection. Obviously I need some form of authentication (username and password) but what other security precautions do I need to explore to prevent cheating?"} {"_id": 32, "text": "What is the standard way of delivering HTML5 games to portals and such? Let me explain what I mean by \"standard way of delivering\"... Think about Flash games sites. Flash games can be delivered as a single file, either hosted by the site, or, I guess, provided by someone else. HTML5 games, on the other hand, don't have something so standard. Usually, they have their own page, and portals just link to that page. I think that it greatly hinders the purpose of that portal, because, well, you want people to stay on your site and look for other games. Now, I think that a some kind of iframe way of delivering games would help solve this problem greatly. I saw some games doing that, and they were often included on tutorial sites to show a live example, which is obviously a great thing. So, is there a standard at all? Any suggestions? Can you create a game that just preloads itself in an iframe (I heard something about a \"single document\" or something)?"} {"_id": 32, "text": "Are there any command line swf packing tools? I want to packing image files(png, jpg) into swf, then game can load files easily. But I want to do this by a Makefile, not FLASH CS. Do you know any command line swf tool set can do that? And can I packing XML files into it as well?"} {"_id": 32, "text": "Large Sprite Performance I've got a large Sprite generated using a set of vertices(x,y coordinates) and a bitmap pattern (using moveTo, lineTo, beginBitmapFill, endFill ...etc). It's about 15000 pixels wide and between 1500 2000 pixels high depending on the level it's the terrain for a 2D game. My question is what is the best way to display move it on the stage performance wise? Currently I'm just adding it to the stage as is...I get decent frame rate memory cpu usage but I want to optimize it for slower PCs. Any ideas? I've been reading a little about blitting but I'm not sure how to implement it in my case. Thanks."} {"_id": 32, "text": "Beginner flash game development Start with framework or from scratch? I want to write some simple flash games (as a hobby). I have a lot of programming experience, but no experience with Flash ActionScript. My question is As a beginner, is it a good idea to start with a framework like Flixel, FlashPunk or PushButton or would it be better to write my first games from scratch? Also, if you vote for using a framework, which one would you recommend? What are the differences? And another question What about Flex, would you recommend using it?"} {"_id": 32, "text": "How can I save a global high score for all players in AS3? I am developing a game in which I want to make a scoring system where the global high score is stored and shared by all players. I am using Flash and ActionScript 3. Until now I've used SharedObject.getLocal(\"savename\") for saving score individualy but I cant figure out the way to store a common high score for all players."} {"_id": 32, "text": "Movie clip in a button changes on hover I have a button for my game which has a MovieClip in it. It consists of an image of a lock and an image of an item, representing the item being locked and unlocked. I make the button become slightly smaller when the mouse is over it to create the effect of a button slightly down. For some reason, however, this makes the MovieClip in the button go to the next frame. I have no Actionscript code in the button or any frame except stop() on the first frame of the MovieClip, so I really don't understand why this would happen. It only goes to the next frame when I hover my mouse over the button and then quickly goes back to the first frame (since there's no stop() in the second frame). After experimenting with stop() in both frames of the movie clip, it does indeed only happen when my mouse enters the button. Leaving the button doesn't do anything and the button left alone doesn't do anything. It just changes the frame when I hover my cursor over it. There's absolutely no script involved aside from stop() in the first frame of the movie clip in the button. What could be the cause of this problem?"} {"_id": 32, "text": "Camera and enemy behaviour in AS3 platformer beginner in AS3 here. I am working on a platformer game based on the code of a provided example exercise. I have the following problem I have an enemy who shoots bullets. The enemy is the parent, and the bullet are the child. When I move to the next scene (level), the bullets are still there, but invisible, even using the removeEventListener to shut down the bullet hit check. Here is the code of the child \"disparoEnemigo mov\" addEventListener(Event.ENTER FRAME, fl MoveEnemyShot) function fl MoveEnemyShot(event Event) try if (enemy shot.y lt 300) if (enemy shot.hitTestObject(Object(this.parent).mario)) variablesGlobales.variables().vidas 1 Object(root).texto.text variablesGlobales.variables().vidas.toString() trace(\"vidas \" variablesGlobales.variables().vidas) if (variablesGlobales.variables().vidas lt 1) MovieClip(this.parent).gotoAndStop(2) this.parent.removeChild(this) removeEventListener(Event.ENTER FRAME, fl MoveEnemyShot) else enemy shot.y 3 else trace(\"LLEGADA\") removeEventListener(Event.ENTER FRAME, fl MoveEnemyShot) this.parent.removeChild(this) catch (error Error) removeEventListener(Event.ENTER FRAME, fl MoveEnemyShot) import flash.events.Event import flash.media.SoundMixer addEventListener(Event.ENTER FRAME, fl EnterFrameHandler) function fl EnterFrameHandler(event Event) void try if (this.hitTestObject(Object(this.parent).mario)) SoundMixer.stopAll() var sound gameOver new gameOver() sound.play() Object(this.parent).mario.y 1000 Object(this.parent).mario.x 15 trace(\"Mario dies\") var cartel StageLose new StageLose() stage.addChild(cartel) cartel.x 85 Object(this.parent).mario.y 1000 catch(error Error) removeEventListener (Event.ENTER FRAME, fl EnterFrameHandler) And this is the code of the parent, \"enemigo mov\" var leftPressed Boolean true var rightPressed Boolean false stage.addEventListener(Event.ENTER FRAME, fl MoveEnemy) function fl MoveEnemy(event Event) try if (leftPressed) enemy1.x 0 if (enemy1.x lt 120) leftPressed false rightPressed true else if (rightPressed) enemy1.x 1 if (enemy1.x gt 120) rightPressed false leftPressed true var number Number Math.random() if (number lt 0.05) amp amp variablesGlobales.variables().coleccionEnemigos.indexOf(this) ! 1) trace(\"creation\") var disparo disparoEnemigo mov new disparoEnemigo mov() this.parent.addChild(disparo) disparo.x enemy1.x 115 disparo.y enemy1.y 115 disparo.z 50 trace(disparo.x \" \" disparo.y) catch(error Error) removeEventListener(Event.ENTER FRAME, fl MoveEnemy) In both codes, \"mario\" is the player character. What I need to do is to stop the bullet creation of \"\"disparoEnemigo mov\" when we move to the next scene. Shouldn't the \"removeEventListener(Event.ENTER FRAME, fl MoveEnemy)\" line stop the bullets to check if there is any collision with the player? Any help or resource will be helpful. Thank you so much!"} {"_id": 32, "text": "How to add a ramp in a flash game? I am a huge novice and this isn't really a programming question, but here I go, say I want to make a game that involves rolling up a ramp like this one to move upwards, similar to how it would work in an old Sonic the Hedgehog game or something, how would I go about doing that, where could I find a good recourse to learn this?"} {"_id": 32, "text": "Use of FlxG.camera.follow to follow a character vertically I am developing a prototype for a game in Flixel in which a character floats upward continually to traverse the level. I would like to have a \"tall\" layout for levels and set the FlxG.camera to follow the character as he floats upward. My issue is in understanding the proper use of FlxG.camera. I have my game constructor coded as follows package import flash.display.Sprite import org.flixel. SWF(width \"640\",height \"480\",backgroundColor \" 000000\") public class MyGame extends FlxGame public function MyGame() super(320,240,PlayState,2) forceDebugger true In the override of create() in the PlayState.as file I attempt to set the camera to follow the player as follows public var TheClimber BalloonHero override public function create() void set background color FlxG.bgColor FlxG.BLUE Set data for player TheClimber new BalloonHero(FlxG.width 2 5,480) Add camera and set it to follow The Climber which will automatically set the boundaries of the world. FlxG.camera.setBounds(0,1280,640,1280,true) FlxG.camera.follow(TheClimber,FlxCamera.STYLE PLATFORMER) add player to the game add(TheClimber) I assumed this would set the camera bounds to twice the height of the SWF background(i.e. the FlxG height) and then scroll the background along with the specified FlxObject(TheClimber in this case) until it had reached the height of the game. However, I must be going about it incorrectly because when the zoom is 2 and the game height 720 the camera starts at the top of the screen with the player character not visible at the bottom of the game height. Is there a way to start with the camera game focused on the bottom of the game object(FlxG.height) ? Or am I going about this the wrong way and have other issues with the way I am using the camera? Thanks in advance."} {"_id": 32, "text": "Examples of good Javascript HTML5 based games Now that Flash is largely being replaced with HTML5 elements (video, audio, canvas, etc.) are there any good examples of web based games built on completely open standards (meaning Javascript, HTML and CSS)? I see a lot of examples of pure HTML5 implementations of what was once only in Flash (like stuff here http www.html5rocks.com ) but not many games, a domain which still seem dominated by Flash. I'm curious what's possible and what the limitations are."} {"_id": 32, "text": "Rotation of objects from different axes in Flash AS3 In my game, I have made 4 lines with different colors to form a square but the colored lines are different objects. I want to rotate the lines in a way that the lines will still form a square. Eg But I'm only able to rotate them on the central axis, so, it forms a cross The code for leftPressed is if(leftPressed) black.rotation 90 blue.rotation 90 yellow.rotation 90 red.rotation 90 So, I need to know how to rotate objects on different axes."} {"_id": 32, "text": "Splitting a large number of FLAs into multiple gifs I currently have a large number (300 or so) FLAs that I wish to convert to GIFs for a HTML5 game I'm creating. Each one of these FLAs contains multiple animations in the timeline, and they all have the same basic structure (Animation one in frames 1 25, animation 2 in frames 26 34, etc.) Is there a way I could automate splitting them up and converting them into the GIFs? I am on a Mac, but do have access to a Windows machine, so any solution will work, basically. I don't have the Windows version of Flash though, so that is annoying. Thanks in advance, and if this the wrong StackExchange to ask in, then I apologise in advance."} {"_id": 32, "text": "Stage3D Camera pans the whole screen I am trying to create a 2D Stage3D game where you can move the camera around the level in an RTS style. I thought about using Orthographic Matrix3D functions for this but when I try to scroll the whole \"stage\" also scrolls. This is the Camera code public function Camera2D(width int, height int, zoom Number 1) resize(width, height) zoom zoom public function resize(width Number, height Number) void width width height height projectionMatrix makeMatrix(0, width, 0, height) recalculate true protected function makeMatrix(left Number, right Number, top Number, bottom Number, zNear Number 0, zFar Number 1) Matrix3D return new Matrix3D(Vector. lt Number gt ( 2 (right left), 0, 0, 0, 0, 2 (top bottom), 0, 0, 0, 0, 1 (zFar zNear), 0, 0, 0, zNear (zNear zFar), 1 )) public function get viewMatrix() Matrix3D if ( recalculate) recalculate false viewMatrix.identity() viewMatrix.appendTranslation( width 2 x, height 2 y, 0) viewMatrix.appendScale( zoom, zoom, 1) renderMatrix.identity() renderMatrix.append( viewMatrix) renderMatrix.append( projectionMatrix) return renderMatrix And the camera is send directly to the GPU with c3d.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 0, cameraMatrix, true) And these are the shaders Vertex Shader m44 op, va0, vc0 mov v0, va1.xy mov v0.z, va0.z Fragment Shader tex ft0, v0, fs0 lt 2d,linear,nomip gt mov oc, ft1 Here is a example and here are two screenshots to show what I mean How do I only let the inside of the stage3D scroll and not the whole stage?"} {"_id": 32, "text": "Can a texture's UV coordinates be animated (scrolled) when part of a SpriteSheet? Alright so my question is about texture manipulation in Flash Stage3D Context3D using AGAL for the shader language. But I'm pretty sure this could be applicable in other situations involving GPU programming. So the goal is, if I wish to have a \"scrolling\" animation on a certain tile (like a tile of water), can I still have that texture packed along with all the rest of my sprite assets? Or does it have to be alone to avoid bleeding nearby assets? From what I can understand, when the FragmentShader samples the portion of the texture offsetted during a scroll animation, any coordinates outside the desired texture will reveal incorrect nearby textures. Some example to clarify Fluid motion (lava, water waves, acid bubbles) Background motion (cloud, trees, houses) Directional indicators (lines on a conveyor belt, race circuit dash regions) Do I need to use some extra operations to wrap the texture if it tries to sample beyond a certain point? How could those constraints be defined transferred to the FragmentShader? UPDATE To clarify, I would like to scroll only on 1 single tile that would be part of a SpriteSheet TextureAtlas (meaning, mixed with other existing sprites part of a game project). Imagine you had something like this (but better artwork, of course) So a 256 x 256 Texture with a \"Wavy Water\" tile in the top left corner (128 x 128 in dimensions). How would you write a shader that can scroll through ONLY the water portion to give a sense of motion without running over the adjacent textures (ex faces and cars). How would you handle situations where the Quad is much larger than the texture and could repeat many times as well in combination to being able to scroll it?"} {"_id": 32, "text": "How can I develop Flash games without expensive software? I've been playing with writing flash games in my spare time, but up to this point, I've just been using a trial version of Adobe Flash Professional. I'm aware of FlashDevelop, but their documentation is basically non existent when it comes to the workflow of developing purely with FlashDevelop. Does anyone know of any good tutorials for developing Flash games purely with FlashDevelop? Alternatively, does anyone have any other free cheap software recommendations to use in place of Flash Professional?"} {"_id": 32, "text": "Should all stats only exist on MySQL database for my Flash browser RPG? I'm creating a browser RPG in Flash which will have some multiplayer elements and in app purchases so security is a high concern. Would it be better to have all game stats like health and such exist only in the MySQL database and retrieve them every time I need them? The game is turn based, but that would still require very frequent connections to the database. I could use local copies to cut down on the number of connections, but I imagine that would make it much easier for people to cheat."} {"_id": 32, "text": "Host Migration (P2P) with RTMFP and AS3 I was wondering if this is a possibility with RTMFP since it acts like UDP P2P.. Host Migration Player A starts and host a game.. Player B and C connects.. Player A quits.. Player B is now assigned as new host server Game not interrupted or disconnected. Maybe some basic example on how this is done with RTMFP AS3?"} {"_id": 32, "text": "Make colour change depending on time I'm making a Flash game (ActionScript 3) and for dynamics I'd like to make the background change colour depending on the clients' time of day. I have a rough idea on how I want to do this, At sunrise, I want the background to be yellow orange In the middle of the day, I want the background to be cyan clear sky colour At sunset, a reddish orange During the night, a navy blue. I will be using this method to change the colour of the symbol, which is at default a dark grey colour. (unless someone points out a better way to do this). This means I have access to the red, blue and green components of the background. On implementing the system itself I suppose I could simply get the client time and do if (hour gt 9) and (hour lt 18) colour SKY BLUE and similar for the other times of day, but I'd like it to tween slowly between colours as time progresses. For example, if 6AM is yellow orange and 9AM is blue, 7 30AM would be yellow moving towards blue. I have a feeling I need to come up with an algorithm to link time to the RGB components of the colour, but I've always been terrible at maths and I can't think of how to do this, so that's why I'm asking. Please tell me how I would do this, both concept outlining and sample code, or even just tips are welcome. )"} {"_id": 32, "text": "Change the tilemap shown on stage in Flixel I am building a simple platformer using Flixel, beginning with the source code from Flixel creator's EZPlatformer . I would like to adjust the level's tilemap when the player sprite enters overlaps with a sprite representing a door. I use Flixel's built in function to track if the player overlaps the door sprite. exits is a class level variable public var exits FlxGroup I call this function in the Update event to check for overlap FlxG.overlap(exits,player,UpdateScreen) I successfully catch when they overlap, however when I try and load the new tilemap, the old one continues to show. I use this function to attempt to update the tilemap on the screen public function ChangeScreen() void load the screen and locations of sprites(e.g. player, exits) based on current screen switch(currentScreen) case 1 load tilemap level new FlxTilemap() level.loadMap(FlxTilemap.arrayToCSV(data1,40),FlxTilemap.ImgAuto,0,0,FlxTilemap.AUTO) add(level) break case 2 load new tilemap level new FlxTilemap() level.loadMap(FlxTilemap.arrayToCSV(data2,40),FlxTilemap.ImgAuto,0,0,FlxTilemap.AUTO) add(level) break I thought that I would need to first call remove on level to take it off the stage, and then call add on it, however, when I do that, the tilemap does not show up at all. What is the correct way to do this?"} {"_id": 32, "text": "How can I manage an animated UI from ActionScript? I'm trying to code a game of Poker in AS3, using Flash Professional CS5 (although I try to keep as little code as possible in the .fla). When a player bets, for example, I need to be able to show an animation of some chips sliding into the center of the screen. After that happens, the AI decides what to do, and another animation of their chips occurs. Then a menu pops up so the player can choose their own next action. And so on. I started writing a UIBet interface with bet(amount) and raise(amount) methods and so on, that you would implement with a class extending MovieClip and fill in the methods with gotoAndPlays to various animations. But if I just have code that calls these graphics object like so playerUIBet.bet() aiUIBet.bet() menu.prompt() Then, if I understand Flash correctly, what'll happen is that the code will finish executing, and then all of those animations will happen simultaneously. How can I get these animations to happen sequentially? What if I want to insert pauses between them? Some kind of solution like this? What's the best way to do this in AS3?"} {"_id": 32, "text": "Level Design Char Traveling to and from a Site I'm developing a 2d platformer game where your character can travel to and from sites as he pleases. To travel to and from these sites the character must travel along a path between his current location and his destination (see illustration below). And of course the idea is that you can travel through the level backwards if you wish to return to Site One. But as you probably realize, doing this may provoke some serious problems, and will put limitations on the level design (no cliffs or long drops because then your character wouldn't be able to overcome them on the way back). I've come up with multiple ways to overcome this (such as designing two levels for the same path etc), but I was wondering if anyone else has any creative work arounds for this problem. Any help and advice is appreciated."} {"_id": 32, "text": "Fixed timestep with interpolation in AS3 I'm trying to implement Glenn Fiedler's popular fixed timestep system as documented here http gafferongames.com game physics fix your timestep In Flash. I'm fairly sure that I've got it set up correctly, along with state interpolation. The result is that if my character is supposed to move at 6 pixels per frame, 35 frames per second 210 pixels a second, it does exactly that, even if the framerate climbs or falls. The problem is it looks awful. The movement is very stuttery and just doesn't look good. I find that the amount of time in between ENTER FRAME events, which I'm adding on to my accumulator, averages out to 28.5ms (1000 35) just as it should, but individual frame times vary wildly, sometimes an ENTER FRAME event will come 16ms after the last, sometimes 42ms. This means that at each graphical redraw the character graphic moves by a different amount, because a different amount of time has passed since the last draw. In theory it should look smooth, but it doesn't at all. In contrast, if I just use the ultra simple system of moving the character 6px every frame, it looks completely smooth, even with these large variances in frame times. How can this be possible? I'm using getTimer() to measure these time differences, are they even reliable?"} {"_id": 32, "text": "Water simulation in Isometric game I'm creating a game in Flash AS3 in which the player needs to modify land in order to direct the water in the right direction. However, water simulation is a new topic for me and I'm kinda stuck. It doesn't have to be like realistic water, with ripples and stuff, but it has to flow, and if there's enough water, it needs to rise. I've thought up two different types of water A Spring Infinite source of water. Used for simulating seas and stuff. Water block Just one unit of water. My current implementation shows how I'd like the water to spread, but it doesn't rise, and doesn't allow for finite water. Also, the spreading isn't accounting for any amount of water, it just duplicates instead of actually moving units of water. I'm curious to how you guys would solve this problem. Any examples pseudo code is always appreciated. Current version http dl.dropbox.com u 319897 ProjectWater.swf You can manipulate the land by pressing left mouse. And can simulate one step of water at a time by pressing A. Source of the water part http pastebin.com Js2kYt4y"} {"_id": 32, "text": "How to build a bones animation engine? I want to develop a flash game. It would draw a stick man, and edit his pose. I think what I need to learn are bones animation and physics engine. Can anyone introduce some good resources to learn both?"} {"_id": 32, "text": "How can I develop Flash games without expensive software? I've been playing with writing flash games in my spare time, but up to this point, I've just been using a trial version of Adobe Flash Professional. I'm aware of FlashDevelop, but their documentation is basically non existent when it comes to the workflow of developing purely with FlashDevelop. Does anyone know of any good tutorials for developing Flash games purely with FlashDevelop? Alternatively, does anyone have any other free cheap software recommendations to use in place of Flash Professional?"} {"_id": 33, "text": "Improving shading of procedurally generated pixel art sprites I've been working on a sprite generator and I'm having a hard time figuring out how to add shading automatically. Here are some examples of the generated sprites Currently what I'm doing is checking where a flat color meets a dark boundary, and then applying either a highlight or a shadow depending on the direction. This is of course really boring. I've tried searching for other methods, but all I could find were AI examples. Does anyone know of any particularity simple yet clever ways of adding shading automatically? I've thought of expanding the check up to 5 cells, and using a set of pre determined patterns to generate the shading, but I'm just not too sure"} {"_id": 33, "text": "Tiled map editor and objects Ive been searching for an easy way to group multiple sprites of a spritesheet into a single entity. Im using tiled editor as written at the title. Some objects might be larger than the tile size and i need a way to let my game know that in order to manipulate these objects. I dont want to create new tilesets with different sizes for all objects. Is this possible in this app and if not do you know another that can handle this?"} {"_id": 33, "text": "How to set a static size for an object in GameMaker? I have many sprites with different sizes, and I have an object in which I set those sprites, but this object gets resized by the currently displayed sprite. How can I set a fixed size for the object so that it can no longer change size? Thanks for any help."} {"_id": 33, "text": "libgdx sprite position relative to body Apologies if this is a reiteration, as I couldn't find another discussion of this over the past couple days. Issue I'm using libgdx and box2d, and I'm currently updating the sprite's position to the body's current position every render call. Using a debugRenderer to see the bodies, I see that there is fairly noticeable lag between the movement position of the body and the sprite that is being moved relative to it. Question Is this lag normal, possibly to perform collisions ahead of time? If not, should I be manipulating relating the positions differently? Thanks in advance! Solution This was a coding error on my part. Pointed out by a good reply below, I was updating the position of the sprite relative to the body and then stepping the physics. Thus never actually setting the sprite to the body's CURRENT position. Thanks!"} {"_id": 33, "text": "Use an external sprite or image file in flixel game in flashbuilder Is there any way to use an external image sprite file for the graphic of a FlxSprite instance? Say I declare my player FlxSprite as follows player new FlxSprite(FlxG.width 2 5) player.makeGraphic(10,12,0xffaa1111) How could I instead instantiate the FlxSprite using my own spritesheet or image? I have seen others do it in the Flixel demos , and in the featured games."} {"_id": 33, "text": "Separate objects for hitbox and sprite? I am making a technically top down game with a shifted perspective. It shows more of the characters side, not just above their head. I think most \"top down\" games have a similar art style. Due to this, only the bottom of the character sprite should collide and interact with game objects. Should I use two separate objects for the hitbox and the sprite? It seems inefficient to do this. Is there some other solution? For reference, I am using python3 and the pygame library. I am using the sprite class from pygame. My player class inherits from the sprite class and is comprised of a surface object for the sprite image, and a rectangle object for the coordinates and length width. Using a separate object for the hitbox and sprite would require to classes for this."} {"_id": 33, "text": "How to decide sprite size for isometric tile textures? When I draw these textures on screen, I put them in a sprite and specify a width and height to draw the sprites in like this new Sprite( width 10, height 10, texture greenTileTexture ) This draws the sprite at size 10x10 on screen. Let's say I want to have tile size of 10. I use this This is the size of the textures as in png. let textureWidth greenTileTexture.width let textureHeight greenTileTexture.height let textureRatio textureWidth textureHeight This is the size that draws on screen. let spriteWidth 10 let spriteHeight 10 textureRatio Now for the 3x2 tile I don't know what the width should be since it takes more tiles. I want to draw isometric tiles with arbitrary tile sizes. For example above picture there are 1x1 and 3x2 sized tiles. The textures have arbitrary height because of decoration. a is the tile's height b is texture's height c is tile's width. I can't figure out what the sprite size should be when I lay these out on screen. Maybe I should have exact tile sizes cover the whole texture without decorations (a b). But still what the sprite size should be?"} {"_id": 33, "text": "pygame avoiding sprite 'jitters' on rotating the image Is there a common trick for getting around sprites that are changing directions 'too quickly' and causing their sprite to display erratically? In this project, the player moves in 8 directions by determining the abs() distance between the mouse's X and Y coordinates and its own obj.rect.center. If the absolute value is less than obj.speed, it simply moves to that point. If it is greater, it moves the distance its speed allows it to move in that direction. When it's time to draw the sprite, PyGame rotates it in accordance to obj.direction by using a dict called SPINNER with stored default values to pass to pygame.transform.rotate. def draw(obj) drawImg pygame.rotate.transform(obj.img, SPINNER obj.direction ) drawCtr drawImg.get rect(center obj.rect.center) DISPLAYSURF.blit(drawImg, drawCtr) This is fine for the foolish AI characters which typically make very few course corrections however, small movements of the mouse can cause the player's obj.direction to update very quickly, which looks chaotic. Is there a simple way to curb this behavior? My first guess is to bog down the player object with values that retain its previous state and then determine the amount of rotation to apply, but I have a feeling the better solution is to assign that responsibility to the 'view' and not the 'model'. I'm not sticking to any hard and fast rules regarding MVC, but I am trying to engage in enough separation of concerns that 'view like methods' don't make 'controller like' changes to 'model like' objects, if that makes sense."} {"_id": 33, "text": "PYGAME Sprite movement seize to function when entire X and Y span is reviewed I've created an sprite class that has a detection radius checking if the player enters the zone. If yes, the sprite moves towards the player. It works perfectly fine when the sprite checks for three directions (X is greater, X is lower, Y is greater lower), in other words, the sprite only moves up and down if all four directions are enabled.. Here is my code for the move function def move(self) target x, target y self.target.pos if self.mob wc 1 lt 24 if self.pos x lt target x self.vel vec(self.speed, 0) self.image self.game.orc mob walkRight self.mob wc 6 self.mob wc 1 elif self.pos x gt target x self.vel vec( self.speed, 0) self.image self.game.orc mob walkLeft self.mob wc 6 self.mob wc 1 if self.pos y gt target y self.vel vec(0, self.speed) self.mob wc 1 elif self.pos y lt target y lt if this condition is disabled self.vel vec(0, self.speed) The sprites move perfectly upwards self.mob wc 1 towards the player, shifting between moving On X and moving on Y. else However, if it is enabled, the self.mob wc 0 sprites ONLY move on the Y field Here is my code for the update function def update(self) self.rect self.image.get rect() self.rect.center self.pos self.pos self.vel self.game.dt self.pos x, self.pos y self.pos target dist self.target.pos self.pos if target dist.length squared() lt self.detect radi 2 self.move() else self.vel vec(0,0) self.image self.game.orc mob img For the way they move i followed this post. I am aware my build differs due to the use of vectors, which is something that i'm suspecting may be the cause of the issue. If anyone have any idea or tips to why this issue may occur, please tell me cause i've been sitting trying to fix this for 3 hours now.."} {"_id": 33, "text": "How can I get the width and height of a picture? I'm trying to make a script on RPG Maker XP that needs the width and height of an image to do some calculations. I tried picture.bitmap.widthand picture.bitmap.height but it returned the width and height of the image that is being shown in the screen. For instance, if the image is 800 pixels height, and the image takes 400 pixels in the screen, picture.bitmap.height will only return 400. This is the code I'm using picture Sprite.new picture.bitmap RPG Cache.picture(\"picture\") pictureWidth picture.bitmap.width pictureHeight picture.bitmap.height"} {"_id": 33, "text": "How to make a map surface object I'm making a 2d tile based game. In pygame I could create a map like this screen pygame.display(resolution) map pygame.Surface(width, height) for tile in all tiles map.blit(tile) screen.blit(map) The strength of this is that I can scroll the map by changing the map surface x and y. Also all the in game coordinates are conveniently set in relation to the map rather than the screen. However I can no longer use pygame, and I'm trying to switch to pyglet instead. As far as I can tell pyglet doesn't have an equivalent surface class built in, and therefore I need to build my own, this is what I need help with. I've used pygame.Surface extensively without really understanding how it works (python programmers these days huh). So I'm hoping you can offer some insight on how to get started. I know it needs a width and height, as well as some kind of list of the sprites which have been 'blitted' to it, and that moving the surface itself moves all the contained sprites, so surfaces blitted to it are somehow anchored to the surface rather than the screen. How is this stuff done in pygame, and how do we create a pyglet friendly version?"} {"_id": 33, "text": "Concerns about how to efficiently implement sprite atlas I currently transform (translate, rotate, scale) a bunch of vertices in my own Java code, then populate an mPositions array and an mTextureCoordinates array, which draws a bunch of different textured sprites to the screen in one GL draw command. Works great. However, I now wish to move the transformation process away from native Java code and over to the vertex shader, and so I will need to pass into the shader transformation matrices which encode the translation, rotation, and scaling operations for each sprite. Given my current approach the naive and obvious choice is to introduce another array mTransformations, passed into the shader via a GLES20.glVertexAttribPointer command, which contains a matrix for each and every vertex. But this way seems a little wasteful for two reasons I will have to add the same transformation matrix 6 times per sprite to the mTransformations array since each square sprite is made of 2 triangles (3 3 vertices) Since I'm now going to use the shader to perform the transformations, the 6 canonical coordinates of each square sprite (two triangles) will be the same for every sprite. In effect I'd have to populate mPositions with the same coordinates over and over for each sprite. Is there a more efficient way to do achieve what I want?"} {"_id": 33, "text": "How to handle 2d avatar creation I am new to game design and i am creating a MMORPG that allows players to create 2d avatars that can be customized. If i had lets say a male character model (no equipment no armor). How would i handle body variation for this male model? If this has been answered please provide link. I know layering customizing for equipment and armor has but not morphing the character sprite itself."} {"_id": 33, "text": "How to create custom methods for sprite groups in pygame? I want to use sprite groups in my game using pygame and the default draw isn't enough. I have tried some tutorials but I failed. So, being more specific I want to create custom methods for sprite groups in pygame such as .handle event (this method can exist at all sprites or not)."} {"_id": 33, "text": "Common practice when handling sprite animation Let's say I'm using the following sprite as a sample to try LibGDX Animation and TextureRegion. http www.smackjeeves.com images uploaded comics 7 8 78bc6b62fEySW.gif As you can see, the provided image above has different width amp height per image. The width when Zero performs a slash is different when Zero stands. Is it a good practice to create a padding margin for every image so they have similar width amp height. Or should I just have all the sprite cramped like that and try to handle it in the backend? Thanks"} {"_id": 33, "text": "pixel art tree using 3 4 perspective Is there a correct way to calculate the exact proportions for drawing a tree sprite for an RPG. These are the types of trees I am aiming to create(sorry for the huge picture, I dont how to scale it down) The tutorial here, http cyangmou.deviantart.com art Pixel Art Tutorial 3 The perfect crate 311089437, perfectly describes how to create an object using the 3 4 perspective but when I apply this method when drawing a tree it doesn't quite work. Is there a different method that I could use for creating non rectangle shaped objects like a tree or other strangely shaped objects, or am I going about it wrong? Thank you in advance D."} {"_id": 33, "text": "Limiting the speed of a dragged sprite in Cocos2dx I am trying to drag a row of sprites using ccTouchesMoved. By that I mean that there is a row of sprites (they are colored squares) lined up next to each other and if I grab one with a touch the rest follow it. If a sprite moves off screen I want to append it to the rest of the sprites in formation. However, if the sprite formation moves too fast it creates a slight gap between it and the appended sprites. How do I go about limiting the speed that I can drag the sprite with ccTouchesMoved? This is the only solution I could think of to my problem. If anyone has another suggestion to prevent this sprite gap from happening I would appreciate it. In ccTouchesBegan I loop through the sprites, mark the one that is touched(used for another part of game), and save the distance between the touch point and every other sprite. touch (CCTouch )(touches gt anyObject()) location touch gt getLocation() for (int i 0 i lt grid gt getGridSizeY() i ) for (int j 0 j lt grid gt getGridSizeX() j ) button grid gt button(i, j) button gt setDistanceX(location.x button gt getPositionX()) button gt setDistanceY(location.y button gt getPositionY()) if (button gt boundingBox().containsPoint(location)) button gt setTouched(true) Then in ccTouchesMoved I loop through all the sprites again and set them to always be the same saved distance from the touch point. touch (CCTouch )(touches gt anyObject()) location touch gt getLocation() for (int i 0 i lt grid gt getGridSizeY() i ) for (int j 0 j lt grid gt getGridSizeX() j ) button grid gt button(i, j) button gt setPositionX(touchLocation.x button gt getDistanceX()) button gt setPositionY(touchLocation.y button gt getDistanceY()) This is the update method code only for a sprite moving off the left side of the screen. No point in writing all the sides until I get one side to work for (int i 0 i lt grid gt getGridSizeY() i ) for (int j 0 j lt grid gt getGridSizeX() j ) button grid gt button(i, j) Replaces button if it goes off left side of grid if (button gt getPositionX() lt grid gt button(0, 0) gt getPositionX() button gt boundingBox().size.height 2) button gt setPositionX(grid gt button(grid gt getGridSizeY() 1, 0) gt getCoord().x button gt boundingBox().size.height 2) button gt setDistanceX(location.x button gt getPositionX())"} {"_id": 33, "text": "How can I make tiny sprites larger? I used a 16x16 sprite pack to make a 640x640 map in pygame The problem is that everything is extremely tiny. How could I go about making the expected \"JRPG\" look, like this for instance I have tried so far to double the size of the map tiles using pygame.transform.scale(tile,(32,32)) but that makes everything look terrible Here is how I am rendering the map import pygame import pytmx from pytmx.util pygame import class tileRender def init (self,filename) tm pytmx.load pygame(filename) self.width tm.width tm.tilewidth self.height tm.height tm.tileheight self.tmxdata tm def render(self,surface) ti self.tmxdata.get tile image by gid for layer in self.tmxdata.visible layers if isinstance(layer,pytmx.TiledTileLayer) for x,y,gid in layer tile ti(gid) tile pygame.transform.scale(tile,(32,32)) if tile surface.blit(tile,(x self.tmxdata.tilewidth, y self.tmxdata.tileheight)) def makemap(self) temp surface pygame.Surface((self.width,self.height)) self.render(temp surface) return temp surface Is there a way of \"zooming in\" on the sprites in order to get the expected look?"} {"_id": 33, "text": "What approaches are there to re designing 8 16 bit sprites for HD? I'm new to game development, and my skills with Photoshop are not that great. I was planning to try to convert a old game to HD, but for this I need HD sprites. What is a good way to approach converting 8 16 bit sprites into something like HD? I mean something like this"} {"_id": 33, "text": "Rotate sprite direction Cocos2d I want that my sprite go always forward, and you can only control his direction moving right and left (on 360 degrees). I don't know why, but the movement it's senseless. The constants to move and rotate const int POD DEGRE MOVE 5 const int POD STEP MOVE 3 The sprite initalization dragonSprite gt setPosition(Point(visibleSize.width 2, dragonSprite gt getContentSize().height 0.75)) addChild( dragonSprite, 2) The event key listener void GameScene onKeyPressed(EventKeyboard KeyCode keyCode, Event event) pressedKey keyCode switch ( pressedKey) case EventKeyboard KeyCode KEY LEFT ARROW giro POD DEGRE MOVE isMoving true break case EventKeyboard KeyCode KEY RIGHT ARROW giro POD DEGRE MOVE isMoving true break void GameScene onKeyReleased(EventKeyboard KeyCode keyCode, Event event) if ( pressedKey keyCode) pressedKey EventKeyboard KeyCode KEY NONE isMoving false giro 0 And the calculations of the new direction void GameScene update(float dt) dragonSprite gt setRotation( dragonSprite gt getRotation() giro) podVector Vec2(cos( dragonSprite gt getRotation()) POD STEP MOVE, sin( dragonSprite gt getRotation()) POD STEP MOVE) Vec2 newPos Vec2( dragonSprite gt getPosition().x podVector.x, dragonSprite gt getPosition().y podVector.y) dragonSprite gt setPosition(newPos) Another problem is that the sprite at the start moves to the right (because Cos(0) 1), so I rotate the image of the sprite 90 degrees to the right, to then rotate it again at the initialization 90 to the left so the sprite is in the right position and his start angle is 90 (sin(90) 1), but the angle is not 90, and it moves as he wishes. The last problem I have with this is that when I press a key (right or left), the sprite stops, rotates, and starts again (a direction that is not the direction where the sprite is aiming, that's the main problem). The sprite shouldn't stop while you are moving it. Can anyone help me?"} {"_id": 33, "text": "Use spritesheet frames as particles? I want to use frames from a spritesheet as particles for my emitter. I load my spritesheet with game.load.spritesheet('particles sheet', 'http stuff.lck.io luckyslot sprite sheet.png', 50, 50, 6) var emitter game.add.emitter(game.world.centerX, canvas height, 80) And i need some code to load the right frame at random emitter.makeParticles('particles sheet') Any idea?"} {"_id": 33, "text": "How to make a sprite above my character appear on the minimap attached to the floor? I have a project where I made 2 minimaps. One of minimaps is linked to the character of my project and the other to the floor As I already said in the title of the question, my character has a sprite above the head (red arrow) that appears on the minimap attached to it, but does not appear on the minimap attached to the floor. Image I looked at the rendering options and many others, but I could not get the sprite to show up. How do I get the sprite to appear on the floor minimap? EDIT 1 (Showing how I made the minimap) I used a SpringArm And a SceneCaptureComponent2D The PaperSprite is not the children of the SpringArm and stands a little below the SceneCaptureComponent2D The minimap is made from a RenderTarget. From this RenderTarget a material is created Widget Blueprint"} {"_id": 33, "text": "How to determine the best approximate direction I want to determine which sprite to use when one agent is \"facing\" another agent. My game is 2d, and uses 8 directional movement. Deciding which sprite to use for movement is easy enough since there are only 8 options when moving form one square to another. def direction(self, start, end) method for determining facing direction s width int(start 0 ) s height int(start 1 ) e width int(end 0 ) e height int(end 1 ) check directions if s height lt e height and s width e width return 'down' elif s height lt e height and s width gt e width return 'downright' elif s height e height and s width gt e width return 'left' elif s height gt e height and s width gt e width return 'upleft' elif s height gt e height and s width e width return 'up' elif s height gt e height and s width lt e width return 'upright' elif s height e height and s width lt e width return 'right' elif s height lt e height and s width lt e width return 'downleft' It's verbose, but gets the job done. start is the agents current coordinate position, and as you might guess end is the next step in the list of waypoints which makes up an agents path. The problem is that using the same function for determining which sprite should be used when attacking another agent does not look very good at all. For example, if the target is down, but only one pixel to the right, we would want to show the 'down' sprite, but this function returns 'downright' instead. How can we change it to appropriately return the fitting sprite?"} {"_id": 33, "text": "Alternative Font loaders in Monogame Framework While working on projects of mine, I have been finding that it is a huge pain to switch operating systems just to create a simple spritefont when using Monogame. I saw that the Nuclex Framework can load fonts which are clearer sharper, and they can be used in a Monogame project as well. They load fonts using the FreeType library, which is very multiplatform and is used widely. Is there a fairly simple way to use the FreeType library or another library to render text suitable for use in a Monogame project, as an xnb file?"} {"_id": 33, "text": "MonoGame sprites not consistently drawing Please don't mark this as a duplicate of my previous question which was asked anonymously. this is a reattempt because i cannot edit the first attempt. What I have so far is randomly generated tile set with items on SOME tiles one creature spawner that spawns up to 5 creatures which can be controlled by the player the ability for creatures to pick up items and bring them back to the spawn and store them for later use What I am noticing is when i launch the game, it doesnt always show all the sprites. Sometimes the spawner is missing, or the creatures, or the GUI. ANd when things DO appear, if i tell the creatures to pick up anything, other items on the ground randomly appear and disappear. even the spawn sometimes disappears! what I do notice is that when i have multiple creatures, some will disappear when crossing invisible lines but not all of them. i forced two creatures to go east at the same speed and time, and one vanished and the other didnt. If you have any ideas as to what might be causing this, please let me know. if you have any questions, i'll try to edit to appease you. thanks for reading! I have my draw method like this GraphicsDevice.Clear(Color.CornflowerBlue) TODO Add your drawing code here spriteBatch.Begin(SpriteSortMode.BackToFront, null, null, null, null, null, camera.GetTransformation()) worldEntity.Draw(spriteBatch) guiManager.DrawGUI(spriteBatch) spriteBatch.End() base.Draw(gameTime) for the world entity... its draw method systematically goes through each tile in the world and calls its draw method. the tile draws itself using Vector2 topLeftOfSprite new Vector2(this.X, this.Y) Color tintColor Color.White spriteBatch.Draw(tileTexture, topLeftOfSprite, tintColor) and then proceeds to call the draw method of any items on it. creatures and items have very similar draw methods. the gui also draws itself in a similar fashion. what i DO notice is that ive NEVER seen ground tiles vanish, only the items on them or creatures in the world. Could it be their Z isn't set appropriately?"} {"_id": 33, "text": "Alternative Font loaders in Monogame Framework While working on projects of mine, I have been finding that it is a huge pain to switch operating systems just to create a simple spritefont when using Monogame. I saw that the Nuclex Framework can load fonts which are clearer sharper, and they can be used in a Monogame project as well. They load fonts using the FreeType library, which is very multiplatform and is used widely. Is there a fairly simple way to use the FreeType library or another library to render text suitable for use in a Monogame project, as an xnb file?"} {"_id": 33, "text": "How to access sprite sheet via row and column I'm currently designing a 2D game engine in C , just had a quick question. I have a SpriteSheet class that splits up a sprite into several different sprites (like a tileset for a example) and stores them in a list. Which is great, because now I can access sprites via it's corresponding index in the sheet. However, I would really like to add a feature that will let me access a sprite by specifying the row and column it resides in (in the original sprite). I just don't know the equation to find where the sprite is in the list. Here is what I have so far public Sprite this int index get return this.sprites index public Sprite this int row, int column get Get the width and height of each individual sprite in the sheet. int cellWidth this 0 .Width int cellHeight this 0 .Height Figure out and how many rows and columns are in the entire sprite sheet int rows this.sprite.Width cellWidth int columns this.sprite.Height cellHeight Here is where I want to return the sprite located at the row and column specified. return this.sprites what do i put in here? Also, I don't know if it will help but here is the method I use to fill the list with sprites private void CreateSheet(Sprite sprite, int xOffset, int yOffset) for (int y 0 y lt sprite.Height y yOffset) for (int x 0 x lt sprite.Width x xOffset) this.sprites.Add(sprite.Clone(new Rectangle(x, y, xOffset, yOffset)))"} {"_id": 33, "text": "How to remove the old sprites in pygame and show them at a different location I am trying to show the motion of some basketballs towards walle using the pygae sprites. The idea is that I don't know how to remove the old ones so they won't show. Is there a move method so that it would know it has to draw it again at the specified location? I created a sprite class. Then I have a Character class that uses the sprite class and threads to calculate the intermediary coordinates for them. But I don't want them to show on the screen forever, like the pictures show. Thanks! import pygame class CharacterSprite(pygame.sprite.Sprite) def init (self, location, image, surface) pygame.sprite.Sprite. init (self) self.image pygame.image.load(image).convert alpha() self.rect self.image.get rect() self.rect.center location self.surface surface def draw(self) self.surface.blit(self.image, self.rect) def update(self, location) self.rect.center location self.draw() import threading import pygame import os from random import randint from Sprites.CharacterSprite import CharacterSprite LOCK threading.Lock() class StudentCharacter(threading.Thread) NRSTEPS 3 YPOS 440 TEACHERPOS 40 IMAGE PATH os.path.join('images', 'ball.png') def init (self, screen, xpos, interval) threading.Thread. init (self) self.screen, self.xpos, self.ypos, self.interval screen, xpos, self.YPOS, interval self.draw(self.xpos, self.ypos) self.configure() def draw(self, x, y) self.circle CharacterSprite( x, y , self.IMAGE PATH, self.screen) self.circle.draw() def configure(self) (left, right) self.interval self.target randint(left, right) xdif self.target self.xpos ydif self.TEACHERPOS self.ypos self.normal 'x' int(xdif self.NRSTEPS), 'y' int(ydif self.NRSTEPS) print self.target, self.normal 'x' , self.normal 'y' def update(self) self.circle.update( self.xpos, self.ypos ) def run(self) i 0 while i lt self.NRSTEPS LOCK.acquire() pygame.time.wait(100) self.xpos self.normal 'x' self.ypos self.normal 'y' self.update() print self.xpos, self.ypos pygame.display.update() i 1 LOCK.release() print \"Done\""} {"_id": 33, "text": "Problem with preloading plist file in Cocos2d x I am using Cocos2d x engine with 3.2 version. In my splash screen I am prefeching a plist by below line SpriteFrameCache getInstance() gt addSpriteFramesWithFile(\"ui.plist\") Now inside game when I am creating a sprite I am getting an assert fail error Sprite ss Sprite createWithSpriteFrameName(\"pause.png\") Assert failed Invalid spriteFrameName pause.png Also when the splash screen is removed, I am getting the below line in console cocos2d TextureCache removing unused texture D cocos2dx projects ABCD Resources mid ui.png Is there anything I need to add or something? I was doing the same thing for 2.x and was working but not in 3.2 EDIT In 3.x if you are calling this line Director getInstance() gt purgeCachedData() , remember that it will delete all textures from the cache memory. So handle all sprite sheets manually."} {"_id": 33, "text": "Are metal slug art assets free use? I'm making a mobile game and I've gotten by with completely free art assets so far, but I have an explosion from metal slug. I love it and it's perfect, but I don't want to get sued. I've seen metal slug art assets posted around the internet on various clip art websites, but haven't found any statements outright saying they're free to use in one's own commercial application. Could someone show me a link saying whether or not metal slug assets are free to use?"} {"_id": 33, "text": "how to re use a sprite in cocos2d x some times it takes time to create the sprite structures in the scene, I might need to setup structures inside this sprite to meet requirement, thus I would hope to reuse such structures with the game again and again. I tried that, remove the child from parent, detach it from parent , clean parent with the sprite. but when I try to add the sprite to another scene, it's just wont pass the assertion that the sprite already have parent did I miss some step ? add an example I have a sprite A which involves of quite a few steps to construct, so I used it in scene A layer A, and then I want to use it in scene A layer B, scene B layer A1 etc..... generally speaking I don't want to reconstruct the sprte again."} {"_id": 33, "text": "Finding relative x and y value on a sprite Gamemaker I'm having a little conundrum that may just result from a lack of knowledge of Gamemaker's functionality. I've attached two images to aid explanation. I have a sprite of a turret (with a gun barrel), attached to a turret object, and at certain points in gameplay this object will spawn another object on top of it (let's call it the 'bullet object'). I would like the bullet object to spawn at the x and y coordinates at the end of the gun barrel. This would be easy to find as a pair of coordinates if the sprite was always stationary, in this configuration. Alas, it is not. It rotates like billy oh. This means that the x and y coordinates at the end of the gun barrel are constantly different. How do I find this constantly changing x and y coordinate? I imagine (though am most likely wrong) that there the initial x and y coordinates of the sprite are saved and can be found even if rotated is there a function that does this? Or do I need to write a script and then call it every time I want to spawn the bullet object? Thanks for your help."} {"_id": 33, "text": "How to access sprite sheet via row and column I'm currently designing a 2D game engine in C , just had a quick question. I have a SpriteSheet class that splits up a sprite into several different sprites (like a tileset for a example) and stores them in a list. Which is great, because now I can access sprites via it's corresponding index in the sheet. However, I would really like to add a feature that will let me access a sprite by specifying the row and column it resides in (in the original sprite). I just don't know the equation to find where the sprite is in the list. Here is what I have so far public Sprite this int index get return this.sprites index public Sprite this int row, int column get Get the width and height of each individual sprite in the sheet. int cellWidth this 0 .Width int cellHeight this 0 .Height Figure out and how many rows and columns are in the entire sprite sheet int rows this.sprite.Width cellWidth int columns this.sprite.Height cellHeight Here is where I want to return the sprite located at the row and column specified. return this.sprites what do i put in here? Also, I don't know if it will help but here is the method I use to fill the list with sprites private void CreateSheet(Sprite sprite, int xOffset, int yOffset) for (int y 0 y lt sprite.Height y yOffset) for (int x 0 x lt sprite.Width x xOffset) this.sprites.Add(sprite.Clone(new Rectangle(x, y, xOffset, yOffset)))"} {"_id": 33, "text": "Finding relative x and y value on a sprite Gamemaker I'm having a little conundrum that may just result from a lack of knowledge of Gamemaker's functionality. I've attached two images to aid explanation. I have a sprite of a turret (with a gun barrel), attached to a turret object, and at certain points in gameplay this object will spawn another object on top of it (let's call it the 'bullet object'). I would like the bullet object to spawn at the x and y coordinates at the end of the gun barrel. This would be easy to find as a pair of coordinates if the sprite was always stationary, in this configuration. Alas, it is not. It rotates like billy oh. This means that the x and y coordinates at the end of the gun barrel are constantly different. How do I find this constantly changing x and y coordinate? I imagine (though am most likely wrong) that there the initial x and y coordinates of the sprite are saved and can be found even if rotated is there a function that does this? Or do I need to write a script and then call it every time I want to spawn the bullet object? Thanks for your help."} {"_id": 33, "text": "How to remove the old sprites in pygame and show them at a different location I am trying to show the motion of some basketballs towards walle using the pygae sprites. The idea is that I don't know how to remove the old ones so they won't show. Is there a move method so that it would know it has to draw it again at the specified location? I created a sprite class. Then I have a Character class that uses the sprite class and threads to calculate the intermediary coordinates for them. But I don't want them to show on the screen forever, like the pictures show. Thanks! import pygame class CharacterSprite(pygame.sprite.Sprite) def init (self, location, image, surface) pygame.sprite.Sprite. init (self) self.image pygame.image.load(image).convert alpha() self.rect self.image.get rect() self.rect.center location self.surface surface def draw(self) self.surface.blit(self.image, self.rect) def update(self, location) self.rect.center location self.draw() import threading import pygame import os from random import randint from Sprites.CharacterSprite import CharacterSprite LOCK threading.Lock() class StudentCharacter(threading.Thread) NRSTEPS 3 YPOS 440 TEACHERPOS 40 IMAGE PATH os.path.join('images', 'ball.png') def init (self, screen, xpos, interval) threading.Thread. init (self) self.screen, self.xpos, self.ypos, self.interval screen, xpos, self.YPOS, interval self.draw(self.xpos, self.ypos) self.configure() def draw(self, x, y) self.circle CharacterSprite( x, y , self.IMAGE PATH, self.screen) self.circle.draw() def configure(self) (left, right) self.interval self.target randint(left, right) xdif self.target self.xpos ydif self.TEACHERPOS self.ypos self.normal 'x' int(xdif self.NRSTEPS), 'y' int(ydif self.NRSTEPS) print self.target, self.normal 'x' , self.normal 'y' def update(self) self.circle.update( self.xpos, self.ypos ) def run(self) i 0 while i lt self.NRSTEPS LOCK.acquire() pygame.time.wait(100) self.xpos self.normal 'x' self.ypos self.normal 'y' self.update() print self.xpos, self.ypos pygame.display.update() i 1 LOCK.release() print \"Done\""} {"_id": 33, "text": "Slicing irregular spritesheet (automatically?) If found a cool sprite sheet on the internet but its irregular. Is there any way besides manually cutting sprites to extract the separate pngs? I need to pack them then again into the Texture Atlas under proper names. Maybe theres some smart online tool that uses deep learning or something like that?"} {"_id": 33, "text": "Spriter model not touching ground in? I was attempting to make a game in Construct 2 by using my Spriter Models plugin. However, when I imported the model, rescaled it amp changed a few things, I got this As seen in the picture, the Spriter model is not touching the platform ground. Do you know of any ways I could have the model touch the ground? Thanks in advance, Jamie Ps. Here is the link to the files, just in case you guys might wanna have a look at it https drive.google.com folderview?id 0B11opD9YgSqWbVhaNEVTcGhIRTA amp usp sharing Pps. You will need the Spriter plugin for Construct 2 to open the project file. The Spriter model files will need Spriter to open it."} {"_id": 33, "text": "What is the difference between sprites and tiles? I'm making a game, where it came to adding a tile class, but i already have a sprite one, which does the same at first glance. Can you explain the difference with a couple of examples?"} {"_id": 33, "text": "Where to hire 2D sprite artists? I'm looking for high quality original 2D sprite collections which are animated where appropriate. (IE not simply collections I can buy, we want original work). I've had a look online but am struggling to find out where I can hire such people! Where do I find such people? How much should I expect to pay?"} {"_id": 33, "text": "The right way to add images to Monogame Windows I'm starting out with MonoGame. For now, I'm only targeting Windows (desktop not Windows 8 specifically). I've used a couple of XNA products in the past (raw XNA, FlatRedBall, SilverSprite), so I may have a misunderstanding about how I should add images to my content. How do I add images to my project? Currently, I created a new Monogame project, added a folder called \"Content,\" and added images under there the only caveat is that I need to set the Copy to Output Directory action to one of the Copy ones. It seems strange, because my \"raw\" XNA project just last week had a Content project in it (XNA Framework Content Pipeline, according to VS2010), which compiled my images to XNB (I think). It seems like Monogame doesn't use the same content pipeline, but I'm not sure. Edit My question is not about \"how do I get the XNA content pipeline to work with Monogame.\" My question is \"why would I want to use the XNA content pipeline in Monogame?\" Because there are (at least) two solutions (that I see today) Add the images to the Monogame project and set the Copy to Output Directory options to copy. Add a XNA content pipeline project and add my images to that instead reference it from my MOnogame project. Which solution should I use, and why? I currently have a working version with the first option."} {"_id": 33, "text": "separate fixed size animation sheet into texture atlas I'd like to separate a 64px x 512px spritesheet into eight 64px 64px images in Adobe photoshop cs 5 so I can use a Texture Packer image atlas rather than a fixed spritesheet. Is this possible? If so, how?"} {"_id": 33, "text": "Efficient way to draw multiple separated quads Let's assume I want to draw several separated (possibly textured) quads in Direct3D 9, each consisting of two triangles How should I draw these for maximum performance, i.e. which of the following ways is better in terms of speed? Describe each quad by 4 vertices, use D3DPT TRIANGLESTRIP and call IDirect3DDevice9 DrawPrimitive for each individual quad, since they are not connected. Describe each quad by 6 vertices, use D3DPT TRIANGLELIST and call IDirect3DDevice9 DrawPrimitive just once. The first method uses less memory, while the second one requires only one draw call. However, the second way seems to be feasible only if all the quads have the same texture, since otherwise a switch would be required."} {"_id": 33, "text": "SNES development why bitplanes get scrambled? I am following this tutorial https georgjz.github.io snesaa04 . I am stuck on trying to draw a sprite. Where the end result should be this My end result is this As I have not been able to find samples of tile and palette files, I am not sure if I have done everything right. Sprites.vra 0b 2e 2a 3f 1e 1f 0f 3f 2e 3f 1c 1f 0c ff f3 fe 2f 00 3f 00 1f 00 3c 00 38 00 10 00 00 00 00 00 SpriteColors.pal fe 3f 3e 77 f8 5d 0f 49 ff 7f f8 6f 8a 6b 49 62 64 39 e0 2c 60 18 98 04 9f 0e 3e 09 2c 00 00 00 As the tutorial proposes, I use cc65 as a compiler. The files are included like this .segment quot SPRITEDATA quot SpriteData .incbin quot Sprites.vra quot ColorData .incbin quot SpriteColors.pal quot As I could not get bsnes working, I am using Snes9X. As this failed, I tried to draw a plane with just one color as well to figure out the logic. I did not manage, as the colors were always scrambled. Questions How should the tile bitplane and palette files look like? What is the checksum error my emulator throws? As a last note please be patient if this is basic stuff. I am ex web dev and a retro game hobbyist, and assembly code is completely foreign world to me."} {"_id": 33, "text": "Loss in quality on downsized sprites in Game Maker I'm having an issue with sprites quality in Game Maker. I have some sprites used for UI with an original size of 2048 512. I need to resize them in game to 512 128. But when I do, I got a loss in quality. This is the original picture, resized to 512 128 with a third party software This is the sprite, as it appears in Game Maker room editor (and in game) once resized to 512 128 Are there general guidelines for this kind of situation? By the way, it's on Windows. Though I tried launching the game on an Android device and the result was the same."} {"_id": 33, "text": "Why are 16 16 pixel tiles so common? Is there any good reason for tiles (e.g. Minecraft's) to be 16 16? I have a feeling it has something to do with binary because 16 is 10000 in binary, but that might be a coincidence. I want to know is because I want to make a game with terrain generation, and I want to know how big my tiles should be, or if it doesn't really matter."} {"_id": 33, "text": "How player(sprite) in the phaser will opposite or reverse while going left and right? I am developing a game where my player has to look to see forward when I am pressing right arrow key. But how can I make it look reverse after pressing left arrow? I can create a sprite of reverse look but how can load that while pressing left and at the same time forward player should be destroyed?"} {"_id": 33, "text": "pygame avoiding sprite 'jitters' on rotating the image Is there a common trick for getting around sprites that are changing directions 'too quickly' and causing their sprite to display erratically? In this project, the player moves in 8 directions by determining the abs() distance between the mouse's X and Y coordinates and its own obj.rect.center. If the absolute value is less than obj.speed, it simply moves to that point. If it is greater, it moves the distance its speed allows it to move in that direction. When it's time to draw the sprite, PyGame rotates it in accordance to obj.direction by using a dict called SPINNER with stored default values to pass to pygame.transform.rotate. def draw(obj) drawImg pygame.rotate.transform(obj.img, SPINNER obj.direction ) drawCtr drawImg.get rect(center obj.rect.center) DISPLAYSURF.blit(drawImg, drawCtr) This is fine for the foolish AI characters which typically make very few course corrections however, small movements of the mouse can cause the player's obj.direction to update very quickly, which looks chaotic. Is there a simple way to curb this behavior? My first guess is to bog down the player object with values that retain its previous state and then determine the amount of rotation to apply, but I have a feeling the better solution is to assign that responsibility to the 'view' and not the 'model'. I'm not sticking to any hard and fast rules regarding MVC, but I am trying to engage in enough separation of concerns that 'view like methods' don't make 'controller like' changes to 'model like' objects, if that makes sense."} {"_id": 33, "text": "Problem with preloading plist file in Cocos2d x I am using Cocos2d x engine with 3.2 version. In my splash screen I am prefeching a plist by below line SpriteFrameCache getInstance() gt addSpriteFramesWithFile(\"ui.plist\") Now inside game when I am creating a sprite I am getting an assert fail error Sprite ss Sprite createWithSpriteFrameName(\"pause.png\") Assert failed Invalid spriteFrameName pause.png Also when the splash screen is removed, I am getting the below line in console cocos2d TextureCache removing unused texture D cocos2dx projects ABCD Resources mid ui.png Is there anything I need to add or something? I was doing the same thing for 2.x and was working but not in 3.2 EDIT In 3.x if you are calling this line Director getInstance() gt purgeCachedData() , remember that it will delete all textures from the cache memory. So handle all sprite sheets manually."} {"_id": 33, "text": "How to make an object with its own sprite draw an additional sprite on top of itself I'm making character select buttons for a Game Maker Studio 2 game, hoping to do so by just having a single object I can edit on an individual basis to change which character it represents. I also want the button itself to display the sprite of the character it's meant to represent like an image overlaying the button's own sprite. I can't seem to get a clear, direct answer on how this is done. To sum up Character select button is an object with its own assigned sprite. Each individual button object holds (a reference to) a corresponding character object the player may select by clicking that specific button. Button object should be able to check the sprite of the character object it references, and draw it on top of its own sprite without replacing it entirely. If anyone can help show me how to do that last part or barring that, perhaps point me toward a better way to achieve a similar effect, it would be appreciated."} {"_id": 33, "text": "Make a laser beam effect with Ogre and a BillboardChain http www.lpi.usra.edu lunar missions apollo apollo 15 images laser beam lg.gif I want to be able to such an effect, but I don't really know how the BillboardChain class works or how I can use it, examples for this class seems to be rare."} {"_id": 34, "text": "Can I make a mirror with Unity Free? If I understand correctly, render textures are a feature of Unity Pro, and that is the best way to create mirrors, TV screens, and so forth. If I am wrong, please tell me. What I would like to know is if there is another, probably less convenient, way to create a mirror with the free version of Unity. If I need to write a custom script, I would appreciate a basic outline of how to write it. Even better, if you know of a free script package that does this, please tell me."} {"_id": 34, "text": "Is there a way to easily make 3d models and textures for people with no prior experience? I want to make a game, but I need assets. I am wondering if I should make them by myself even though I never made any textures or 3d models before. Are there technologies that allow you to easily make them? What would you recommend me to do?"} {"_id": 34, "text": "LightMap not working properly I've made a chips bag model for my game http imgur.com JcumRF4 And I textured it like this http imgur.com wpyeACZ and I googled on how to make lightmaps all of them say \"Smart UV project\" but when I do that, texture on my model gets broken, so thats why I dont want to use smart uv project Is there another way?, it has to be."} {"_id": 34, "text": "Would it be possible to edit character models of a PS1 game, to be played on an emulator? There are some abandoned PS1 oldies out there that I would love to see revamped with improved assets. I have some skills with some some modelling programs, so I was wondering if it would be possible to rip some models with or without their textures so that I could try to update them, and experience them on an emulator. Is this possible? Even if the edited copies cannot be reinserted into the game, would it still be possible to rip the models out so that I could edit them?"} {"_id": 34, "text": "How to shade a texture two different colors? To give an example of what I'm asking about, I'll use Saints Row 3 since I've been playing that lately. In that game you can customize your looks and your car's appearance a lot. Your coat can have a primary color and a trim color. Your car can have a primary color and a stripe color, etc. Is there just a single coat texture that is being shaded two different colors somehow or are they overlaying a transparent second texture for the trim stripes that gets shaded differently? If it's just one texture I'd like to know how it's done. If it's two different textures it seems like it's a waste of space. The second texture would be the same size as the first one but mostly transparent if you just wanted to lay it on top of the first one. Or are they just carefully positioning a second, smaller texture so that it aligns properly with the first one?"} {"_id": 34, "text": "Why is my texture displaying incorrect colours using dx11? I am trying to load my data from a binary file (ppm) and create a texture using this data. It is important that I learn to do it this way as I am eventually going to be packing all of my textures into a single binary file and then index them so creating the texture with pure binary data is something that I need to be able to do. It seems that the texture is drawing correctly, but the colours are incorrect. I saved my image as .ppm just for this test application. Here is the code to load my data ppm ppm ppm.read(std string(\"textureppm.ppm\")) just to ensure the data is correct uint32 t val ppm.pixels 0 unsigned char r (val amp 0xFF000000) gt gt 24 unsigned char g (val amp 0x00FF0000) gt gt 16 unsigned char b (val amp 0x0000FF00) gt gt 8 unsigned char a (val amp 0x000000FF) ID3D11ShaderResourceView texSRV nullptr D3D11 SUBRESOURCE DATA initData amp ppm.pixels, ppm.width sizeof(uint32 t), 0 D3D11 TEXTURE2D DESC desc desc.Width ppm.width desc.Height ppm.height desc.MipLevels 1 desc.ArraySize 1 desc.Format DXGI FORMAT R8G8B8A8 UNORM desc.SampleDesc.Count 1 desc.Usage D3D11 USAGE IMMUTABLE desc.BindFlags D3D11 BIND SHADER RESOURCE ID3D11Texture2D tex HRESULT hr getDevice() gt CreateTexture2D( amp desc, amp initData, amp tex) if (SUCCEEDED(hr)) D3D11 SHADER RESOURCE VIEW DESC SRVDesc SRVDesc.Format DXGI FORMAT R8G8B8A8 UNORM SRVDesc.ViewDimension D3D11 SRV DIMENSION TEXTURE2D SRVDesc.Texture2D.MipLevels 1 hr getDevice() gt CreateShaderResourceView(tex, amp SRVDesc, amp texSRV) if (FAILED(hr)) throw 0 else setTexture(texSRV) I have packed each byte into a uint32 t as it seems that is the format that is required DXGI FORMAT R8G8B8A8 UNORM Here is the packing uint32 t ppm CreateRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a) uint32 t value 0 int r2 (r amp 0xff) lt lt 24 int g2 (g amp 0xff) lt lt 16 int b2 (b amp 0xff) lt lt 8 int a2 (a amp 0xff) value r2 g2 b2 a2 return value This code produces the following texture When the original texture is Does anyone know what I am doing wrong?"} {"_id": 34, "text": "FPS drop after moved from Textures to TextureAtlas in LibGDX I've started using LibGDX some time ago and I was making a test project to get used to this library. I've created some images and added them to the assets folder and loaded each image as a Texture using the AssetManager. Everything was working fine and I had 60 FPS. I wanted to work in a more efficient way so I packed all my images into an atlas using the TexturePacker tool. I loaded the atlas using the AssetManager again and started using TextureRegions instead of Textures. After this change I've started to notice sudden drops in FPS from 60 to 50 and even 30 once. I've tried to change the pixel format to RGBA4444, I've made sure that the min and mag filter were both seth to Nearest, but still I see those annoying frame drops. I'm not doing anything heavy in the game itself, it's currently some actors in a stage. I got some MoveActions and Animation, but nothing special yet. Does anyone have a clue what can cause the FPS drop? Thanks"} {"_id": 34, "text": "Confusion on HLSL Samplers. Can I Set Samplers Inside Functions? I'm trying to create a system where I can instance a quad to the screen, however I've run into a problem. Like I said, I'm trying to instance the quad, so I'm trying to use the same geometry several times, and I'm trying to do it in one draw call. The issue is, I want some quads to use different textures, but I can't figure out how to get the data into a sampler so I can use it in the pixel shader. I figured that since we can simply pass in the 4 bytes of our IDirect3DTexture9 to set the global texture, I can do so when passing in my dynamic buffer. (Which also stores each objects world matrix and UV data) Now that I'm sending the data, I can't figure how to get it into the sampler, and I really want to assume that it's simply not possible. Is there any way I could achieve this?"} {"_id": 34, "text": "Why is the texture all wrong on my model? Why is this happening? If possible I'd like to know what this particular problem is called. The model is a simple cube made in blender and exported with normals and MTL. Texture is the cube unwrapped with crate image on each side. Are the UV coordinates wrong?"} {"_id": 34, "text": "What is the difference between a Sprite and a Texture? I have an assignment due for University, and my task is to discuss textures used within video games, and how they have evolved. My main question is, what is the fundamental difference between using a sprite, or using other texture methods? Having done a little research myself, I seem to be inclined that Sprites store images in a single file, and can be used for animations etc.. and were commonly used with older video games, generally using sprites as all of their game visuals. Now, with modern games, sprites I believe tend to be less used as technology advances and other textures are available such as bump mapping. Although sprites are still used today to accommodate features such as a health bar or long distance textures. But what are the main advantages of using textures, over sprites?"} {"_id": 34, "text": "does cocos2d cache texture automatically I know if we want the textures cached we can use the sharedtexture manager to cache them, but since this is on mobile platform , why don't cocos2d x just do this for all texture loads ? when creating sprites with images, are these textures cached as well ?"} {"_id": 34, "text": "How to make a texture appear the same way in a cube? My problem seems so simple, that before asking the question here I did a search on google and this site https forums.unrealengine.com development discussion content creation 33665 applying and manipulating textures on actors https www.youtube.com watch?v p6O4AgSwTmQ Trouble applying a texture to a cube How to produce a texture to represent a vector field Why do I get a blank material in Unreal Engine 4? How to create smoke that spreads outward in all directions? But nothing seemed to be related to my problem. I imported this image.png I created a material and added the image to it But I did not get the expected result in the game (I wish this yellow line were under that pink arrow that I drew) Innocently I thought the solution was obvious, so I added another image.png and added it to the material To my surprise, the result was worse, the yellow line did not even appear I realized this happens because the floor of my game is a \"stretched\" cube, so the image I added is appearing correctly on one of its faces, not just the one I want. I'd like to know how to make it look the same on all faces, or some value that I can change so that it appears correctly on the face I want. EDIT 1 (attempt using rotator) I put the input time to see if any value would be compatible with what I want, but none is. I tried with both texture images, but both presented the same behavior See that spinning looks like the shaft rotates around the top left of the floor. For some moments the yellow line will disappear."} {"_id": 34, "text": "Where does the roughness map go? So I used Quixel, and created a great item. I want to view it in Unity with all the maps the problem however is I have 5 maps but only know how to insert 4. Diffuse Normal AO Specular Roughness I don't see a slot for roughness (AKA gloss)."} {"_id": 34, "text": "Is it possible to look up a texel from a texture in GLES2 GLSL framgent shader without using sampler? Is there some way I can directly access texture memory from fragment shader in GLES2 GLSL? I don't need the sampler to be involved since I am just using it as a look up table."} {"_id": 34, "text": "How to read BC4 texture in GLSL? I'm supposed to receive a texture in BC4 format. In OpenGL, i guess this format is called GL COMPRESSED RED RGTC1. The texture is not really a \"texture\", more like a data to handle at fragment shader. Usually, to get colors from a texture within a fragment shader, i do uniform sampler2D TextureUnit void main() vec4 TexColor texture2D(TextureUnit, vec2(gl TexCoord 0 )) (...) the result of which is obviously a v4, for RGBA. But now, i'm supposed to receive a single float from the read. I'm struggling to understand how this is achieved. Should i still use a texture sampler, and expect the value to be in a specific position (for example, within TexColor.r ?), or should i use something else ?"} {"_id": 34, "text": "How can I create random noise that is seamless across modular game assets? Does anyone know how I can create a texture for a modular tile, such that when the tiles are arranged, random weathering effects such as scratches will be continuous across seams? An example photo below shows the ideal result. The scratches are continuous between different tiles. Is creating weathering effects like this possible using any procedural software?"} {"_id": 34, "text": "3ds max \"thread stiching\" plugin for cloths or furniture i m trying to find a plugin or way to add 3D thread stiching to a mesh. It would be perfect if you could creat thread stiches along edges in \"editpoly\" mode. I know that you can somehow do this in Z Brush with customized alpha brushes but in my opinion its a bit complicated. I could also imagine alining a editable spline along a mesh edge. Important for me would be that this \"unknown tool\" would also add the displacement on the canvas and the stiches so i can use \"render to texture\" to give seems realistic look. Thisway you could always creat perfect stiches with realistic looking displacement like in the picture below without to much affort. http www.esunroof.com contrast stitch.jpg http t1.gstatic.com images?q tbn ANd9GcQplgCvhur ynthz15Qdaqpv1QRwkG4K6sjhVjDqzzxm6OaY9Bt would be awesome if you know a way to do this, Thanks a lot lot )"} {"_id": 34, "text": "libgdx texture edge blending problem I have two completely white bitmaps here They're there, trust me. When I put one on top of the other and scale them down with TextureFilter.Linear I get this How do I get rid of the dark pixels?"} {"_id": 34, "text": "Reversing plane projection texture mapping algorithm I found this algorithm in some old codebase, it takes two triangles from a mesh ABC and PMN, where ABC is the triangle that will be rendered and PMN is an extra triangle that is only used to generate the UV coordinate for ABC and is not rendered. I am trying to create a reverse algorithm to calculate the PMN triangle positions based on UV coordinates of a triangle and ABC positions of the same triangle. Vector3f A stored in mesh data Vector3f B stored in mesh data Vector3f C stored in mesh data Vector3f P stored in mesh data Vector3f M stored in mesh data Vector3f N stored in mesh data Vector3f PM M.sub(P, new Vector3f()) Vector3f PN N.sub(P, new Vector3f()) Vector3f PA A.sub(P, new Vector3f()) Vector3f PB B.sub(P, new Vector3f()) Vector3f PC C.sub(P, new Vector3f()) Vector3f PMxPN PM.cross(PN, new Vector3f()) Calculate the U coordinates Vector3f U PN.cross(PMxPN, new Vector3f()) float Mu 1.0F U.dot(PM) float Ua U.dot(PA) Mu 1st U coordinate (for vertex A) float Ub U.dot(PB) Mu 2nd U coordinate (for vertex B) float Uc U.dot(PC) Mu 3rd U coordinate (for vertex C) Calculate the V coordinates Vector3f V PM.cross(PMxPN, new Vector3f()) float Mv 1 V.dot(PN) float Va V.dot(PA) Mv 1st V coordinate (for vertex A) float Vb V.dot(PB) Mv 2nd V coordinate (for vertex B) float Vc V.dot(PC) Mv 3rd V coordinate (for vertex C) Formatted LaTex represention of the same algorithm vec PM vec M vec P vec PN vec N vec P vec PA vec A vec P vec PB vec B vec P vec PC vec C vec P vec PMPN vec PM times vec PN vec U vec PN times vec PMPN Mu frac 1 vec U cdot vec PM Ua vec U cdot vec PA times Mu Ub vec U cdot vec PB times Mu Uc vec U cdot vec PC times Mu vec V vec PM times vec PMPN Mv frac 1 vec V cdot vec PN Va vec V cdot vec PA times Mv Vb vec V cdot vec PB times Mv Vc vec V cdot vec PC times Mv"} {"_id": 34, "text": "Replicating no. of sprites without letting the app to slow down and crash Is it possible that if I'm making a a simple drag n drop game, does making a new sprite via constructor with texture as a parameter makes the game slower and depletes more memory until it crashes or does making a new texture via constructor cause the memory to go slow? I'm on a revision for the new drag n drop puzzle game where the only goal is to stack the most no. of objects as you can before it falls off the platform. Is it a good idea to create another sprite with texture as a parameter every time a player drag n drop another object? Here's the start of the dry run looked like and I set it to debug mode so that the platform is completely block the pit to test the replication test. Afterwards, when it reaches from hundreds to thousands, this will be like this and the game gets slower. When the game crashes, here's the result via Logcat 12 11 16 38 53.953 E AudioTrack(25701) AudioFlinger could not create track, status 22 12 11 16 38 53.953 E SoundPool(25701) Error creating AudioTrack 12 11 16 38 53.993 D dalvikvm(25701) GC EXPLICIT freed 947K, 14 free 14414K 16672K, paused 2ms 4ms, total 96ms 12 11 16 39 16.363 E AudioTrack(25701) AudioFlinger could not create track, status 22 12 11 16 39 16.363 E SoundPool(25701) Error creating AudioTrack 12 11 16 39 16.433 D dalvikvm(25701) GC FOR ALLOC freed 2120K, 15 free 14418K 16848K, paused 47ms, total 47ms By the way, I'm using BodyEditor library for Box2D program and rendering, a physics engine."} {"_id": 34, "text": "Triangle Texture Packing Problem I'm trying to create a texture atlas where each triangle face is laid separately from each other (i.e. it is not typical mesh parameterization). In order to do this, I would have to pack the triangles into a 2D texture image. Can someone suggest a good algorithm to do this efficiently, both timely and spatially?"} {"_id": 34, "text": "Unity 5 Textures look strange in Deferred Rendering I've created an exterior terrain scene in Unity 5 which features lots of trees and grass but some textures look awful and I'm wondering why. Please see the attached image This texture problem is especially obvious at night (I'm using Time of Day unity asset for Day Night cycle) but also during day light it doesn't look good. The tree bark looks like plastic and also the ground textures are too bright and lack contrast. Stone texture on the other hand look perfectly fine. Can somebody point me into the right direction of what I'm doing wrong here with my lighting and rendering?"} {"_id": 34, "text": "Accessing and changing texture data in SlimDX How can I access and change texture data in SlimDX? I have a Texture2D and a Texture3D and I need to be able to go in and change either a single or group of pixels."} {"_id": 34, "text": "How do I use transparent textures in panda3d? I need to map a partially transparent texture on a flat quad with panda3d. With the quad as a canvas I'd like to create something like sprites positioned in the 3d coordinate system. I wanted to render a tree. As you can see the color values of the trees border have been stretched over the texture. How can I change the texture mode to include the alpha channel ? I just don't know how to get hold of the right settings. A link to the right manpage would be perfect. If you need more information about the setup you might want to look at my other question How do I use setFilmSize in panda3d to achieve the correct view?"} {"_id": 34, "text": "How can I find the right UV coordinates for interpolating a bezier curve? I'll let this picture do the talking. I'm trying to create a mesh from a bezier curve and then add a texture to it. The problem here is that the interpolation points along the curve do not increase linearly, so points farther from the control point (near the endpoints) stretch and those in the bend contract, causing the texture to be uneven across the curve, which can be problematic when using a pattern like stripes on a road. How can I determine how far along the curve the vertices actually are so I can give a proper UV coordinate? EDIT Allow me to clarify that I'm not talking about the trapezoidal distortion of the roads. That I know is normal and I'm not concerned about. I've updated the image to show more clearly where my concerns are. Interpolating over the curve I get 10 segments, but each of these 10 segments is not spaced at an equal point along the curve, so I have to account for this in assigning UV data to vertices or else the road texture will stretch shrink depending on how far apart vertices are at that particular part of the curve."} {"_id": 34, "text": "Why is it when I render a basic cube, my editor's grid changes too? I have one HLSL file for DirectX11 that only has input layout for color and position. Then another HLSL file for the simple cube that has position, normal and textures. What I noticed is when I render the simple cube the grid also changes and doesn't remain pure white color. They have different pixelshaders, vertexshaders, constant buffers and different inputlayout descriptions. Would anyone like to chip in and help get this resolved? This has been puzzling for a day!"} {"_id": 34, "text": "minecraft mapping from tibia OTBM file I am new to minecraft modding but i program for a living and it looks quite simple to get around. I have this fantasy and a quick internet search shows im not the only one. For those of you who do not know tibia is an MMORPG first released in 1997. It is a 2d tile based game and i would like to see it in 3D. since it is a tile based game it fits nicely with the minecraft architecture. Tibia is a close sourced game but there is TibiaOT which is developed by the community and the map file format is OTBM (open tibia binary map). This is a set of 15 2D grids where each grid represents a floor or the height of the grid, the file comes with two more files with monster spawns and default item locations like chests. There is a tibia texture pack for minecraft called \"Tibian texture pack\", so we got the materials covered. all in all we have the following a native tibia map and a minecraft texture pack people have been building tibia maps manually for years now, it seems stupid because we have a binary file for the real map. what we need is a way to map the OTBM file to a minecraft map. i am looking for tools and any other tips a on how to digest the files into a minecraft map file. an explanation of minecraft map file format would also be very helpful."} {"_id": 34, "text": "Multiple colored textures vs Color Overlay Let's say we're using DirectX 9 10 11. In our game we have a character wearing armor. The armor has 50 different color variations. So, if armor is red, the first method would load the red texture from file. The second method would display the 1 base texture, with a red overlay. Code wise the overlay armor would just contain an extra flag that would specify color. Is it faster more efficient to load different textures in? Or, is it faster more efficient to color the texture on the fly? I'm not aware if there is some huge overhead for dropping a tint over a texture..."} {"_id": 34, "text": "reading from texture2d resource in directx11 Hi i am trying to read data in resource, which i used to do well without any problems. but suddenly it is not working. first i made immutable resource that has data in it, which is XMFLOAT4(1,1,1,1) here. next i made staging resource for reading. lastly, i called map unmap to read and store data into outputArr. (all HRESULT checked already) int WIDTH 10, HEIGHT 2 ID3D11Texture2D resource create texture D3D11 TEXTURE2D DESC texDesc texDesc.BindFlags D3D11 BIND SHADER RESOURCE texDesc.Usage D3D11 USAGE IMMUTABLE texDesc.Format DXGI FORMAT R32G32B32A32 FLOAT texDesc.Width WIDTH texDesc.Height HEIGHT texDesc.CPUAccessFlags 0 texDesc.ArraySize 1 texDesc.MipLevels 1 texDesc.SampleDesc.Count 1 texDesc.SampleDesc.Quality 0 texDesc.MiscFlags 0 XMFLOAT4 initValues new XMFLOAT4 WIDTH HEIGHT for (int i 0 i lt WIDTH HEIGHT i) initValues i XMFLOAT4(1,1,1,1) D3D11 SUBRESOURCE DATA data data.pSysMem initValues data.SysMemPitch sizeof(XMFLOAT4) WIDTH data.SysMemSlicePitch 0 device gt CreateTexture2D( amp texDesc, amp data, amp resource) ID3D11Texture2D staging create texture for reading D3D11 TEXTURE2D DESC stgDesc stgDesc.BindFlags 0 stgDesc.Usage D3D11 USAGE STAGING stgDesc.Format DXGI FORMAT R32G32B32A32 FLOAT stgDesc.Width WIDTH stgDesc.Height HEIGHT stgDesc.CPUAccessFlags D3D11 CPU ACCESS READ stgDesc.ArraySize 1 stgDesc.MipLevels 1 stgDesc.SampleDesc.Count 1 stgDesc.SampleDesc.Quality 0 stgDesc.MiscFlags 0 device gt CreateTexture2D( amp stgDesc, nullptr, amp staging) XMFLOAT4 outputArr new XMFLOAT4 WIDTH HEIGHT READ dContext gt CopyResource(staging, resource) D3D11 MAPPED SUBRESOURCE mappedResource ZeroMemory( amp mappedResource, sizeof(D3D11 MAPPED SUBRESOURCE)) dContext gt Map(staging, 0, D3D11 MAP READ, 0, amp mappedResource) outputArr reinterpret cast lt XMFLOAT4 gt (mappedResource.pData) std vector lt XMFLOAT4 gt testV for (int y 0 y lt HEIGHT y) for (int x 0 x lt WIDTH x) int idx y WIDTH x testV.push back(outputArr idx ) dContext gt Unmap(staging, 0) and it turns out, only when WIDTH is multiple of 16(HEIGHT doesn't seem to be matter here), it copies the data well into ALL element of array, otherwise it fill out just 0 into array until next 16 element. For example, if width height is 10 2, first 10 elements of outputArr will have proper data and next 6 elements have just 0, and next another 10 elements with data, and 6 elements with 0, so on. i haven't had any problem on dealing with resources. and struggle still. just my humble assumption is that there might be specific alignment in number of width of resource that i miss. Or silly mistake in my process. Hope anyone can find something from this question. thanks"} {"_id": 34, "text": "Ogre3d 2.1 How to apply texture on mesh? I have searched forums and tried to read the Ogre 2.1 samples, but I still have no clue how to apply texture on mesh ( Here what I've done so far. I use Easy Ogre Exporter to export the scene (actually I just need the model and texture). I got the following files modelRoot.mesh modelRoot.skeleton model.material model.tga Note I also use OgreMeshTool d.exe to upgrade the mesh from v1 to v2. I render this model into Ogre In the file resources2.cfg Essential Zip .. Data DebugPack.zip I add the model files (4 files I got from Easy Ogre Exporter at step 1 above) into DebugPack.zip file. And I use this code to add the model into the Ogre scene void MeshHelper CreateMesh(Ogre String szFileName, Ogre Vector3 scale) Bring the mesh to scene m meshItem m sceneManager gt createItem(szFileName, Ogre ResourceGroupManager AUTODETECT RESOURCE GROUP NAME, Ogre SCENE DYNAMIC) m meshSceneNode m sceneManager gt getRootSceneNode(Ogre SCENE DYNAMIC) gt createChildSceneNode(Ogre SCENE DYNAMIC) m meshSceneNode gt attachObject(m meshItem) if (nullptr ! scale) m meshSceneNode gt scale(scale gt x, scale gt y, scale gt z) ... meshHelper.CreateMesh(\"modelRoot.mesh\", amp meshScale) But I can only render the model without texture ( Please help me to apply these texture into my model model.material model.tga Thanks for reading )"} {"_id": 34, "text": "How to make a texture not stretch? I have made two textures in Photoshop. I applied one of the textures to the sides (one to each side, in the Unity editor) and the other one to the top and bottom sides. However when I extend the object the texture gets stretched which I don't want. Is there any way to prevent this? The object is a cube. I don't want the texture to get stretched if I make the cube larger and I don't want the texture to get shrunk if I were to make the quad smaller. This is what I don't want as a result"} {"_id": 34, "text": "Why are textures always square powers of two? What if they aren't? Why are the resolution of textures in games always a power of two (128x128, 256x256, 512x512, 1024x1024, etc.)? Wouldn't it be smart to save on the game's file size and make the texture exactly fit the UV unwrapped model? What would happen if there was a texture that was not a power of two? Would it be incorrect to have a texture be something like 256x512, or 512x1024? Or would this cause the problems that non power of two textures may cause?"} {"_id": 34, "text": "Why texture coordinate of flat surface reflection is calculated like this in fragment shader? The whole project is here https developer.apple.com library mac samplecode GLEssentials Introduction Intro.html The rendering flow is like this Render the character upside down to a texture. Render the character normally. Render the flat reflection surface below the character using the texture from step 1. I don't understand the texture coordinate calculation in the fragment shader, specifically the block marked with ??? below precision highp float Color of tint to apply (blue) const vec4 tintColor vec4(0.0, 0.0, 1.0, 1.0) Amount of tint to apply const float tintFactor 0.2 varying vec3 varNormal varying vec3 varEyeDir uniform sampler2D diffuseTexture void main (void) Compute reflection vector vec3 reflectDir reflect(varEyeDir, varNormal) Compute altitude and azimuth angles vec2 texcoord texcoord.t normalize(reflectDir).y ??????????????????????????????????????????????? reflectDir.y 0.0 Why clear reflectDir.y? texcoord.s normalize(reflectDir).x 0.5 Why times 0.5? Translate index values into proper range if (reflectDir.z gt 0.0) texcoord (texcoord 1.0) 0.5 else texcoord.t (texcoord.t 1.0) 0.5 texcoord.s ( texcoord.s) 0.5 1.0 Why translation of s is like this, different from t? ??????????????????????????????????????????????? Do a lookup into the environment map. vec4 texColor texture2D(diffuseTexture, texcoord) Add some blue tint to the image so it looks more like a mirror or glass gl FragColor mix(texColor, tintColor, tintFactor) Thanks in advance to anyone who can demystify this for me!"} {"_id": 34, "text": "pre rendering light on texture based on bump map Using a gray scale bump map and N sources of colored light, what is the algorithm to render the light on the textured surface, assuming I have the angle(s) and distance of each light source? (I am pre rendering in software). I have the part where it renders light based on the position and angle of light source. My question is twofold How do I decide on an RGB color based on multiple different light sources? Is it simply additive by nature? What do I do about cases where the angle is not a sufficient way to determine intensity? For instance when there is a deep caveat in the surface and a higher elevated area is blocking the light to that lower shaded area? How do you handle something like that?"} {"_id": 34, "text": "Making a radial gradient visual range I am currently working on a project in p5JS. So lets say i've got a texture and top of it, i've got a radial gradient that is overlapping on the texture. I want to make this like a cool vision range effect in 2D. I believe you can imagine this stitation. So how am i able to start this thing? Should i use another framework to do this?"} {"_id": 34, "text": "Best way to load multiple TextureRegion from multiple bitmaps in AndEngine I've seen a lot of examples of AndEngine usage where some bitmaps are mapped into some TextureRegions and loaded into an Atlas. But what if I have a lot of bitmaps, where each bitmap is a sprite sheet, with several sprites for a given entity? How can I extract multiple texture regions from each bitmap and load all that into a single Atlas?"} {"_id": 34, "text": "Monogame Texture anti aliasing result in transparent edges This is a follow up question on a previous issue I faced with a game I'm trying to make. It's in a 2D isometric perspective and the levels are created from individual tiles. A simple 3x3 map can be seen here The tiles are individually added to the sprite batch, and (at least, this is what I think is happening) each one get anti aliased on their edges, resulting in a small blur which creates the thin edges that you can see in the picture. To make matters worse, I actually want to provide a bit more complex tiles in my game than what is displayed above. For example, I want to be able to show roads. To do so, I wanted to layer multiple sprites on top of each other, resulting in the picture below I think you can see where I'm going here. The same problem that I described with the aliasing is now occuring aroud each texture. So sad. I know I can use Point sampling to make the textures align pixel perfect, but even though this does work, the (relatively) high resolution textures really do not seem fit for such a setting I mean, these edges simply need to be anti aliased. So, my question to you all is Is there a way to stitch my tiles (and tile pieces) together in a way so that anti aliasing does not ruin it with those annoying edges, while still being able to produce a nicely anti aliased result? I hope there is, and that someone here can show me how ) Thanks, Rutger Edit 1 Changed the title to be more representative to the problem (I hope?)"} {"_id": 34, "text": "Spherical fractal noise generator in shader I have a growing sphere in space, and I thought of having a procedural generated texture over it. Since it is growing, I thought a fractal would be a great choice, because more details would be visible the larger the sphere get (and I could mess with some parameter over time to have it animated). A quick Mandelbrot implementation in GLSL showed it would be too expensive to have it in the devices I am targeting also, I don't know how to map a cool looking fractal over complex plane onto a sphere without distortions (I expect the players to fly around this sphere in every direction, so there should be no \"glued\" edges or collapsed points), neither I have the background to devise project a fractal over the spherical surface myself (probably was done before, but I could not find). So weighting the requisites of the procedural texture Fast to run, for low end mobile GPU Over a spherical surface domain Growing in details with growing in size Possible to animate (BONUS) Cool looking (of course) then I thought it might be impossible within the constraints. But since I am no expert in this fractal thing, I thought I could ask it here first before scraping out the idea. Maybe it is really not a fractal I need, and there is some other kind of noise with growing details I could use. Do you know of such noise generation procedure? Do you know of any noise generator with uniform distribution over spherical sufaces, or any fractals whose domain is a sphere? Can you suggest any alternatives for my situation?"} {"_id": 34, "text": "Should the content pipeline tools be embedded in the engine? How minimal should a games engine be? How much of the content pipeline should be embedded in the engine? Some use cases where the super engine might be useful When loading user content, the user isn't required to package up his textures, the engine will do it at load time. A script requests a font at a much larger size than was pre generated, the engine could parse the ttf file ad build a new texture atlas. Halo forge. None of this is free of course. This requires your content pipeline tools to written in C . Support libraries you use in the pipeline need to be compiled for use on the device. It requires the content generation to be not buggy. And it generally makes your engine larger and unwieldy. What are some other pros and cons? Do the pros outweigh the cons? Some specific questions Should engine be capable of loading various image formats? A TGA only loader is pretty easy to hand code. What about audio formats? Is it feasible to only support loading wav files? What about ambient music files which are often huge. Should the engine be capable of dynamic TTF parsing and atlas generation? Texture packing."} {"_id": 34, "text": "How to print Depth to a Texture2D and then read it in the next pass on a shader in DirectX11 I'm programming a two pass effect in DirectX 11 (SharpDX). It's supposed to write the depth to a texture in the first pass and then use that texture to extract data on the second one in the pixel shader. What I get is a white screen, with nothing but the interface and I don't know why nothing is being printed. What could be the problem? I would say I should get at least something from the Depth Texture. This is how I'm setting the depth texture values this.depthBuffer new Texture2D(device, new Texture2DDescription() Format Format.R32 Typeless, ArraySize 1, MipLevels 1, Width (int)host.ActualWidth, Height (int)host.ActualHeight, SampleDescription new SampleDescription(1, 0), Usage ResourceUsage.Default, BindFlags BindFlags.DepthStencil BindFlags.ShaderResource, CpuAccessFlags CpuAccessFlags.None, OptionFlags ResourceOptionFlags.None, ) this.depthBufferShaderResourceView new ShaderResourceView(this.device, this.depthBuffer, new ShaderResourceViewDescription() Format Format.R32 Float, Dimension ShaderResourceViewDimension.Texture2D, Texture2D new ShaderResourceViewDescription.Texture2DResource() MipLevels 1, MostDetailedMip 0, ) var depthStencilDesc new DepthStencilStateDescription() DepthComparison Comparison.LessEqual, DepthWriteMask global SharpDX.Direct3D11.DepthWriteMask.All, IsDepthEnabled true, And here is how I sample the depth in the .fx file int3 posTex int3(input.p.xy, 0) float depthPixel DepthTexture.Load(posTex) float4 color float4(depthPixel, depthPixel , depthPixel, 1.0f ) return color And here the way I'm now setting the Depth Buffer stencil view as a Render Target in 2 passes. In the first I try to set the depthstencilview as a target. In the second pass I'm trying to set teh depth texture as a shader resource to read from it. this.device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.vertexBuffer, LinesVertex.SizeInBytes, 0)) PASS 0 this.device.ImmediateContext.OutputMerger.SetTargets(depthBufferStencilView) this.device.ImmediateContext.ClearDepthStencilView(this.depthBufferStencilView, DepthStencilClearFlags.Depth DepthStencilClearFlags.Stencil, 1.0f, 0) this.technique.GetPassByIndex(0).Apply(this.device.ImmediateContext) this.device.ImmediateContext.DrawIndexed(this.geometry.Indices.Length, 0, 0) PASS 1 this.device.ImmediateContext.OutputMerger.ResetTargets() unbinding the depthStencilView this.device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.vertexBuffer, LinesVertex.SizeInBytes, 0)) this.depthStencilShaderResourceVariable effect.GetVariableByName(\"DepthTexture\").AsShaderResource() this.depthStencilShaderResourceVariable.SetResource(this.depthBufferShaderResourceView) this.technique.GetPassByIndex(1).Apply(this.device.ImmediateContext) this.device.ImmediateContext.DrawIndexed(this.geometry.Indices.Length, 0, 0) Finally, this is how I set the two passes in the .fx file technique11 RenderMyTechnique pass P0 SetDepthStencilState( DSSDepthLessEqual, 0 ) SetVertexShader ( CompileShader( vs 4 0, VShader() ) ) SetHullShader ( NULL ) SetDomainShader ( NULL ) SetGeometryShader ( NULL ) SetPixelShader ( NULL ) pass P1 SetDepthStencilState( DSSDepthLessEqual, 0 ) SetVertexShader ( CompileShader( vs 4 0, VShader() ) ) SetHullShader ( NULL ) SetDomainShader ( NULL ) SetGeometryShader ( CompileShader( gs 4 0, GShader() ) ) SetPixelShader ( CompileShader( ps 4 0, PShader() ) )"} {"_id": 34, "text": "How do I generate mipmap .png and model .obj files for LibGDX? I'm playing a bit with LibGDX (OpenGL ES 2.0 wrapper for Android). I found some sample code which used prepared files to load models and mipmap textures for them, e.g., at https github.com libgdx libgdx blob master demos invaders gdx invaders src com badlogic gdxinvaders RendererGL20.java it reads .obj file for the model and RGB565 format .png file to apply a mipmapped texture to it. What is the best easiest way for me to create these files? I understand .obj files are generated by a bunch of tools (I installed Blender, Wings3D and Kerkythea so far), but which ones will be the most user friendly for someone unfamiliar with 3D modelling? But more importantly, how do I produce a .png file with the mipmapped texture? The .png I looked at ( https github.com libgdx libgdx blob master demos invaders gdx invaders data ship.png ) seems to include different textures for each of the faces, probably created with some tool. I browsed through the menus for the 3 tools I have installed but didn't find an option to export such a .png file. What am I missing?"} {"_id": 34, "text": "LibGDX render sprites in tiled map format ( convert texture to sprite ) I am creating a game in which till now I have used textures to create A 2D tiled game. I have created a matrix which converts the touch co ordinates into a array index number and according to that index number, a specific tile gets selected. The problem is that I want to emulate the same behaviour for sprites instead of textures. But I get stuck on what could possibly be given as the co ordinates for the sprite position? I want to just use Sprites instead of using textures as Sprites are easier to animate. No matter which values I give, the screen remains white and sometimes a different tile's texture gets rendered at a different position. What am I doing wrong? Function returns the position of tile touched int getPos(int screenX, int screenY) x screenX (int)xSize y screenY (int)ySize y Squares Y 1 y int result y Squares X x return result Previous Render function public void render(float delta) batch.begin() Tile current initial layout if(current.topLink ! null) for (int Pos 0 Pos lt Squares X Pos ) for (int ypos 0 ypos lt Squares Y ypos ) batch.draw(bg texture, Pos xSize, ypos ySize, xSize, ySize) if(current! null) batch.draw(current.getTexture(), Pos xSize, ypos ySize, xSize, ySize) current current.topLink if(Gdx.input.justTouched()) if(win false) int x Gdx.input.getX() int y Gdx.input.getY() touchDown(getPos(x, y)) else System.out.print(\" nLevel Completed !! \" utils.level) game.dispose() batch.end() New Render Function public void render() batch.begin() Tile current initial layout if(current.topLink ! null) for (int Pos 0 Pos lt Squares X Pos ) for (int ypos 0 ypos lt Squares Y ypos ) batch.draw(bg texture, Pos xSize, ypos ySize, xSize, ySize) if(current! null) spriteBatch.begin() texture current.getTexture() sprite new Sprite(texture,(int)xSize,(int)ySize) sprite.setPosition(Pos xSize, ypos ySize) batch.draw(current.getTexture(), Pos xSize, ypos ySize, xSize, ySize) sprite.draw(spriteBatch) current current.topLink spriteBatch.end() if(Gdx.input.justTouched()) if(win false) int x Gdx.input.getX() int y Gdx.input.getY() touchDown(getPos(x, y)) else System.out.print(\" nGame WON for Level \" utils.level) game.dispose() batch.end()"} {"_id": 34, "text": "How to make part of the Texture not to be scaled.? I am new to LibGdx, i was doing one example for my learning and struck with this question, i had searched in google but i am not able to find the answer for this. 1) How to make part of the Texture not to be scaled. as you can see in the image i am reducing the height of bottom pipes so that the top pipe scale is reduced to fit the height given but i want the top part of the pipe not to be scaled. in this example whole pipe is one texture, for fixing this problem i thought to split the top and body to separate texture and set height for only body but i thought there should be some other solution so that only i had put this question here."} {"_id": 34, "text": "d3d11 black texture when manually creating from image (Rust) I am trying to create a ID3D11Texture2D from a RgbaImage loaded from a .jpg. The below code produces no errors. However, the texture is black when it is actually rendered. I know the standard way to load textures is through the DirectXTex library, but I was having issues linking with it and can't find any premade Rust bindings. Should the below code settings work to create a working ID3D11Texture2D? Is there a way to view the contents of a ID3D11Texture2D in order to debug? Are there DirectXTex bindings for Rust? fn load resource from file(device amp Device, path amp Path) gt error Result lt Texture gt unsafe let image Reader open(path)?.decode()?.to rgba() let mut sample desc dxgitype DXGI SAMPLE DESC default() sample desc.Count 1 sample desc.Quality 0 let mut desc d3d11 D3D11 TEXTURE2D DESC default() desc.Width image.width() desc.Height image.height() desc.MipLevels 1 desc.ArraySize 1 desc.Format dxgiformat DXGI FORMAT R8G8B8A8 UINT desc.Usage d3d11 D3D11 USAGE DEFAULT desc.SampleDesc sample desc desc.BindFlags d3d11 D3D11 BIND SHADER RESOURCE desc.CPUAccessFlags 0 desc.MiscFlags 0 let mut data d3d11 D3D11 SUBRESOURCE DATA default() data.SysMemPitch (image.sample layout().width stride mem size of lt Rgba lt u8 gt gt ()) as u32 let buffer Vec lt u8 gt image.into raw() data.pSysMem buffer.as ptr() as const data.SysMemSlicePitch buffer.len() as u32 let mut texture ptr null mut() device.as ref().CreateTexture2D( amp desc, amp data, amp mut texture, ).result()? let texture NonNull new(texture).ok or(null ptr err!())? drop(buffer) let mut resource view ptr null mut() device.as ref().CreateShaderResourceView( amp texture.as ref() as const d3d11 ID3D11Resource as mut , ptr null(), amp mut resource view, ).result()? let resource view NonNull new(resource view).ok or(null ptr err!())? Ok( Texture(Arc new(TextureInner texture, resource view, )))"} {"_id": 34, "text": "Rendering Texture Quad to Screen or FBO (OpenGL ES) I need to render the texture on the iOS device's screen or a render to texture frame buffer object. But it does not show any texture. It's all black. (I am loading texture with image myself for testing purpose) Load texture data UIImage image UIImage imageNamed \"textureImage.png\" GLuint width FRAME WIDTH GLuint height FRAME HEIGHT Create context void imageData malloc(height width 4) CGColorSpaceRef colorSpace CGColorSpaceCreateDeviceRGB() CGContextRef context CGBitmapContextCreate(imageData, width, height, 8, 4 width, colorSpace, kCGImageAlphaPremultipliedLast kCGBitmapByteOrder32Big) CGColorSpaceRelease(colorSpace) Prepare image CGContextClearRect(context, CGRectMake(0, 0, width, height)) CGContextDrawImage(context, CGRectMake(0, 0, width, height), image.CGImage) glGenTextures(1, amp texture) glBindTexture(GL TEXTURE 2D, texture) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexImage2D(GL TEXTURE 2D, 0, GL RGBA, width, height, 0, GL RGBA, GL UNSIGNED BYTE, imageData) glTexParameterf(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameterf(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP TO EDGE) Simple Texture Quad drawing code mentioned here Bind Texture, Bind render to texture FBO and then draw the quad const float quadPositions 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0 const float quadTexcoords 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0 stop using VBO glBindBuffer(GL ARRAY BUFFER, 0) setup buffer offsets glVertexAttribPointer(ATTRIB VERTEX, 3, GL FLOAT, GL FALSE, 3 sizeof(float), quadPositions) glVertexAttribPointer(ATTRIB TEXCOORD0, 2, GL FLOAT, GL FALSE, 2 sizeof(float), quadTexcoords) ensure the proper arrays are enabled glEnableVertexAttribArray(ATTRIB VERTEX) glEnableVertexAttribArray(ATTRIB TEXCOORD0) Bind Texture and render to texture FBO. glBindTexture(GL TEXTURE 2D, GLid) Actually wanted to render it to render to texture FBO, but now testing directly on default FBO. glBindFramebuffer(GL FRAMEBUFFER, textureFBO pixelBuffernum ) draw glDrawArrays(GL TRIANGLES, 0, 2 3) What am I doing wrong in this code? P.S. I'm not familiar with shaders yet, so it is difficult for me to make use of them right now."} {"_id": 34, "text": "How AAA games use this texture in the tone mapping shader? I found that Battlefield 3 as well as Saint's Row the Third use this texture in their final tone mapping stage. Can anyone share a link to an article about how this texture is used? UPDATE As there are hardly any examples of Color Grading implementation on the net, I will post my quick and dirty sample for XNA 4.0. This does nothing but builds the default 2d colormap from scratch on GPU, copies it's contents into a 3d texture on CPU and performs the actual color correction with the shader code from the article provided in the answer. XNA 4.0 Color Correction Sample If you want to know what you can do with this, look here http the witness.net news 2012 08 fun with in engine color grading In short the author explains there, how you can basically make a screenshot of your normal in game image with the default color grading palette on top, perform screenshot color correction in photoshop, cut and copy the deformed color correction palette into the engine and have that color correction applied for every in game scene automatically."} {"_id": 34, "text": "Capturing small details in textures without making a huge map Ex. Nuts and bolts on a cabinet. Said items are tiny relative to the cabinet, and on a texture map looks like an indistinguishable dot. Is it worth it to separate these tiny details into a mesh of their own? Obvious cons are increasing poly count and draw calls, disregarding how much of an increase that would be. Is there a generally accepted way of going about this?"} {"_id": 34, "text": "Why loading 250mb of compressed texture data spills Out of memory error on Windows I am making SDL2 OpenGL 2D game for Windows with a lot of pre rendered sprites. When testing on my laptop I got SDL Surface creation failed out of memory error during loading assets. Windows' Application Manager on other machine shows that my game in stress uses less then 170 mb of ram memory and MSI Afterburner shows that vram usage for entire system is below 800 mb. My laptop has 8 gb of RAM and 2048 mb of vram (GeForce 840 M). I am obviously doing something terribly wrong, but I don't know wheres my ram usage counting technique is wrong, or maybe for some reasons I have less memory then available on system, or something completely else is happening. But I don't know where to search for. I will gladly post some code if I need to, but I don't know which parts will be useful in diagnosing the problem. One more thing, I am using GL COMPRESSED RGBA ARB for all textures Edited It's not exactly the same situation as what's described here. I've already measured vram usage, and numbers are way below available count, yet still I get out of memory error. So, the question is \"How measure properly vram usage\", not \"How measure vram usage\", as in other question. I am not a native English speaker, so maybe there is some cloud in my title I will gladly accept correction for title Edited I reckon the image load procedure might be useful here, since it is heavily related to issue. Game Texture Game Asset GetTex(const UString amp path) Texture ret assetsTex path if (ret) return ret const UString amp absolutePath GetAbsolutePath(path) SDL Surface surface IMG Load(absolutePath.GetCStr()) if (!surface) ERR( U(\"Failed to load surface 1 \"), UString FromA(IMG GetError())) Here's my problem! int bpp surface gt format gt BytesPerPixel UInt8 pixels (UInt8 )surface gt pixels if (bpp ! 3 amp amp bpp ! 4) WARN( U(\"Texture ' 1 ' is not 24 bpp or 32 bpp! Aborting load...\"), path) SDL FreeSurface(surface) return nullptr GLuint tex glGenTextures(1, amp tex) glBindTexture(GL TEXTURE 2D, tex) if (bpp 3) glTexImage2D(GL TEXTURE 2D, 0, GL COMPRESSED RGBA ARB, surface gt w, surface gt h, 0, GL RGB, GL UNSIGNED BYTE, pixels) else if (bpp 4) glTexImage2D(GL TEXTURE 2D, 0, GL COMPRESSED RGBA ARB, surface gt w, surface gt h, 0, GL RGBA, GL UNSIGNED BYTE, pixels) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP TO EDGE) ret new Texture(tex, surface gt w, surface gt h) SDL FreeSurface(surface) assetsTex path ret return ret Edited I moved from SDL Image to stb image for image load, but I still got out of memory error message Edited I've installed VS Studio 2015 on my laptop and found out Task Manager shows application eats up 650 mb in the moment of Out of memory casted GetProcessMemoryInfo returns PeakWorkingSetSize 720 mb and WorkingSetSize 650 mb as well But Visual 2015 UI (Debug Diagnostic, memory usage) shows that application actually consumed 1.7 gb. Even if this is true and both former are not, there is still plenty of room for allocations (application is 32 bit, there are 8 gb of on board memory, not counting page file) I tried to convert png tga and load them up, to check if png uncompressing is eating memory, but the result was exactly the same, the same Out of memory error Out of memory is spit in png load function which has nothing to do with OpenGL and GPU at all. I am retagging and retitleing the post"} {"_id": 34, "text": "OpenGL ES 2.0. Sprite Sheet Animation I've found a bunch of tutorials on how to make this work on Open GL 1 amp 1.1 but I can't find it for 2.0. I would work it out by loading the texture and use a matrix on the vertex shader to move through the sprite sheet. I'm looking for the most efficient way to do it. I've read that when you do the thing I'm proposing you are constantly changing the VBO's and that that is not good. Edit Been doing some research myself. Came upon this two Updating Texture and referring to the one before PBO's. I can't use PBO's since i'm using ES version of OpenGL so I suppose the best way is to make FBO's but, what I still don't get, is if I should create a Sprite atlas batch and make a FBO loadtexture for each frame of if I should load every frame into the buffer and change just de texture directions."} {"_id": 34, "text": "Is it possible to use unnormalized texture coordinates from a GLES2 GLSL fragment shader? I want to look up a texel from my GLES2 GLSL fragment shader using un normalized texture coordinates (0 w, 0 h instead of 0 1, 0 1). The reason is that this texture is used as a look up table and I get precision problems with normalized coordinates. I see that GL TEXTURE RECTANGLE is not supported wihtout extensions and neither is texelFetch(), so I have ruled out those options. Thanks!"} {"_id": 35, "text": "How to pass arguments with BungeeCord Bukkit plugin messaging I am trying to send a plugin message from Bukkit, to BungeeCord, but can not figure out how to send arguments. Here is the code from the Bukkit plugin, which sends the message ByteArrayDataOutput out ByteStreams.newDataOutput() out.writeUTF(\"BungeeCord\") out.writeUTF(\"Argument\") If you don't care about the player Player player Iterables.getFirst(Bukkit.getOnlinePlayers(), null) Else, specify them Player plr Bukkit.getPlayerExact(\"spacegeek224\") plr.sendPluginMessage(p, \"BungeeCord\", out.toByteArray()) Here is the code in the main class of my BungeeCord plugin Override public void onEnable() this.getProxy() ProxyServer.getInstance().getPluginManager().registerListener(this, new ChannelListener()) this.getProxy() ProxyServer.getInstance().registerChannel(\"Return\") And finally, here is the code for the ChannelListener package net.spacegeek224.metro.util import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.DataInputStream import java.io.DataOutputStream import java.io.IOException import net.md 5.bungee.api.ProxyServer import net.md 5.bungee.api.chat.BaseComponent import net.md 5.bungee.api.chat.ComponentBuilder import net.md 5.bungee.api.config.ServerInfo import net.md 5.bungee.api.event.PluginMessageEvent import net.md 5.bungee.api.plugin.Listener import net.md 5.bungee.event.EventHandler public class ChannelListener implements Listener EventHandler public void onPluginMessage(PluginMessageEvent e) if (e.getTag().equalsIgnoreCase(\"BungeeCord\")) DataInputStream in new DataInputStream(new ByteArrayInputStream(e.getData())) try String channel in.readUTF() channel we delivered if(channel.equals(\"BungeeCord\")) ProxyServer.getInstance().broadcast(new ComponentBuilder(e.getReceiver().toString()).create()) else ProxyServer.getInstance().broadcast(new ComponentBuilder(e.getReceiver().toString() \" \" channel).create()) catch (IOException e1) e1.printStackTrace() public void sendToBukkit(String channel, String message, ServerInfo server) ByteArrayOutputStream stream new ByteArrayOutputStream() DataOutputStream out new DataOutputStream(stream) try out.writeUTF(channel) out.writeUTF(message) catch (IOException e) e.printStackTrace() server.sendData(\"Return\", stream.toByteArray()) I have tried many things, including Google, and looking at what other methods are available, but have come up with nothing."} {"_id": 35, "text": "Minecraft Forge 1.8 Custom Recipe Manager, need help sorry for asking this question. Some of you will probably find it very easy but I just can't figure out how to do it. I want to write a custom Recipe Manager. It has to check the recipes. Therefor I create an ArrayList lt Item gt recipes new ArrayList() The Item Array store 4 items(3 inputs and one output) Item items Item1, Item2, Item3, Item4 I want to get a function that does this I give it a Item and it gives me an ArrayList containing all the Item s containing that Item as the 0th index and a Boolean that is true when there is any Item containing the Item. Then I give (if needed to another function) an second Item. It returns me a new ArrayList containing all of the previous Item s that containe the Item and a Boolean similiar to 1 but for the 1th index. Analog to 2. (I think you get what I mean). The 3 points have to be handled in another method call. Thank you very much in advance Nova"} {"_id": 35, "text": "How do I fix a \"missing mcp.cfg\" error? I am trying to use mod coder pack (MCP) to create mods of my own. I have downloaded MCP 9.4 version from www.modcoderpack.com. The error that I have encountered is that when I try to run a file called decompile.sh in the mac terminal, the terminal responds with an error ERROR root !! Missing mcp.cfg. I have checked my MCP folder and made sure that it contained the file mcp.cfg. The file is in my folder. I am currently running on a Macbook Pro with MacOS Mojave Version 10.14.4."} {"_id": 35, "text": "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. For 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). The 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. The 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). This is probably due to my shaky hands, as the controller's data is seemingly exact. I tried filtering input by averaging data from the last X frames, but this makes input seem buttery. My question is How can I filter the rotational data to remove jitter without loosing precision?"} {"_id": 35, "text": "How can I mod Minecraft 1.7.9? I've looked up a lot of tutorials on YouTube and all of them only work for versions of Minecraft prior to 1.7.9. I first got a Minecraft Coder Pack (MCP) off of this website, but then realized that only decompiles Minecraft 1.6.4. Then I found a more recent MCP (that's not on the website for some reason) and it is version 9.03, downloaded here. This decompiles Minecraft version 1.7.2 (when I followed this video's instructions, I run the decompile.bat file and it says Json file not found in C Users mike AppData Roaming .minecraft versions 1.7.2 1.7.2.json). Basically I can't decompile Minecraft 1.7.9, but I can decompile older versions. However, I don't have any older versions downloaded onto my computer. I have only 1.7.9. Then I tried using Forge, but realized that most videos were using versions of Minecraft prior to 1.6.4, meaning they use the bin folder that does not exist anymore. Even after trying to figure that out as well, the decompiling would never work. I tried to do what this video did, but couldn't replicate it. Then I finally looked at this video about using Forge and I could replicate it, but this didn't decompile Minecraft. It just set up a workspace in Eclipse that I'm not sure how to use. TL DR I can decompile Minecraft 1.6.4 and 1.7.2 but I can't decompile version 1.7.9. Should I download an older version of Minecraft, wait for an MCP for 1.7.9, or something else? Is there something I'm missing, where I actually can decompile and mod Minecraft 1.7.9?"} {"_id": 35, "text": "How do you make Minecraft mods? I'm new to making minecraft mods and I'm wondering what I need to do to get started."} {"_id": 35, "text": "How can I use IntelliJ to make Minecraft mods? I'm starting out creating Minecraft mods with my son. I've seen one YouTube tutorial which sets up project with Eclipse. Since I don't like Eclipse much, I ask how would I setup IntelliJ or Android Studio(if feasible) to develop Minecraft mods? My son specifically want to create roller coaster mods."} {"_id": 35, "text": "No MODS button in Windows Minecraft when selecting Forge profile I have installed a Minecraft launcher in Windows that supports Minecraft 1.14. I have installed Forge 1.14.4 forge 28.0.13. I have created the mods folder and placed a mod jar in it which is Xaeros Minimap 1.17.4 Forge 1.14.4. I have selected the Forge profile in the launcher. When running the launcher, I have to remove JVM option XX CMSIncrementalMode in order to run it (also when running the regular profile). I have Java 11 installed. But after launching, there is no MOD button in the menu. What could be the problem?"} {"_id": 35, "text": "How do I use the Minecraft Coder Pack on Linux I downloaded the Minecraft coder pack to mod the game and decompile it, but how do I use it on Linux. Some sources seem to give specific directions, but they are not clear and they involve executing the .bat files. My Ubuntu does not recognize .bat file. How do I decompile a class file from changing a Minecraft version jar file to a zip and unzipping it? How do I decompile one of those class files using Minecraft coder pack? I have been wondering what at least some of the Minecraft source code looks like."} {"_id": 35, "text": "How can I mod a Minecraft slime to be about the size of a full block? I want to make the slime's size roughly the size of a full block, I have tried some values but I'm not sure if any of those I tried fit the idea I have. What would you recommend for the size of the slime which roughly matches or matches a block's size?"} {"_id": 35, "text": "Minecraft Forge Look for Entities in a Certain Location The title mostly explains it. I have a tile entity that is called Energizer. I want this energizer to check to see if there is an EntityItem on top of it and if so, consume it and create energy. The only problem is, I can't figure out how to check for (and receive) an EntityItem in a certain location (on top of it). I considered using a method that searches for nearby entities and then seeing if they were instanceof EntityItem, but I can't even find a method to do that."} {"_id": 35, "text": "How to pass arguments with BungeeCord Bukkit plugin messaging I am trying to send a plugin message from Bukkit, to BungeeCord, but can not figure out how to send arguments. Here is the code from the Bukkit plugin, which sends the message ByteArrayDataOutput out ByteStreams.newDataOutput() out.writeUTF(\"BungeeCord\") out.writeUTF(\"Argument\") If you don't care about the player Player player Iterables.getFirst(Bukkit.getOnlinePlayers(), null) Else, specify them Player plr Bukkit.getPlayerExact(\"spacegeek224\") plr.sendPluginMessage(p, \"BungeeCord\", out.toByteArray()) Here is the code in the main class of my BungeeCord plugin Override public void onEnable() this.getProxy() ProxyServer.getInstance().getPluginManager().registerListener(this, new ChannelListener()) this.getProxy() ProxyServer.getInstance().registerChannel(\"Return\") And finally, here is the code for the ChannelListener package net.spacegeek224.metro.util import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.DataInputStream import java.io.DataOutputStream import java.io.IOException import net.md 5.bungee.api.ProxyServer import net.md 5.bungee.api.chat.BaseComponent import net.md 5.bungee.api.chat.ComponentBuilder import net.md 5.bungee.api.config.ServerInfo import net.md 5.bungee.api.event.PluginMessageEvent import net.md 5.bungee.api.plugin.Listener import net.md 5.bungee.event.EventHandler public class ChannelListener implements Listener EventHandler public void onPluginMessage(PluginMessageEvent e) if (e.getTag().equalsIgnoreCase(\"BungeeCord\")) DataInputStream in new DataInputStream(new ByteArrayInputStream(e.getData())) try String channel in.readUTF() channel we delivered if(channel.equals(\"BungeeCord\")) ProxyServer.getInstance().broadcast(new ComponentBuilder(e.getReceiver().toString()).create()) else ProxyServer.getInstance().broadcast(new ComponentBuilder(e.getReceiver().toString() \" \" channel).create()) catch (IOException e1) e1.printStackTrace() public void sendToBukkit(String channel, String message, ServerInfo server) ByteArrayOutputStream stream new ByteArrayOutputStream() DataOutputStream out new DataOutputStream(stream) try out.writeUTF(channel) out.writeUTF(message) catch (IOException e) e.printStackTrace() server.sendData(\"Return\", stream.toByteArray()) I have tried many things, including Google, and looking at what other methods are available, but have come up with nothing."} {"_id": 35, "text": "How do I add a custom mob to Minecraft? Basically decided to make my own mob, I have Created my mob's entity class Created my mobs model class Drawn the model Added the function call for addMapping within the EntityList class I'm stuck on what to do next. I've tried finding the code that deals with passive animal spawning in the world, however I can't seem to find it. Help greatly appreciated."} {"_id": 35, "text": "Minecraft Optifine where is the zoom class? I'm working on a mod where I want to have a zoom feature like Optifine. To start out, I want to try messing around with the zoom in the actual Optifine mod. There are a lot of .class files, and I don't want to decompile all of them one by one, so if anyone knows which one(s) have the zoom that would be super helpful."} {"_id": 35, "text": "Is there a way to drain durability from an item instead of a sword, for instance? I am modding Minecraft 1.8 using Eclipse with Forge, and I just wondered, is there a way to drain durability from a battery, for instance, instead of a piece of armor when hit. I have tried things like getting an item from the player's inventory and attempting to reduce its durability, so that would be a possibility, however, I was unable to find a way to do so?"} {"_id": 35, "text": "How can I teleport seamlessly, without using interpolation? I've been implementing Bukkit plugin for creating toggleable in game warping areas that will teleport any catched entity to other similar area. I was going to implement concept of non Euclidean maze using this plugin, but, unfortunately, I've discovered that doing Entity.teleport() causes client to interpolate movement while teleporting, so player slides towards target like Enderman and receives screen updates, so for a split second all underground stuff is visible. While for \"just teleport me where I want\" usage this is just fine, it ruins whole idea of seamless teleporting, as player can clearly see when transfer happened even without need to look at debug screen. Is there possibility to somehow disable interpolating while teleporting without modifying client, or maybe prevent client from updating screen while it's being teleported?"} {"_id": 35, "text": "How to pass arguments with BungeeCord Bukkit plugin messaging I am trying to send a plugin message from Bukkit, to BungeeCord, but can not figure out how to send arguments. Here is the code from the Bukkit plugin, which sends the message ByteArrayDataOutput out ByteStreams.newDataOutput() out.writeUTF(\"BungeeCord\") out.writeUTF(\"Argument\") If you don't care about the player Player player Iterables.getFirst(Bukkit.getOnlinePlayers(), null) Else, specify them Player plr Bukkit.getPlayerExact(\"spacegeek224\") plr.sendPluginMessage(p, \"BungeeCord\", out.toByteArray()) Here is the code in the main class of my BungeeCord plugin Override public void onEnable() this.getProxy() ProxyServer.getInstance().getPluginManager().registerListener(this, new ChannelListener()) this.getProxy() ProxyServer.getInstance().registerChannel(\"Return\") And finally, here is the code for the ChannelListener package net.spacegeek224.metro.util import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.DataInputStream import java.io.DataOutputStream import java.io.IOException import net.md 5.bungee.api.ProxyServer import net.md 5.bungee.api.chat.BaseComponent import net.md 5.bungee.api.chat.ComponentBuilder import net.md 5.bungee.api.config.ServerInfo import net.md 5.bungee.api.event.PluginMessageEvent import net.md 5.bungee.api.plugin.Listener import net.md 5.bungee.event.EventHandler public class ChannelListener implements Listener EventHandler public void onPluginMessage(PluginMessageEvent e) if (e.getTag().equalsIgnoreCase(\"BungeeCord\")) DataInputStream in new DataInputStream(new ByteArrayInputStream(e.getData())) try String channel in.readUTF() channel we delivered if(channel.equals(\"BungeeCord\")) ProxyServer.getInstance().broadcast(new ComponentBuilder(e.getReceiver().toString()).create()) else ProxyServer.getInstance().broadcast(new ComponentBuilder(e.getReceiver().toString() \" \" channel).create()) catch (IOException e1) e1.printStackTrace() public void sendToBukkit(String channel, String message, ServerInfo server) ByteArrayOutputStream stream new ByteArrayOutputStream() DataOutputStream out new DataOutputStream(stream) try out.writeUTF(channel) out.writeUTF(message) catch (IOException e) e.printStackTrace() server.sendData(\"Return\", stream.toByteArray()) I have tried many things, including Google, and looking at what other methods are available, but have come up with nothing."} {"_id": 35, "text": "Is there a way to drain durability from an item instead of a sword, for instance? I am modding Minecraft 1.8 using Eclipse with Forge, and I just wondered, is there a way to drain durability from a battery, for instance, instead of a piece of armor when hit. I have tried things like getting an item from the player's inventory and attempting to reduce its durability, so that would be a possibility, however, I was unable to find a way to do so?"} {"_id": 35, "text": "How to make blocks like \"redstone\" working in a minecraft like game when the chunks are not loaded I'm working on a 2D minecraft like game, I use chunks to save my world and each chunk has 128 128 blocks in it. And infinite chunks can create an infinite world. Memory should never be infinite and only several chunks near the character are shown on the screen and loaded into memory. How can I handle logic based blocks like red stone signals when they are in chunks far away and so not loaded in memory?"} {"_id": 35, "text": "How do I add a custom mob to Minecraft? Basically decided to make my own mob, I have Created my mob's entity class Created my mobs model class Drawn the model Added the function call for addMapping within the EntityList class I'm stuck on what to do next. I've tried finding the code that deals with passive animal spawning in the world, however I can't seem to find it. Help greatly appreciated."} {"_id": 35, "text": "No files in .net.minecraft So, I've been trying to make a minecraft 1.11.2 client for minecraft. Thing is, the mcp src minecraft folder is empty, without any net files. The only error I had while decompiling was missing lwjgl 2.9.4, which does not exist. I have everything ready, but those files are missing, and thus I cannot code anything on my client(I am only using allowed mods.) This is a massive project I am taking for my favorite server, and I would like some help. Can anyone be kind and tell me how to fix this? I have installed Optifine files for my client, and seems to have got about half of the files that I need. What I need What I have As you can see, I am missing a lot of packages and have errors in most of them."} {"_id": 35, "text": "how to ADD a NEW entity item effect to Minecraft Java In Minecraft Java, I am creating many resource packs by myself (no studio or external resource) so, I want to ADD a new file entity element items etc. to the game to not replace an old item because EVERY item effect entity has SOME use in the game. In conclusion how I can ADD not replace a file in the game and give it custom physical and mental properties?"} {"_id": 35, "text": "How can I check if player is an operator in Forge? In Minecraft Forge, I would like to know if there is any way to find out if a player currently has vanilla \"OP\" \"Operator\" status. I can't find a method that does this on the EntityPlayer Class. I'd like something like EntityPlayer player (EntityPlayer)sender if (player.getOpStatus) do some stuff"} {"_id": 35, "text": "What are names like \"net.minecraft.blocks\" called? I'm trying to find these types of names for certain Minecraft blocks to add them to a block whitelist for one of my mods. Is there an actual name for these? If not, how would I go about finding a list of or searching for them?"} {"_id": 35, "text": "Source code of Minecraft servers? Is there any way to get the source code of Minecraft servers? I tried decompiling but I get very obfuscated arguments, classes, and methods. If the answer is no, how did services like Bukkit and Spigot create their 'servers'?"} {"_id": 35, "text": "Minecraft Forge Look for Entities in a Certain Location The title mostly explains it. I have a tile entity that is called Energizer. I want this energizer to check to see if there is an EntityItem on top of it and if so, consume it and create energy. The only problem is, I can't figure out how to check for (and receive) an EntityItem in a certain location (on top of it). I considered using a method that searches for nearby entities and then seeing if they were instanceof EntityItem, but I can't even find a method to do that."} {"_id": 35, "text": "No MODS button in Windows Minecraft when selecting Forge profile I have installed a Minecraft launcher in Windows that supports Minecraft 1.14. I have installed Forge 1.14.4 forge 28.0.13. I have created the mods folder and placed a mod jar in it which is Xaeros Minimap 1.17.4 Forge 1.14.4. I have selected the Forge profile in the launcher. When running the launcher, I have to remove JVM option XX CMSIncrementalMode in order to run it (also when running the regular profile). I have Java 11 installed. But after launching, there is no MOD button in the menu. What could be the problem?"} {"_id": 35, "text": "Minecraft Mod making (MCreator) Redstone Result Event I am currently using a Mod making Tool called \"MCreator\" made by Pylo. I am currently making a Block Element and creating an event when The block is right clicked by a Prismarine Shard, then The block will power redstone. I did this by doing the following Event On block rightclicked Condition itemInPlayersHand Items.prismarine shard Event parameters (Redstone Power State of power) true I also checked \"Can provide power?\" In Advanced properties The problem is that when I test the mod in a client environment and click the block, it will not power any redstone around it. I tried to change when the event happens to Print a text and when I tested and clicked on it with a prismarine shard, it printed the text to the console. So is there something wrong with the Redstone Power event result or am I doing something wrong. Thanks in Advanced, Bryan"} {"_id": 35, "text": "How can I use IntelliJ to make Minecraft mods? I'm starting out creating Minecraft mods with my son. I've seen one YouTube tutorial which sets up project with Eclipse. Since I don't like Eclipse much, I ask how would I setup IntelliJ or Android Studio(if feasible) to develop Minecraft mods? My son specifically want to create roller coaster mods."} {"_id": 35, "text": "How to setup for live player observer pair w voice chat in Minecraft I'm trying to build a setup for educational use of Minecraft One person plays Minecraft, another person watches live online with the least lag latency possible, and the pair can talk over high quality voice chat. What is the best setup to allow this? Scenario A 1) Write a mod that allows a watcher to be a passive spectator through their copy of Minecraft? The watcher would see exactly what the player sees. Would this be the fastest and clearest picture? Is it a trivial mod to write? 2) Connect together over Hamachi? Can that be dead easy to set up? 3) Use a voice chat in the game itself? Scenario B 1) Use a streaming video technology. (Twitch? Google Hangouts? Something else?) 2) Third party voice chat like Skype. (Or just Google Hangouts?) My fear here is lag, low quality video, bandwidth. Scenario C ? Thanks very much for any help )"} {"_id": 35, "text": "Why Minecraft has such a terrible backward compatibility? For every release of Minecraft, even a minor release, is almost guaranteed to break some plugins or mod. Why is this so? I am asking this so that we could avoid the same architecture problem as Minecraft. I mean, why can't the upgrades also support previous version of minecraft? Minecraft requires an EXACT version number match in order to connect. I am pretty sure the protocol can be designed so that clients should ignore unsupported commands. For example, if there is new block introduced and the client doesn't understand it, they can just fall back to default dummy block so that players can still play but start seeing dummy wireframe block or so. Once they start seeing too much of wireframe blocks they know they should upgrade."} {"_id": 35, "text": "How do I add a method to a class without editing the source file? I am trying to add a method to a Minecraft source file, but I have to figure out how to do it without actually editing the source files, as it would be illegal to redistribute Minecraft's source files with the mod I am creating. I need to add the method setInPortalZub() to the EntityPlayer class located in net.minecraft.entity.player. I am using the MCP Minecaft Forge API. I have tried creating an EntityPlayer instance, but I'm not exactly sure how to make this work."} {"_id": 35, "text": "How much more do I have to learn? So I started learning java sometime ago and now I am understanding packages. My main goal is to do minecraft modding. Can someone with modding experience please tell me how hard(or easy) minecraft modding is? And how much time will it take for me to get to a level when I can start modding?"} {"_id": 35, "text": "Where do I write code in my minecraft modding environment? So this is probably a stupid question but I'm just beginning so I hope someone can help. I set up my whole modding environment in eclipse but the problem is that I don't know where to start writing code that will be run while playing the game. I'm used to there being a run method that will constantly loop and run the code within that method but there doesn't seem to be such a thing. I tried putting stuff in my main class under the init event handler but that just crashed my game. I was just testing stuff out and tried putting this code in the init area which caused the game to crash when I tried running the client Entity player Minecraft.getMinecraft().player if(player.posX gt 100.0) player.posX 12.0"} {"_id": 35, "text": "How do I add a custom mob to Minecraft? Basically decided to make my own mob, I have Created my mob's entity class Created my mobs model class Drawn the model Added the function call for addMapping within the EntityList class I'm stuck on what to do next. I've tried finding the code that deals with passive animal spawning in the world, however I can't seem to find it. Help greatly appreciated."} {"_id": 35, "text": "How much more do I have to learn? So I started learning java sometime ago and now I am understanding packages. My main goal is to do minecraft modding. Can someone with modding experience please tell me how hard(or easy) minecraft modding is? And how much time will it take for me to get to a level when I can start modding?"} {"_id": 35, "text": "Why aren't ModLoader's decompiled files showing up? I want to start making a Minecraft 1.6.4 mod, but have this trouble with ModLoader I've run the decompile.bat batch file, but when opening the eclipse folder, the bin folder is empty. The batch file ran fine with no errors, and src minecraft net minecraft contains many decompiled java files, but no modloader files like BaseMod.java. If I open this folder with Eclipse, the package explorer menu stays empty. What's happening here?"} {"_id": 35, "text": "Minecraft Forge modding 1.8 instance changing tool armor material color I am developing a minecraft mod in forge, and I need to find a way to create tools and armor where individual instances of items would have different tool material properties, armor material properties, and hues in how they are displayed. If you can offer help for any of those things, or for how to achieve these dynamic properties in general, I would be very appreciative."} {"_id": 35, "text": "Minecraft Bedrock behaviors drop items for player owner? I'm making a simple behavior pack for Minecraft's Bedrock Edition for my own experimenting the aim is to get tamed wolves to play fetch. The behavior pack is valid and loading, as it sort of works, but the part that isn't working is what I've been banging my head against for hours. As per the tutorial on the official wiki, I've copied entities wolf.json and entities player.json from the vanilla behavior pack to my pack and added to them, borrowing cues from the villager's behavior file and referring to the reference for BE's entity components. I've also modified the priorities of the tamed wolf's behaviors so picking up items (i.e. sticks) and sharing them are a higher priority than following the owner or breeding. wolf.json \"minecraft entity\" \"format version\" \"1.2.0\", \"component groups\" ... \"minecraft wolf tame\" ... \"minecraft behavior.pickup items\" \"priority\" 7, \"max dist\" 16, \"speed multiplier\" 1.5, \"track target\" true , \"minecraft inventory\" \"inventory size\" 1, \"private\" true , \"minecraft shareables\" \"items\" \"item\" \"minecraft stick\", \"want amount\" 1, \"surplus amount\" 1 , \"minecraft behavior.share items\" \"priority\" 6, \"max dist\" 16, \"speed multiplier\" 2, \"goal radius\" 2.0, \"entity types\" \"filters\" \"test\" \"is owner\", \"subject\" \"other\" , \"must see\" true ... player.json \"minecraft entity\" \"format version\" \"1.2.0\", \"components\" ... \"minecraft shareables\" \"items\" \"item\" \"minecraft stick\", \"want amount\" 2304, \"surplus amount\" 2304 Currently, a tamed wolf will run over to pick up a dropped stick within 16 blocks of it, but after that it simply resumes following me (its owner) and never drops shares its sticks. I've messed with the want amount and surplus amount of the sticks for both the player and wolf, but with absolutely no results."} {"_id": 35, "text": "What can I do about a \"missing mcp.cfg\" error? I am trying to use MCP. After trying to run decompile.sh, I manually ran decompile.py, getting the error \"ERROR root !! Missing mcp.cfg !!\" I tried to copy the variables from mcp.cfg into the files which reference them, but I still got the error. How can I fix this?"} {"_id": 35, "text": "Minecraft Players Held Item Type How can I check if a players held item is of a specific item type for example an axe. (can be iron axe, gold axe, wooden axe, etc.)? Or do I have to do multiple if statements to have this done? EventHandler(priority EventPriority.HIGH) public void onInteract(PlayerInteractEvent event) Player p event.getPlayer() ItemStack heldItem p.getInventory().getItemInMainHand() if(heldItem.getType() Material.DIAMOND AXE) I dont want to do multiple if statements for multiple type of Axes ... other if statement for Material.WOODEN AXE etc."} {"_id": 35, "text": "How minecraft manages interactable blocks (Chest)? I am wondering, how does minecraft handle blocks like chest? I guess normal blocks are ids in simple array, but how does it store and references blocks with special behaviour?"} {"_id": 35, "text": "How do I use the Minecraft Coder Pack on Linux I downloaded the Minecraft coder pack to mod the game and decompile it, but how do I use it on Linux. Some sources seem to give specific directions, but they are not clear and they involve executing the .bat files. My Ubuntu does not recognize .bat file. How do I decompile a class file from changing a Minecraft version jar file to a zip and unzipping it? How do I decompile one of those class files using Minecraft coder pack? I have been wondering what at least some of the Minecraft source code looks like."} {"_id": 35, "text": "Source code of Minecraft servers? Is there any way to get the source code of Minecraft servers? I tried decompiling but I get very obfuscated arguments, classes, and methods. If the answer is no, how did services like Bukkit and Spigot create their 'servers'?"} {"_id": 35, "text": "Is there a way to create a cellular automaton mod for Minecraft? I basically want to create a mod for Minecraft that does the following if(a sand block is next to lava block) change the sand block to a glass block Is it possible to create a mod like this without editing multiple Java classes?"} {"_id": 35, "text": "How do I modify the health of an entity after it has been created? Is there any way to add or remove health after an entity has been created? For example, I'd like to have a mob regenerate \"hearts\" when some event happens."} {"_id": 35, "text": "Is there a way to create a cellular automaton mod for Minecraft? I basically want to create a mod for Minecraft that does the following if(a sand block is next to lava block) change the sand block to a glass block Is it possible to create a mod like this without editing multiple Java classes?"} {"_id": 35, "text": "How can I read a portion of one Minecraft world file and write it into another? I'm looking to read block data from one Minecraft world and write the data into certain places in another. I have a Minecraft world, let's say \"TemplateWorld\", and a 2D list of Point objects. I'm developing an application that should use the x and y values of these Points as x and z reference coordinates from which to read constant sized areas of blocks from the TemplateWorld. It should then write these blocks into another Minecraft world at constant y coordinates, with x amp z coordinates determined based on each Point's index in the 2D list. The issue is that, while I've found a decent amount of information online regarding Minecraft world formats, I haven't found what I really need more of a breakdown by hex address of where what everything is. For example, I could have the TemplateWorld actually be a .schematic file rather than a world I just need to be able to read the bytes of the file, know that the actual block data starts always at a certain address (or after a certain instance of FF, etc.), and how it's stored. Once I know that, it's easy as pie to just read the bytes and store them."} {"_id": 35, "text": "Minecraft Forge setTextureName method not working I am attempting to make an item using the latest version of Forge. For some reason, the setTextureName method gives me an error that says The method setTextureName(String) is undefined for the type ItemKey I have been trying to fix this for a while, and notice that when I remove the quotation marks from the colon the error for setTextureName disappears, but I get an error on the colon that says Syntax error on token \" \", delete this token an error on the sign that says The operator is undefined for the argument type(s) String and finally an error on \"key\" that says The method setTextureName(String) is undefined for the type ItemKey This is my first time trying to make an item, so help would be greatly appreciated. EDIT I just figured out that if I change MODID to modid in the setTextureName method I stop getting an error message for setTextureName but instead get an error for modid saying that modid cannot be resolved or is not a field package com.arti.artismod import net.minecraft.item.Item import net.minecraft.creativetab.CreativeTabs public class ItemKey extends Item private String name \"key\" public ItemKey() setUnlocalizedName(ArtisMod.MODID \" \" \"key\") setTextureName(ArtisMod.MODID \" \" \"key\") setCreativeTab(CreativeTabs.tabMisc)"} {"_id": 35, "text": "How much more do I have to learn? So I started learning java sometime ago and now I am understanding packages. My main goal is to do minecraft modding. Can someone with modding experience please tell me how hard(or easy) minecraft modding is? And how much time will it take for me to get to a level when I can start modding?"} {"_id": 36, "text": "Pygame's rotation methods have crippling issues, but is it me or Python's pygame? http www.youtube.com watch?v lNJFxvR6ex8 amp feature youtu.be On rotate and rotozoom, can't find fixes on these on the internet, anywhere. Basically, the video is showing 4 things in this order 1. A ring image being rotated with .rotate. 2. A simple image being rotated with .rotate. 3. The ring rotated with .rotozoom. 4. The simple circle rotated with .rotozoom. The difference In 1 and 2, the images do not have that slight quiver movement, but are reduced in quality. It might be difficult to tell with the video quality, but the ring image is slightly pixelated blurred. In 3 and 4, the images are of equal better than 1 amp 2 quality when rotated with rotozoom, but they have this VERY SLIGHT but noticeable wobble about them. This is VERY noticable with test 3, where I put my mouse next to the circle outline, and you can see it move. ANY and all help will be greatly appreciated, AND this will help many people for a long time, i'm sure. Here are images of the differences in picture quality of rotate vs rotozoom http s189.beta.photobucket.com user ECSit library PyGame 20and 20Python"} {"_id": 36, "text": "How to set object's node's absolute rotation correctly? Usually when I want to rotate an object node in my Ogre scene I call the node's rotate() method. That rotates the node locally relative to it's current rotation. So for example, when I start with 0 rotation, then rotate twice for 5 degrees about one axis, then after the second call the object is rotated by 10 degrees in total. Now I need to set the absolute rotation of the node object directly, regardless of its current rotation. Thus, say I don't know the objects current rotation, I need to set it say to 45 degrees on the X axis. Something like setRotation(). I know there is a setOrientation() method in the SceneNode class, which expects a quaternion object. I also know that I can get the current orientation quaternion. What I don't know how can I use change this current orientation quaternion to set the new absolute rotation of the node? PS Crosspost at http www.ogre3d.org forums viewtopic.php?f 2 amp t 77710"} {"_id": 36, "text": "3d rotation of a Gunner unit to shoot the target I'm developing a scenario to shoot incoming targets by a specific gunner unit, however I'm confused to actual logic of shooting an object with a gun. I'm working in 3D environment. I'v target's position vector i.e x,y,z and its rotation vector x,y,z,angle , and also Gun's position vector i.e x,y,z and its rotation vector x,y,z,angle . The gun has two components, i.e a TopDondur and a set of Barrels, both components have the rotation along y axis, i.e only angel of rotation vector 0 1 0 angle is required to move the Gunner Unit to the target. What rotataions shuould give the Gunner unit to rotate both TopDondur and Barrels, i.e TopDondur rotates to the target and Barrels are to move up down with respect to that target."} {"_id": 36, "text": "Converting 3 axis vectors to a rotation matrix I am trying to get a rotation matrix (in 3dsmax) from 3 vectors that form an axis (all 3 vectors are aligned by 90 degrees each other) Somewhere I read that I could build a rotation matrix just by inserting in every row one vector at a time (source http renderdan.blogspot.cz 2006 05 rotation matrix from axis vectors.html) So, I built a matrix with these example vectors x axis 0.194624, 0.23715, 0.951778 y axis 0.773012,0.634392,0 z axis 0.6038, 0.735735,0.306788 But for some reason, if I try to convert this matrix to eulerangles, I receive this rotation (eulerAngles 47.7284 6.12831 36.8263) ... which is totally wrong, and doesn't align to my 3 vectors at all. I know that rotation is quite difficult to understand, may someone shed some light? )"} {"_id": 36, "text": "Get 3D quad rotation matrix from points I have 4 3D points which represent a even quad in space. (So 3 points are sufficient) I need to get all the individual transformations (translation, rotation, dimensions) so that I can build that quad in my CSS 3D engine. So the default normal vector for a quad is 0, 0, 1 . What I have so far 4 points p0, p1, p2, p3 normal normal cross(p1 p0, p2 p0) axis and angle axis cross( 0, 0, 1 , normal) angle arccos(dot( 0, 0, 1 , normal)) rotation matrix rotationMatrix matrix4.fromAxisAngle(axis, angle) width and height width sqrt((p2.x p1.x) 2, (p2.y p1.y) 2, (p2.z p1.z) 2) height sqrt((p1.x p0.x) 2, (p1.y p0.y) 2, (p1.z p0.z) 2) translation x (p0.x p1.x p2.x p3.x) 4 y (p0.y p1.y p2.y p3.y) 4 z (p0.z p1.z p2.z p3.z) 4 It almost works, but some rotations are wrong or more specifically one rotation axis is missing. This is logical because the rotation is only build from the normal. So how can I get the full rotation? Here you see that the top and bottom quads are just rotated around the x axis but the y axis rotation is missing"} {"_id": 36, "text": "Rotating and pitching a turret I am new to game development and I was trying to build a turret model, and control it through lua script in shiva3d. I can rotate it around the y axis which is no problem, but when it comes to pitching, I am not sure how to do that in a way which is independent of the Y rotation, for example, in the default position, rotating with a positive value around X aims upwards, which is what I expect. when I rotate it by 180 degrees around Y, the positive rotation around X aims downwards towards the ground instead of upwards. on the other hand, if I rotate by 90 degrees, the turret rotates around it self as if its rolling... I am not sure what to look for in order to understand how rotation in a 3d world should happen, so any pointers on that would be much appreciated"} {"_id": 36, "text": "Error in plane transformation I have a bunch of coplanar points, who sit on plane P. I want to translate the plane to Q with the points upon. Here is what I do I take three points from P, say a, b, c. Their centroid is denoted by c(a,b,c). I pick the local origin as O c(a,b,c) and local XYZ as x normalize(Oa) v normalize(Ob) z x.crossProduct(v) y x.crossProduct(z) I apply the same method to their global coordinates on Q, which are d, e, f. O c(d,e,f) x normalize(Od) v normalize(Oe) z x .crossProduct(v ) y x .crossproduct(z ) Then, I use the transformation matrix as follows Matrix input x,y,z Matrix output x ,y ,z Matrix T output.multiply(input.transpose()) After this step, I multiply the coordinates of a point p that sit in plane P with matrix T. Of course, before that, I take the vector difference p O. The result should be the transformed point minus target origin (q O ). Hence, for each p in P, I transform p to its place in Q, which is denoted by q using the following computation q T.multiply(p.subtract(O)).add(O ) But what I get is, the reflection of the points through an imaginary (I don't know which) axis. Am I missing some step? Is there a wrong computation?"} {"_id": 36, "text": "How can I keep the clicked point under the mouse when rotating? (GLM) I have a spherical mesh of radius 1, centered at (0,0,0) in world coordinates. I want to rotate the sphere so that the clicked point remains under the mouse at all times. However, I cannot find an algorithm that does this. The clicked point always drifts away from the mouse. My current algorithm does the following Cast a ray to a sphere of radius 1. Find intersection point in world coordinates (Pa). After the mouse is moved, cast another ray and find a new intersection point. (Pb) since both those 3D points are on a sphere of radius one, centered at the origin, they should have length 1 but just in case I normalize them both. Find the rotation axis by doing Pa x Pb. Normalize the resulting axis axis glm cross(Pa,Pb) axis glm normalize(axis) Find the angle by doing arccosine on the dot product float angle glm acos(glm dot(Pa,Pb)) Build a rotation matrix from the axis and angle mat4 rotation glm rotate(glm degrees(angle),axis) lt This was the mistake glm degrees is not needed Multiply the existing model matrix by that calculated matrix modelMatrix rotation modelMatrix The rotations are correct but the clicked point does not stay under the mouse (I am checking by drawing a black square point on the sphere texture when the drag starts). If I click and drag to the right, the initially clicked point drifts to the left (lags)."} {"_id": 36, "text": "How to eliminate roll rotation? Let's say I have Rotation(0, 0, 180) pitch, yaw, roll . How to do it that I would have Rotation(180, 180, 0) which is exactly the same?"} {"_id": 36, "text": "How do I create a rocket projectile that is \"dropped\", then accelerates toward the enemy? I'm making an Asteroids like game. I've successfully implemented linear bullets. Now I want to add some rocket styled bullets, with a certain flight path The rockets should be \"dropped\" back first, then accelerate towards the enemy. I'm having difficulty making this work when the shooter is rotated. To visualize what I mean Bullets have a lifeTime which increases every frame."} {"_id": 36, "text": "How to map absolute Joystick position to object rotation? In my (Ogre) 3d scene I have an object that should be rotated locally based on Joystick input. I have a Joystick with min max values of 32767, 32767 on both X and Y axes. When the Joystick is in its origin position, the object should not be rotated. When the user moves the Joystick, the object in the 3d scene should follow this movement (or better orientation) up to a max. of 45 degrees on both axes. Or in other words when the user moves the Joystick e.g. fully to the left, the object's orientation in the 3d scene should be set to 45 degrees on the according axis. Being new to 3d programming I searched on the Internet on how to achieve this. I think to understand that I want to use Quaternions for this task. I found some examples and tutorials on how to use Quaternions for rotating objects. What I don't understand though is how I can map from the Joystick's current absolute axes positions to the absolute, local rotation of an object. I see that I could use the rotate() method of the object's node to set its rotation, but I understand that this rotates the object relatively to it's current position. But instead I want to map from the Joystick's absolute position to the absolute orientation rotation of the object in the scene. Any advice how I should approach this?"} {"_id": 36, "text": "from normal to rotation matrix (i'm on OPENGL) i have a mesh O (object) and a mesh T (terrain). i know a single triangle in T and i want to orient O to be aligned to that triangle (torate O to align to T in that point). i have only the normal in the triangle. how can i achive the roation matrix? i have thought this algorithm pseudocode float normal2rotation(Vector3D normal) angleX Vector3D.angleBetween(normal, Vecto3D.Axis3D.X) angleY Vector3D.angleBetween(normal, Vecto3D.Axis3D.Y) angleZ Vector3D.angleBetween(normal, Vecto3D.Axis3D.Z) float result angleX, angleY, angleZ return result but it does not give me the desired result."} {"_id": 36, "text": "What is an efficient way to get a look at direction from either a quaternion or a transformation matrix? So, I have an object in my custom engine (C ), with a column major transform in world space. I'm using a package that takes a look at direction as an input. What's the most efficient way to get a look at direction from this transform? Do I extract the rotation matrix? Do I try to extract a quaternion?"} {"_id": 36, "text": "How do I determine the forward right direction when I have the \"up\" vector? Unity I am trying to fix a gameobject for e.g. a cube (which i am using as a sensor) on my character. I need the cube to rotate (with orientation control from the inspector I have a public quaternion rotation variable set). I have identified 3 vertices using ray cast to fix my sensor onto the character. I already have determined the normal of these vertices which will be the \"up\" direction of the cube. I am wondering how I can determine the forward right vector to use in the LookRotation() function. I need to basically be able to rotate the cube ON the character even as the character moves on animation. This is my code, and as of now there is no rotation happening. I'm sure I am missing something and would really appreciate help. I really hope this is enough explanation. using System.Collections using System.Collections.Generic using UnityEngine public class orientation MonoBehaviour importing from Vertex Finder Script to use InterpolatedNormalInWorldSpace value private VertexFinder script public Transform target to edit orientation of sensor in Unity Inspector public Quaternion rotation edit Start is called before the first frame update void Start() script GetComponent lt VertexFinder gt () Quaternion TurretLookRotation(Vector3 approximateForward, Vector3 exactUp) Quaternion rotateZToUp Quaternion.LookRotation(exactUp, approximateForward) Quaternion rotateYToZ Quaternion.Euler(90f, 0f, 0f) return rotateZToUp rotateYToZ Update is called once per frame void Update() Vector3 relativePos target.position transform.position aligning axes of sensor to z axis and y axis respectively Quaternion rotation1 TurretLookRotation(relativePos, script.interpolatedNormalInWorldSpace) setting rotation of sensor to values entered in Inspector with respect to the above aligned axes transform.rotation rotation1 rotation edit"} {"_id": 36, "text": "Increasing the rotation angle on a quaternion makes the rotation stop at a certain angle I'm using the following code to change the rotation of an object Quaternion rot getRotation() setRotation(make quaternion axis angle(rot.v,rotationSpeed dt) rot) This code works as expected until a certain angle where it suddenly stops. Why does it stop?"} {"_id": 36, "text": "Quaternion rotation is inverse of what I expect I'm trying to learn quaternions and decided to implement my own quaternion class. To test it I made a couple vertex shaders, one that gets a model matrix (calculated from the quaternion) and another that gets the rotation quaternion directly and rotates vertices in shader. I then feed these a quaternion that rotates around the Y axis t 10000 radians (t time) const rotation Quat.fromAxisAngle(new Vec3( 0, 1, 0 ), t 10000) The result surprises me because my model is rotating counter clockwise but I expected it to rotate clockwise, since the angle is increasing (checked it, quat's xyz increase with time). Rotation around the X or Z axes is also backwards. All translations as well as matrix rotations work as expected in my coordinate system. I suspect my formulas are wrong, and probably assume Z is forward. If I transpose my model matrix (or post multiply with it) it rotates as expected, which suggests it's a handedness problem. Where are my formulas wrong and how can I understand the math behind this? Details My matrices are column major in memory (to match GLSL's mat4). My coordinate system is X right, Y up, Z forward. My code Quaternion from axis angle function fromAxisAngle(axis Vec3, angle number, dest new Quat()) Quat angle 0.5 const sin Math.sin(angle) dest.x axis.x sin dest.y axis.y sin dest.z axis.z sin dest.w Math.cos(angle) return dest Note I noticed if I negate this quaternion's x, y and z, everthing works as expected. Is this the root cause? I thought quaternions didn't have handedness! Since this is actually just inverting the quaternion (and thus its rotation) I'm afraid I'm just patching over the root cause. I don't want to patch the issue, I want to fix my math! Matrix from quaternion toMat4(dest new Mat4()) Mat4 const x, y, z, w this const x2 x x const y2 y y const z2 z z const xx x x2 const xy x y2 const xz x z2 const yy y y2 const yz y z2 const zz z z2 const wx w x2 const wy w y2 const wz w z2 Notice matrix is column major Source https en.wikipedia.org wiki Quaternions and spatial rotation Quaternion derived rotation matrix dest.init( 1 (yy zz), xy wz, xz wy, 0, xy wz, 1 (xx zz), yz wx, 0, xz wy, yz wx, 1 (xx yy), 0, 0, 0, 0, 1, ) return dest Matrix vertex shader precision mediump float attribute vec3 aVertexPosition attribute vec2 aVertexUV uniform mat4 uModelMatrix uniform mat4 uViewMatrix uniform mat4 uProjectionMatrix varying vec2 vUV void main(void) vUV aVertexUV gl Position uProjectionMatrix uViewMatrix uModelMatrix vec4(aVertexPosition.xyz, 1.0) Quaternion vertex shader precision mediump float attribute vec3 aVertexPosition attribute vec2 aVertexUV struct Transform float scale vec3 translation vec4 rotation uniform Transform uModel uniform Transform uView uniform mat4 uProjection varying vec2 vUV Source https twistedpairdevelopment.wordpress.com 2013 02 11 rotating a vector by a quaternion in glsl vec3 rotateVector(vec4 quat, vec3 vec) return vec 2.0 cross(cross(vec, quat.xyz) quat.w vec, quat.xyz) void main(void) vUV aVertexUV vec3 world rotateVector(uModel.rotation, aVertexPosition uModel.scale) uModel.translation vec3 view rotateVector(uView.rotation, world uView.scale) uView.translation gl Position uProjection vec4(view, 1.0)"} {"_id": 36, "text": "Increasing the rotation angle on a quaternion makes the rotation stop at a certain angle I'm using the following code to change the rotation of an object Quaternion rot getRotation() setRotation(make quaternion axis angle(rot.v,rotationSpeed dt) rot) This code works as expected until a certain angle where it suddenly stops. Why does it stop?"} {"_id": 36, "text": "Does gimbal lock occur only when a combination of local and world rotation axis are used? In all the explanations I've seen of gimbal lock, they always refer to the fact that when performing a series of rotations on all axes, it is possible that one rotation might end up aligning an axis with another which causes us to lose a degree of freedom. This never made sense to me since a rotation around e.g. the LOCAL RIGHT axis will rotation the whole LOCAL BASIS, no alignment happens. The only explanation I've seen that made sense was this one by DMGregory where it clearly explains that gimbal lock occurs when we e.g. change the yaw using the local basis and the pitch using a world basis. My question is Is that the only scenario where gimbal lock occurs or am I missing something? I also thought that quaternions help avoid gimbal lock but again, I'm missing something here because it seems to occur regardless of the rotation representation method (euler quaternion)."} {"_id": 36, "text": "Rotating the playing field. (MonoGame) My maths isn't as good as it should be, I need to pick up some reference books on Trig. Could someone give me an idea of the maths if I wanted to revolve many sprites around a central point? It's a 2D system in MonoGame. I'm going to try to describe the scenario, I can't think of anything quite like it to reference. Imagine a game screen, you are looking down on the world, with my character in the middle, my character sprite will never change, but if I turn left or right I want everything else to rotate around the central point. Of course every sprite will have to be moved, and also rotate to account for the spin. Can someone point me in the right direction? Thanks."} {"_id": 36, "text": "AABB of rotated sprite? Say I have a sprite. Its AABB is easy to find since I know the width and height. Say I rotate it 45 degrees, I don't think the AABB would be big enough to cover it, so I need a new AABB. How can I calculate the bounding rectangle of a rotated rectangle (given a center point, an angle, and its width and height)? Note that OpenGL does the rotation so I do not have access to the vertex information. What I'm trying to do is get AABBs so I can do 2D culling for rendering. Thanks"} {"_id": 36, "text": "How to eliminate roll rotation? Let's say I have Rotation(0, 0, 180) pitch, yaw, roll . How to do it that I would have Rotation(180, 180, 0) which is exactly the same?"} {"_id": 36, "text": "Rotate around an axis function for euler angles representation For a 3d game i need a function to rotate an euler representation around an arbitary axis by an angle. For example an object is rotated with euler angles (0,90,0). Now the object should be rotated by 100 degrees around the axis (0,1,0). The resulting angle will be (0,190,0) using rotation order YXZ. In this case I can add the angle to the euler value of the axis, however for an arbitary axis this will not work. Problem with Quaternions amp Rotation matrices With these representations the resulting rotations will always be smaller that 180 for each axis. I need the rotation to be lerped afterwards for example from (0,0,0) to (0,720,0). Basically I am searching for a way to display euler angles like most of the 3D editors. When you rotate an object around any arbitary axis rotation might be larger than 360 in the editor, like (420,720,15)."} {"_id": 36, "text": "How to find optimal perpendicular axis of rotation vector to draw arrows? I am drawing lines on the screen. Each line has a point (x,y,z) and a direction (u,v,w). I want to draw arrow heads on these lines, like two lines that start from (x,y,z) and leave at a 15 degree angle. I know how to draw these arrow head lines. I do this by rotating (u,v,w) by 15 degrees on some axis of rotation which is perpendicular to (u,v,w). The problem is the axis of rotation I am using is not making all my graphs look good. Basically I'm given a unit vector (u,v,w). If w 1, then u and v are 0 and I just use (1,0,0) which is a unit vector and perpendicular to (u,v,w). If that is not the case, then I use (v, u, 0) which is not a unit vector but is perpendicular. Then I normalize it. The norm won't be 0, since w lt 1 which means u 2 v 2 ! 0. This gives ok results. But some tests, the arrow head lines look a bit messed up, or not even looking like a 15 degree angle from the main line. Does anyone know a good way to find a good perpendicular unit vector to (u,v,w) so the results will always look good? Thanks"} {"_id": 36, "text": "Can I \"Pre rotate\" VBOs while loading them in LWJGL? It is possible to flip VBOs horizontally and vertically by swapping around destination coordinates. Is it possible to rotate an image by any angle, such as 45 degrees, using different destination coordinates when loading up a VBO? I realise that rotating present VBOs can easily be done using a matrix uniform in your vertex shader, but I'm asking about pre loaded (VBOs) rotations the VBO that you load being permanently rotated by X degrees. I am not looking for code but a conceptual method (or an explanation of why this isn't possible)."} {"_id": 36, "text": "How to expand the limit of screen mouse access for FPS side rotation I started coding in Godot and i have a working FPS controller but the problem is that when i move my mouse sideways , it cannot move my sight beyinid that side of my screen , in other words the movement of my charecter is limited by the size of my screen , how to prevent this Rotation code func input(event) if event is InputEventMouseMotion head.rotate y(deg2rad(event.relative.x mouseSensitivity)) camera.rotate x(deg2rad(event.relative.y mouseSensitivity))"} {"_id": 36, "text": "3D 3 axes rotation into 3D 2 axes rotation Hello everyone and thanks in advance to anyone who'll help me through this ! I am currently working on the Kinect V2 (for XBox One) to interact with an avatar. I'd like to use the rotation quaternion that the SDK 2.0 give for each joint of the Skeleton. My avatar (virtual avatar of NAO robot) communicates through nautical angles, yaw, ptich and roll. There's no problem to convert quaternions into nautical angles, but here's my problem Let's take the shoulder as an example of joint Where the Kinect express the rotation of my shoulder as a 3 axes rotation, I need to convert it into a 2 axes rotation. So for my shoulder I have a Yaw, Pitch, Roll from the Kinect, which I want to convert into a Pitch, Roll for NAO's avatar At the beginning, I didn't see the problem I just ignored the Yaw angle. But I rapidly noticed that the movement was not the same than in the Kinect (and it makes sense). Can someone help me ? How can I convert a 3D 3 axes rotation into a 3D 2 axes rotation ?"} {"_id": 36, "text": "from normal to rotation matrix (i'm on OPENGL) i have a mesh O (object) and a mesh T (terrain). i know a single triangle in T and i want to orient O to be aligned to that triangle (torate O to align to T in that point). i have only the normal in the triangle. how can i achive the roation matrix? i have thought this algorithm pseudocode float normal2rotation(Vector3D normal) angleX Vector3D.angleBetween(normal, Vecto3D.Axis3D.X) angleY Vector3D.angleBetween(normal, Vecto3D.Axis3D.Y) angleZ Vector3D.angleBetween(normal, Vecto3D.Axis3D.Z) float result angleX, angleY, angleZ return result but it does not give me the desired result."} {"_id": 36, "text": "Arcball Problems with UDK I'm trying to re create an arcball example from a Nehe, where an object can be rotated in a more realistic way while floating in the air (in my game the object is attached to the player at a distance like for example the Physics Gun) however I'm having trouble getting this to work with UDK. I have created an LGArcBall which follows the example from Nehe and I've compared outputs from this with the example code. I think where my problem lies is what I do to the Quaternion that is returned from the LGArcBall. Currently I am taking the returned Quaternion converting it to a rotation matrix. Getting the product of the last rotation (set when the object is first clicked) and then returning that into a Rotator and setting that to the objects rotation. If you could point me in the right direction that would be great, my code can be found below. class LGArcBall extends Object var Quat StartRotation var Vector StartVector var float AdjustWidth, AdjustHeight, Epsilon function SetBounds(float NewWidth, float NewHeight) AdjustWidth 1.0f ((NewWidth 1.0f) 0.5f) AdjustHeight 1.0f ((NewHeight 1.0f) 0.5f) function StartDrag(Vector2D startPoint, Quat rotation) StartVector MapToSphere(startPoint) function Quat Update(Vector2D currentPoint) local Vector currentVector, perp local Quat newRot Map the new point to the sphere currentVector MapToSphere(currentPoint) Compute the vector perpendicular to the start and current perp startVector cross currentVector Make sure our length is larger than Epsilon if (VSize(perp) gt Epsilon) Return the perpendicular vector as the transform newRot.X perp.X newRot.Y perp.Y newRot.Z perp.Z In the quaternion values, w is cosine (theta 2), where theta is the rotation angle newRot.W startVector dot currentVector else The two vectors coincide, so return an identity transform newRot.X 0.0f newRot.Y 0.0f newRot.Z 0.0f newRot.W 0.0f return newRot function Vector MapToSphere(Vector2D point) local float x, y, length, norm local Vector result Transform the mouse coords to 1..1 and inverse the Y coord x (point.X AdjustWidth) 1.0f y 1.0f (point.Y AdjustHeight) length (x x) (y y) If the point is mapped outside of the sphere ( length gt radius squared) if (length gt 1.0f) norm 1.0f Sqrt(length) Return the \"normalized\" vector, a point on the sphere result.X x norm result.Y y norm result.Z 0.0f else It's inside of the sphere Return a vector to the point mapped inside the sphere sqrt(radius squared length) result.X x result.Y y result.Z Sqrt(1.0f length) return result DefaultProperties Epsilon 0.000001f I'm then attempting to rotate that object when the mouse is dragged, with the following update code in my PlayerController. Get Mouse Position MousePosition.X LGMouseInterfacePlayerInput(PlayerInput).MousePosition.X MousePosition.Y LGMouseInterfacePlayerInput(PlayerInput).MousePosition.Y newQuat ArcBall.Update(MousePosition) rotMatrix MakeRotationMatrix(QuatToRotator(newQuat)) rotMatrix rotMatrix LastRot LGMoveableActor(movingPawn.CurrentUseableObject).SetPhysics(EPhysics.PHYS Rotating) LGMoveableActor(movingPawn.CurrentUseableObject).SetRotation(MatrixGetRotator(rotMatrix))"} {"_id": 36, "text": "3d rotation of a Gunner unit to shoot the target I'm developing a scenario to shoot incoming targets by a specific gunner unit, however I'm confused to actual logic of shooting an object with a gun. I'm working in 3D environment. I'v target's position vector i.e x,y,z and its rotation vector x,y,z,angle , and also Gun's position vector i.e x,y,z and its rotation vector x,y,z,angle . The gun has two components, i.e a TopDondur and a set of Barrels, both components have the rotation along y axis, i.e only angel of rotation vector 0 1 0 angle is required to move the Gunner Unit to the target. What rotataions shuould give the Gunner unit to rotate both TopDondur and Barrels, i.e TopDondur rotates to the target and Barrels are to move up down with respect to that target."} {"_id": 36, "text": "How to set object's node's absolute rotation correctly? Usually when I want to rotate an object node in my Ogre scene I call the node's rotate() method. That rotates the node locally relative to it's current rotation. So for example, when I start with 0 rotation, then rotate twice for 5 degrees about one axis, then after the second call the object is rotated by 10 degrees in total. Now I need to set the absolute rotation of the node object directly, regardless of its current rotation. Thus, say I don't know the objects current rotation, I need to set it say to 45 degrees on the X axis. Something like setRotation(). I know there is a setOrientation() method in the SceneNode class, which expects a quaternion object. I also know that I can get the current orientation quaternion. What I don't know how can I use change this current orientation quaternion to set the new absolute rotation of the node? PS Crosspost at http www.ogre3d.org forums viewtopic.php?f 2 amp t 77710"} {"_id": 36, "text": "Rotating hitboxes in PyGame? I'm using pygame.rect.colliderect() to check hitbox collision between sprites in my game, but now that I'm rotating the sprites, I'm realizing I can't do this because there's no way to rotate a PyGame rect, so the hitboxes are way off now. How should I handle collision in a game with rotating sprites if I don't want to use masks or pixel perfect collision? Is there a way to make a hitbox that rotates with the sprite?"} {"_id": 36, "text": "How to expand the limit of screen mouse access for FPS side rotation I started coding in Godot and i have a working FPS controller but the problem is that when i move my mouse sideways , it cannot move my sight beyinid that side of my screen , in other words the movement of my charecter is limited by the size of my screen , how to prevent this Rotation code func input(event) if event is InputEventMouseMotion head.rotate y(deg2rad(event.relative.x mouseSensitivity)) camera.rotate x(deg2rad(event.relative.y mouseSensitivity))"} {"_id": 36, "text": "Rotating and pitching a turret I am new to game development and I was trying to build a turret model, and control it through lua script in shiva3d. I can rotate it around the y axis which is no problem, but when it comes to pitching, I am not sure how to do that in a way which is independent of the Y rotation, for example, in the default position, rotating with a positive value around X aims upwards, which is what I expect. when I rotate it by 180 degrees around Y, the positive rotation around X aims downwards towards the ground instead of upwards. on the other hand, if I rotate by 90 degrees, the turret rotates around it self as if its rolling... I am not sure what to look for in order to understand how rotation in a 3d world should happen, so any pointers on that would be much appreciated"} {"_id": 36, "text": "Transform inertia tensor using quaternion I have inertia tensor T in body coordinates and quaternion q for the body. I know I can transform T to world coordinate by converting quaternion to rotation matrix R and then use the relation (R T R T). However this seems unnecessarily expensive and unwieldy (especially if you are doing this often). So my question is How do I transform inertia tensor from body to world coordinate directly using quaternion and without having to generate rotation matrix from quaternion?"} {"_id": 36, "text": "Godot 3.0 Constant 2D Angular Velocity I am making a Top Down shooter in Godot 3.0 on Linux. I would like to have my character rotate to face the mouse pointer at a constant speed, and have rotation speed power ups that allow the player turn faster. So far, this is done by having a Position2D object called \"Center\" share the same position (but not be a child of) the player (below just called \"Sprite\"). The center always looks to the mouse, and the Sprite rotates with linear interpolation to eventually reach the same rotation as the \"Center\". The weight of linear interpolation is calculated by dividing the difference in rotation (in radians) by an arbitrary constant speed. Problem The speed of rotation increases as rotation occurs, or more specifically, the time it takes to reach the same rotation (a rotational difference of zero) becomes shorter over time. I have the following code extends Sprite onready var center get parent().get node(\"Center\") var current time 0 var total time 0 var start rot 0 var end rot 0 func process(delta) center.look at(get global mouse position()) var amt 0 var theta abs(self.rotation center.rotation) var speed 0.05 total time theta speed start rot get rotation() end rot center.rotation if not total time 0 amt current time total time current time delta amt clamp(amt,0,1) var rot lerp(start rot,end rot,amt) center.rotation fmod(rot,(PI 2)) set rotation(fmod(rot,(PI 2))) get parent().get node(\"Control rotation\").text str(int(self.rotation degrees)) get parent().get node(\"Control theta\").text str(theta) get parent().get node(\"Control time\").text str(total time) What am I doing wrong?"} {"_id": 36, "text": "Rotate Translate a MatrixTRS Hello I have a question about translation amp rotation of a MatrixTRS... So basicly I have a given MatrixTRS A in space, define by a positionA, rotationA and scaleA. (DISCLAIMER I am using Unity, but I do not use Transform, therefore I have a Matrix4x4, created like that Matrix4x4 A Matrix4x4.TRS(position, rotation, scale) Ok, Now I have a Point in space, with a given rotation, named PositionB, and RotationB. I would like to translate amp Rotate my TRS matrix to that positionB, and rotationB. I know I have to do something like b.transform.TransformPoint() and Quaternion.Inverse(b.transform.rotation) a.transform.rotation, but i didn't manage to make it right yet. Thanks!"} {"_id": 36, "text": "Bounding Box in Monogame for mouse picking Hello guys so I'm implementing this mouse manager to be able to pick up objects. My application uses mainly textured quads in 3d space. I'm using bounding boxes in monogame to do so, however my solution lacks accuracy. Right now what I have is this http imgur.com oySTCay you can clearly see what the problem is, so this solution is probably not the best. this is my method to calculate the bounding box public BoundingBox GetBoundingBox() Matrix transform Node.GetTransformForBoundingBox() vertices 0 Vector3.Transform(new Vector3(0, 0, 0), transform) vertices 1 Vector3.Transform(new Vector3(Texture.Width m fTexturescale, 0, 0), transform) vertices 2 Vector3.Transform(new Vector3(0, (Texture.Height m fTexturescale) 1, 0), transform) vertices 3 Vector3.Transform(new Vector3(Texture.Width m fTexturescale, (Texture.Height m fTexturescale) 1, 0), transform) return BoundingBox.CreateFromPoints(vertices) And the mouse picking part is the standard ray tracing into near far clipping planes with unproject. So I was thinking, maybe if I do the other way around, and instead of un projecting the mouse, i could project all the vertices and do some kind of polygon math to check if the mouse position is inside the polygon formed from the projected vertices, (occluded vertices are worrying me though). Do you think is feasible, or is there any other option, should i just go for OBB? Thanks alot, Roger Martins EDIT So after searching a bit for OBB's i found that CartBlanche had one implementation on his samples repo this https github.com CartBlanche MonoGame Samples blob master CollisionSample BoundingOrientedBox.cs so I just used it and it works pretty well, now i just have one bug that i cant figure out, one transformation must be wrong. result http imgur.com QOsIbj7 what i'm doing so now I have a box parameter in this class, nullable one. how I build the bounding box public SOrientedBoundingBox GetBoundingBox() create the initial bounding box if (obb null) calculate the vertices for the textured quad in model space at the origin (inferior left corner is origin because we invert the y to conpensate for the perspective projection) vertices 0 new Vector3(0, 0, 0) vertices 1 new Vector3(Texture.Width m fTexturescale, 0, 0) vertices 2 new Vector3(0, (Texture.Height m fTexturescale) 1, 0) vertices 3 new Vector3(Texture.Width m fTexturescale, (Texture.Height m fTexturescale) 1, 0) get bounding box and trasnform it to orientedboundingbox TODO remove the middle step BoundingBox box BoundingBox.CreateFromPoints(vertices) obb SOrientedBoundingBox.CreateFromBoundingBox(box) return obb.Value else return obb.Value.Transform(Node.GetQuaternion(), new Vector3(Node.AbsolutePosition.X, Node.AbsolutePosition.Y 1, Node.AbsolutePosition.Z) Node.Scale) I'm going to fiddle a bit more with it, but the problem is something minor, i think. But maybe one of you can detect something silly i did. Thanks, Roger."} {"_id": 36, "text": "Rotate an object around a point in Ogre3D Possible Duplicate How can I rotate about an arbitrary point in 3D (instead of the origin)? I am new to 3D programming and I have been using Ogre3D lately to get a grasp of it. What I am trying to do is the following I want to make an entity rotate around a point (probably the parent SceneNode) in a circular way only in the X and Z axis. I have tried using yaw pitch roll and rotate but no luck, and I can't find any good tutorials how tos online."} {"_id": 36, "text": "Translate extrinsic rotations to intrinsic rotations ( Euler angles ) The problem I have is very frustrating I am using the Jitter Physics library which gives Quaternion rotations, you can extract the extrinsic rotations but I need intrinsic rotations to rotate in OpenTK (There are other reasons as well so I don't want to make OpenTK use a Matrix) GL.Rotate(xr, 1, 0, 0) GL.Rotate(yr, 0, 1, 0) GL.Rotate(zr, 0, 0, 1) EDIT Response to the first answer Like This? GL.Rotate(zr, 0, 0, 1) GL.Rotate(yr, 0, 1, 0) GL.Rotate(xr, 1, 0, 0) Or This? GL.Rotate(xr, 1, 0, 0) GL.Rotate(yr, 0, 1, 0) GL.Rotate(zr, 0, 0, 1) GL.Rotate(zr, 0, 0, 1) GL.Rotate(yr, 0, 1, 0) GL.Rotate(xr, 1, 0, 0) GL.Rotate(xr, 1, 0, 0) GL.Rotate(yr, 0, 1, 0) GL.Rotate(zr, 0, 0, 1) I'm confused, please give an example"} {"_id": 36, "text": "AABB of rotated sprite? Say I have a sprite. Its AABB is easy to find since I know the width and height. Say I rotate it 45 degrees, I don't think the AABB would be big enough to cover it, so I need a new AABB. How can I calculate the bounding rectangle of a rotated rectangle (given a center point, an angle, and its width and height)? Note that OpenGL does the rotation so I do not have access to the vertex information. What I'm trying to do is get AABBs so I can do 2D culling for rendering. Thanks"} {"_id": 36, "text": "Rotate can I rotate an object to a target angle using Euler Angles? How do I rotate an object from its current angle to the desired angle in increments on 1 axis? The problem is the wraparound at 360 degrees What I have so far (Note pseudocode) double MaxSpeed 5 double CurrentAngle 170 double DesiredAngle 40 double Distance DesiredAngle CurrentAngle How do I calculate this value considering angle wraparound? CurrentAngle Mathd.clamp(Distance, MaxSpeed, MaxSpeed) Caps the rotation speed"} {"_id": 36, "text": "I'm rotating an object on two axes, so why does it keep twisting around the third axis? I see questions come up quite often that have this underlying issue, but they're all caught up in the particulars of a given feature or tool. Here's an attempt to create a canonical answer we can refer users to when this comes up with lots of animated examples! ) Let's say we're making a first person camera. The basic idea is it should yaw to look left amp right, and pitch to look up amp down. So we write a bit of code like this (using Unity as an example) void Update() float speed lookSpeed Time.deltaTime Yaw around the y axis using the player's horizontal input. transform.Rotate(0f, Input.GetAxis(\"Horizontal\") speed, 0f) Pitch around the x axis using the player's vertical input. transform.Rotate( Input.GetAxis(\"Vertical\") speed, 0f, 0f) or maybe Construct a quaternion or a matrix representing incremental camera rotation. Quaternion rotation Quaternion.Euler( Input.GetAxis(\"Vertical\") speed, Input.GetAxis(\"Horizontal\") speed, 0) Fold this change into the camera's current rotation. transform.rotation rotation And it mostly works, but over time the view starts to get crooked. The camera seems to be turning on its roll axis (z) even though we only told it to rotate on the x and y! This can also happen if we're trying to manipulate an object in front of the camera say it's a globe we want to turn to look around The same problem after a while the North pole starts to wander away to the left or right. We're giving input on two axes but we're getting this confusing rotation on a third. And it happens whether we apply all our rotations around the object's local axes or the world's global axes. In many engines you'll also see this in the inspector rotate the object in the world, and suddenly numbers change on an axis we didn't even touch! So, is this an engine bug? How do we tell the program we don't want it adding extra rotation? Does it have something to do with Euler angles? Should I use Quaternions or Rotation Matrices or Basis Vectors instead?"} {"_id": 36, "text": "Programmatically determine UVs by rotating a plane along X axis I'm having a math brainfart while trying to solve what might be a simple problem. I've got a plane in 3d space (it's actually the face of a 10 sided die) Coordinates x,y,z Point top 0,0,1 Point left Sin (2pie9 10), Cos(2pie9 10), 0.1 .5878,.809,.1 Point right Sin (2pie 10) , Cos(2pie 10), 0.1 .5878,.809,.1 Point bot 1,0, 0.1 If you project that out, it's a plane with the top leaning back away from you, and the bottom closer to you. I'm trying to automatically build a UV map of that face to put a texture on, so think I should rotate it around the x asix so that it's only in 2D, then scale that to best fill up a 256x256 texture. I'm doing this in Three.JS for a canvas app. Is this the right approach? In this example http wecreategames.com games DiceBoard ( die creation code is in http wecreategames.com games DiceBoard die10.js ), I'm estimating the UVs by Build UVs scope.faceUvs scope.faceVertexUvs for (var f 0 f lt numHalfFaces f ) var faceuv new THREE.UV(.2, .6), new THREE.UV(.5, .75), new THREE.UV(.8, .6), new THREE.UV(.5, .2) scope.faceUvs 0 .push(new THREE.UV(0, 1)) scope.faceVertexUvs 0 .push(faceuv) But when I view on an iPhone or Android, it shows weird screen artifacts... I'm thinking because the UVs aren't exact. I think I'd apply some function like this (where andDist is an angle) rx x ry (y Math.cos(angDist)) (z Math.sin(angDist)) rz (y Math.sin(angDist)) (z Math.cos(angDist)) But, I'm not sure how to get the angle that the face is inclined at. Any suggestions? Or, are those white screen artifacts due to something else I've overlooked?"} {"_id": 36, "text": "Align Players Rotation I'm currently working on rope Swinging. The Rope consists of Physics Constraints Joints and between them the rope is rendered. I would like align my Character's Pitch to the Rope. I'm horribly bad at vector Math, and I have trouble finding the solution. Here's a picture that shows what I want to achieve I tried using the Difference between two joints but somehow it doesn't work. I'm using Unreal Engine if that helps."} {"_id": 36, "text": "Translate extrinsic rotations to intrinsic rotations ( Euler angles ) The problem I have is very frustrating I am using the Jitter Physics library which gives Quaternion rotations, you can extract the extrinsic rotations but I need intrinsic rotations to rotate in OpenTK (There are other reasons as well so I don't want to make OpenTK use a Matrix) GL.Rotate(xr, 1, 0, 0) GL.Rotate(yr, 0, 1, 0) GL.Rotate(zr, 0, 0, 1) EDIT Response to the first answer Like This? GL.Rotate(zr, 0, 0, 1) GL.Rotate(yr, 0, 1, 0) GL.Rotate(xr, 1, 0, 0) Or This? GL.Rotate(xr, 1, 0, 0) GL.Rotate(yr, 0, 1, 0) GL.Rotate(zr, 0, 0, 1) GL.Rotate(zr, 0, 0, 1) GL.Rotate(yr, 0, 1, 0) GL.Rotate(xr, 1, 0, 0) GL.Rotate(xr, 1, 0, 0) GL.Rotate(yr, 0, 1, 0) GL.Rotate(zr, 0, 0, 1) I'm confused, please give an example"} {"_id": 36, "text": "Rotate around an axis function for euler angles representation For a 3d game i need a function to rotate an euler representation around an arbitary axis by an angle. For example an object is rotated with euler angles (0,90,0). Now the object should be rotated by 100 degrees around the axis (0,1,0). The resulting angle will be (0,190,0) using rotation order YXZ. In this case I can add the angle to the euler value of the axis, however for an arbitary axis this will not work. Problem with Quaternions amp Rotation matrices With these representations the resulting rotations will always be smaller that 180 for each axis. I need the rotation to be lerped afterwards for example from (0,0,0) to (0,720,0). Basically I am searching for a way to display euler angles like most of the 3D editors. When you rotate an object around any arbitary axis rotation might be larger than 360 in the editor, like (420,720,15)."} {"_id": 36, "text": "AABB of rotated sprite? Say I have a sprite. Its AABB is easy to find since I know the width and height. Say I rotate it 45 degrees, I don't think the AABB would be big enough to cover it, so I need a new AABB. How can I calculate the bounding rectangle of a rotated rectangle (given a center point, an angle, and its width and height)? Note that OpenGL does the rotation so I do not have access to the vertex information. What I'm trying to do is get AABBs so I can do 2D culling for rendering. Thanks"} {"_id": 36, "text": "How to eliminate roll rotation? Let's say I have Rotation(0, 0, 180) pitch, yaw, roll . How to do it that I would have Rotation(180, 180, 0) which is exactly the same?"} {"_id": 36, "text": "THREE.JS why is the rotation only applied on the last axis used? my function function rotateAroundWorldAxis2(object, radians1, radians2) object.rotWorldMatrix.makeRotationX(radians1).makeRotationZ(radians2) object.rotWorldMatrix old code for Three.JS pre r54 rotWorldMatrix.multiply(object.matrix) new code for Three.JS r55 object.rotWorldMatrix.multiply(object.matrix) pre multiply object.matrix.copy( object.rotWorldMatrix ) old code for Three.js pre r49 object.rotation.getRotationFromMatrix(object.matrix, object.scale) old code for Three.js pre r59 object.rotation.setEulerFromRotationMatrix(object.matrix) code for r59 object.rotation.setFromRotationMatrix(object.matrix) my object was initialized like this object.rotWorldMatrix new THREE.Matrix4()"} {"_id": 36, "text": "How can I modify the UV co ordinates on a texture so they converge to a point? I'm building a roof visualiser app, where someone can take a picture of their roof, define its outline, then visualise a new roof texture on it. I'm generating a 3D plane that matches the roof outline points, but I'd like the 3D planes material's UV's to match the perspective of the existing roof (i.e the lines converge into the distance as they move away from the user. Is this possible? The alternative solution is to figure out how to rotate the generated 3D plane to match the roof outline points, while matching the perspective too, but I'm thinking this may be more complicated. Step 1 Define roof oultine with points Step 2 Texture 3D plane with UV's mapped to maintain roof perspective based on slant defined in the 4 points Any tips on how to solve this?"} {"_id": 37, "text": "TiledMaps and real objects I'm creating a simple game for the iPhone using Cocos2d. I'm having a hard time understanding how add real objects to a tiled map. I know that you can add an object layer to the tiled map and set the position of it, but I'm not sure how to define WHAT object it should be. For example, if I'm creating a simple Super Mario Bros. I want to add different blocks to the map, one should hold a star, one should hold a coin, and so on. How should I define what object it is? So my question, how do I correctly create class objects in a tiled map?"} {"_id": 37, "text": "create a simple tilemap programatically i am working on a tile roguelike i got some of the basics working using this tutorial http www.raywenderlich.com 1163 how to make a tile based game with cocos2d but i want to be able to create a map programatically instead of using the tiled editor just add a NSArray of sprites tiles to my CCLayer derived class or something, or should i make use of the CCTMXTiledMap class? can anyone gimme some hints about how to do this? or know of a tutorial or sample code somewhere? thanks a lot"} {"_id": 37, "text": "How to get a large quantity of photographs in an app while being memory efficient?? There have been a lot of word games (apps) lately and some use graphics but others use photographs and I was hoping that someone could explain how these games manage to get so many photos in an app without taking up huge amounts of memory? The easiest example I can give is an app called '4 pics 1 word' it has over 350 levels and obviously 4 pics on each level and the photos are good quality on retina screens but the memory of the app is less than 40mb, if I have remembered correctly. I was curious as to how this works, is it each photo being optimized in photoshop (save for web and devices) (png or jpeg) or is it something to do with the code or something else? I know this question is quite broad but any answers, help, links to anything would be greatly appreciated."} {"_id": 37, "text": "iPhone, iPad Rendering Ahead of Input (4 5 seconds) UPDATE I think I solved this one, though any thoughts or suggestions are always welcome! This one is truly bizarre... I'm developing using both an iPhone 3GS and an iPad 2. This symptom is repeatable on the older iPhone hardware much more readily than on the iPad 2. Here's what happens I start the game and the FPS is ticking at about 47 on the 3GS in OpenGLES2.0. I have quite a lot on screen right now, so that is reasonable at this stage (I still have a few optimizations I can make too). If you put a break in touchesBegan, it takes roughly 4 5 seconds before the break occurs and the game halts. This doesn't happen all of the time, and in fact, if you restart the app several times, it usually goes away. Moreover, if I let the game sit for a bit, it will eventually \"sync.\" Like I said, the iPad 2 rarely exhibits the problem (one out of every 15 20 test runs), but it is definitely still present. If you perform a series of touches and accelerometer events in sequence, they are queued up and rendered just like you did them 4 5 seconds later. Very reminiscent of 4 5s lag delays back in the day online ) I've tried a couple things like glFlush, or glFinish at the end of each render loop (doesn't seem to have any effect). Here's the top game loop (void) drawView (CADisplayLink ) displayLink double dt 0.0f Time in seconds since last loop if (displayLink ! nil) dt displayLink.timestamp m timestamp m timestamp displayLink.timestamp Update the game m gameEngine gt Update(dt) Render the game m gameEngine gt Render() m context presentRenderbuffer GL RENDERBUFFER UPDATE The more I think about it... this could be a loading issue. Right now, I instantiate my main controller class for the game loop in the (id) initWithFrame (CGRect) frame call, which is also where I initialize OpenGL and (finally) call displayLink addToRunLoop NSRunLoop currentRunLoop forMode NSDefaultRunLoopMode . It's almost as if the renderer gets behind or ahead of the game logic and it takes it awhile to get caught back up. From research, I could also just be throttling the CPU too hard. But if that were the case, I would imagine it wouldn't catch up... the FPS stays at a solid 44 46, and the input lag does go away if you let it sit for 10 15 seconds (with or without doing anything, it eventually catches up). I'm stumped, but I'll keep digging... UPDATE 2 Doing some profiling... figured out that the accelerometer being polled 1 60 was a bit taxing. If I moved it to 1 30, this problem went away. This is concerning to me, as it likely suggests I do have a CPU overloading issue that will only be solved through some serious optimizations across the board (which is okay, I knew I had to do it anyway). For anyone with a similar issue, especially if you are using the accelerometer, make sure you disable it if when you aren't using it. I only use the accelerometer to allow the player to rotate move the camera so when the player has the camera locked, I am now toggling it off. This has solved my problem for now, but like I said, I probably only solved it temporarily. A real solution is going to take more work! Hope this helps."} {"_id": 37, "text": "Saving data in games? I'm soon going to make a game for the iPhone as a school project. My idea was to make a TLOZ remake, with Tiled Maps. However, I'm not quite sure how save the data. In TLOZ you have a lot of sub quests, treasures, items, and much more. I want the user to only be able to open a treasure once. Therefore I have to save this information somehow. However, I'm not sure how to assign the data to that certain object, for example that treasure that Link has opened. I thought about making id's for every object, but I'll have multiple maps, and it doesn't seem like the right solution. Are there any standards for this? Or does anyone have another idea?"} {"_id": 37, "text": "Creating Level iPhone I am thinking about a new game idea for the iPhone and presumably all the levels would have to be made programatically. So Im wondering what the best method to approach it? Say I have a game with a standard typical 2d, top down maze. Thise maze is simply made up of walls, multiple rectangles on screen, making paths. Do I have to manually work out the position of every rectangle and put it in with an x and y position or is there a better way? I see this taking, forever, there must be certain ways developers approach these situations to get by them efficiently and quickly surely? Thanks."} {"_id": 37, "text": "How can I make a rectangle to an irregular shape? I used masking for breaking an image into the below pattern. Now that it's broken into different pieces I need to make a rectangle of each piece. I need to drag the broken pieces and adjust to the correct position so I can reconstruct the image. To drag and put at the right position I need to make the pieces rectangles but I am not getting the idea of how to make rectangles out of these irregular shapes. How can I make rectangles for manipulating these pieces? This is a follow up to my previous question."} {"_id": 37, "text": "Game server for an android iOS turn based board game I am currently programming an iPhone game and I would like to create an online multiplayer mode. In the future, this app will be port to Android devices, so I was wondering how to create the game server? First at all, which language should I choose? How to make a server able to communicate both with programs written in objective c and Java? Then, how to effectively do it? Is it good if I open a socket by client (there'll be 2)? What kind of information should I send to the server? to the clients?"} {"_id": 37, "text": "Efficient Bullet Firing Class I've been struggling with this for a while. I have been trying to create a bullet pool class for a game I have made that doesn't cause a significant fps drop. I have tried creating a bullet pool and have also tried dynamically creating and deleting bullets, both of which drop the fps of the game around 10 15. I ran a test a few days ago and just put a return statement in the bullet pool's firebullet function, which represented the logic leading up to this, function calling, etc. This only dropped the fps 2 4. If I can fire bullets without dropping the fps more than another 2 3, I would be satisfied. My bullets are autorelease objects that are a subclass of a ccnode. I create a ccsprite and a box2d b2body for each one. I am working on the ios platform. Any thoughts on how to make this more efficient? Has anyone managed to do something similar to this?"} {"_id": 37, "text": "How do I repeatedly move an image by 1 pixel? I have a method that is moving a UIImageView called shootImg across the screen (IBAction)shoot if (appDelegate.shootInt gt 0) if (direction 1) shootImg.center CGPointMake(shootImg.center.x 1, shootImg.center.y) appDelegate.shootInt appDelegate.shootInt 1 shootLabel.text NSString stringWithFormat \" d\", appDelegate.shootInt This does seem to work. But it only moves shootImage 1 pixel. What I want to do is make it repeatedly move 1 pixel. I tried a while loop but that didn't seem to work. I'm not using cocos2d or anything like that and if you need to see more code just ask. Thanks )"} {"_id": 37, "text": "Best way to learn iphone game development? I know php and some python, but not much c. Where should I start to learn iphone game development? Is there some recommended books tutorials for beginners? I'm looking at using cocos2d but I'm open to anything that isn't too limited."} {"_id": 37, "text": "Set texture of a LHSprite that is loaded from LevelHelper How do i set the image texture of an LHSprite that is loaded into xCode using levelHelper amp spriteHelper? I am using sprite sheets. So i tried to load the image the old fashioned way using CCSpriteFrameCache, but unfortunately it isnt recognizing the .pshs file ( Any Help would be great!"} {"_id": 37, "text": "Getting started with Box2D for iOS I just want to run any Box2D \"Hello World\" or test apps. I've downloaded the source twice (zip file the first time and via svn the second time), followed the build instructions (do stuff w cmake, \"make\", \"make install\" etc) and don't know where to go from there. How do I run the test apps or Hello World apps that come w Box2D on my iPhone (or simulator)?"} {"_id": 37, "text": "How can I make iPhone apps (games) on Windows? I want to start making iPhone games, but sadly I'm a Windows geek.. Is there a way to make good profesional iPhone games without Xcode owning a Mac computer? If not, what do you recommend, a Mac Mini? Thanks in advance!"} {"_id": 37, "text": ".NET WCF as backend server for iPhone games I'm planning to develop an iPhone game. Is it possible to use .NET WCF as a backend? The server would be windows 2008 and MS SQL database."} {"_id": 37, "text": "Looking for the reference tutorials for the joints in the Box2D for iphone I can't find the tutorials of joints class in the Box2D for iPhone. I am unable to run a Testbed for iPhone Box2D. (void)ccTouchesBegan (NSSet )touches withEvent (UIEvent )event if ( mouseJoint! NULL)return UITouch mytouch touches anyObject CGPoint location mytouch locationInView mytouch view location CCDirector sharedDirector convertToGL location b2Vec2 locationWorld b2Vec2(location.x PTM RATIO,location.y PTM RATIO) ristrict the player within the ground limit keep stucking the player with grounditself..... if ( playerFixture gt TestPoint(locationWorld)) b2MouseJointDef md md.bodyA groundBody md.bodyB playerBody md.target locationWorld md.collideConnected true md.maxForce 100.0f playerBody gt GetMass() mouseJoint (b2MouseJoint ) world gt CreateJoint( amp md) playerBody gt SetAwake(true) (void)ccTouchesMoved (NSSet )touches withEvent (UIEvent )event if ( mouseJoint NULL) return UITouch myTouch touches anyObject CGPoint location myTouch locationInView myTouch view location CCDirector sharedDirector convertToGL location if (location.y lt 240.00 amp amp location.y gt 20.0f) b2Vec2 locationWorld b2Vec2(location.x PTM RATIO, location.y PTM RATIO) mouseJoint gt SetTarget(locationWorld) (void)ccTouchesEnded (NSSet )touches withEvent (UIEvent )event if ( mouseJoint) world gt DestroyJoint( mouseJoint) mouseJoint NULL"} {"_id": 37, "text": "iPhone 3GS can't ever seem to hold 60fps with CADisplayLink So I've switched from NSTimer to CADisplayLink and I'm still seeing unexpected variation in my frame counter it fluctuates between 59 60fps, even when I'm not rendering much. Has anyone else seen this? Is this an expected variation in iOS? Or should I look more closely at my game loop?"} {"_id": 37, "text": "Creating 2D waveform for Cocos2d game I'd like to have a Waveform in my iPhone game that I am developing using Cocos2d v2.0. That's the ideal wave I'd like to achieve. A simpler wave which I would still be happy with is this one. Some people suggested me to use ParticleEffects ands ParticleDesigners like 71squared but I am not sure that this is the right approach. Brainstorming, I think that at the end a wave is a plot of some function, and at each frame translate the wave points that where from the origin apart ( x and x) and computes new wave points for the origin. Something like this for (duration of effect) compute wave point intensity at origin and display it and for each wave point before the center translate to x and display it and after the center translate to x and display it Let me know what you think and if you have any better solution. I was thinking to achieve the display point by colouring a particular pixel but I need to figure out how ).."} {"_id": 37, "text": "UDK iOS System Requirements confusion Unreal Development Kit for iOS was recently released. The system requirements note that Windows is needed. Does this mean that iOS game development is possible on a PC now? I am confused since I thought iOS development required an OSX machine. Thanks in advance."} {"_id": 37, "text": "shake Vibrate a body in box2d? How do you vibrate or cause a shake effect to a body of type static or dynamic or kinematic. I tried applying forces to a dynamic body in the timeStep, which did not work, as well I tried ApplyLinearImpulse many times a sec within the timeStep, which again did not give me the result. So right now Iam experimenting with adding a static circle body as a hinge point to my rectangular body and create a revolute joint between them. May be then applying a force could result in Tension between the 2 bodies? Does anybody know about this? have any ideas please let me know?"} {"_id": 37, "text": "How to support all iOS device screen sizes resolutions in my game I made this game. Right now the game supports all iOS devices except iPhone 5. The definition of each level of the game is kept in a plist. The creation of each level is done through a graphical level editor. Each device family has its own plists. So, right now the game has 100 levels and 200 plists 100 plists for the iPhone family and 100 plists for the iPad family. In order to support the iPhone 5 I need to create 100 new plists and adjust the plists accordingly, which is time consuming, not to mention the creation of new levels... The editor for creating and editing the levels is solely based on the manipulation of UIViews that describe the game elements. So, this is the code that I wrote to save and restore the state of each UIView in one level of the game. (void)encodeWithCoder (NSCoder )aCoder Save the screen size of the device that the view was saved on aCoder encodeCGSize self.gameView.bounds.size forKey \"saveDeviceGameViewSize\" ALL properties are saved in normalized coords Save the center of the view CGPoint normCenter CGPointMake(self.center.x self.gameView.bounds.size.width, self.center.y self.gameView.bounds.size.height) aCoder encodeCGPoint normCenter forKey \"center\" I rely on view bounds NOT frame CGRect normBounds CGRectMake(0, 0, self.bounds.size.width self.gameView.bounds.size.width, self.bounds.size.height self.gameView.bounds.size.height) aCoder encodeCGRect normBounds forKey \"bounds\" Here I save the transformation of the view, it has ONLY rotation info, not translation or scalings aCoder encodeCGAffineTransform self.transform forKey \"transform\" (id)initWithCoder (NSCoder )aDecoder self super initWithCoder aDecoder if (self) Restore the screen size of the device that the view was saved on saveDeviceGameViewSize aDecoder decodeCGSizeForKey \"saveDeviceGameViewSize\" Adjust the view center CGPoint tmpCenter aDecoder decodeCGPointForKey \"center\" tmpCenter.x self.gameView.bounds.size.width tmpCenter.y self.gameView.bounds.size.height self.center tmpCenter Restore the transform self.transform aDecoder decodeCGAffineTransformForKey \"transform\" Restore the bounds CGRect tmpBounds aDecoder decodeCGRectForKey \"bounds\" CGFloat ratio self.gameView.bounds.size.height saveDeviceGameViewSize.height tmpBounds.size.width (saveDeviceGameViewSize.width ratio) tmpBounds.size.height self.gameView.bounds.size.height self.bounds tmpBounds return self I am really stuck here. I cannot explain what is wrong with this code. The UIViews are correctly positioned when restored on the same device. This is not true when the level is opened on another device. There are slightly misplaced elements and distortions. Here are two pairs of screenshots demostrating the issues What is the correct approach to handle the scaling of the levels on different screens? Should I rely on AutoResizingMasks (I need to support iOS 4 and later)? In any case I would like to give a solid paradigm on how to achieve this."} {"_id": 37, "text": "How do I randomly create and store enemy data for my iPhone game? In my game you need to protect something from enemies. There can be many on the screen at once. But I don't know how to create the enemies randomly, and how I can save the data to each enemy? Can give good tips or good links to tutorials?"} {"_id": 37, "text": "i want to move arrow by dragging and than want to toss throw when i give swipe event In My Application I Have One Arrow Image With Fix Center and i Can rotate it by touch move method on same center but i also need to Toss trow the arrow after doing some rotation with dragging or without doing that How Can I Put The Toss Throw Action in MyApplication Thank You Very Much In advance"} {"_id": 37, "text": "Updating games for iOS 6 and new iPhone iPod Touch Say I have a game that runs full screen on iPhone 4S and older devices. The balance of the game is just right for the 480 x 320 screen and associated aspect ratio. Now I want to update my game to run full screen on the new iPhone iPod Touch where the aspect ratio of the screen is different. It seems like this can be challenging for some games in terms of maintaining the \"balance\". For example if the extra screen space was just tacked onto the right side of Jet Pack Joyride the balance would be thrown off since the user now has more time to see and react to obstacles. Also it could be challenging in terms of code maintenance. Perhaps Jet Pack Joyride would slightly increase the speed of approaching obstacles when the game is played on newer devices. However this quickly becomes messy when extra conditional statements are added all over the code. One solution is to have some parameters that are set in once place at start up depending on the device type. What are some strategies for updating iOS games to run on the new iPhone and iPod Touch? Edit more info I wonder what happens with a game like Plants vs Zombies? There's quite a bit of artwork that's probably sized to the 320x480 screen. Perhaps the lawn background's width can be increased while the size of the zombies and the row heights stay the same."} {"_id": 37, "text": "Which iPhone iPod Hardware to Support for iPhone Game I'm coming from a background of Android. I would like to figure out what kind of iBlah device hardware I need to support for iPhone game development something like Android's OS distribution stats, but for iBlah hardware. From my research, it seems that I need to support both iPod and iPhone. But which versions of hardware? is 3G still used? What about 3GS? For example, the S phones seem to have dual core instead of single core CPUs. I also worry about performance. In Android, I had a severely low end phone, which meant pretty much anything that ran okay there ran okay on other phones. For iPhone, how do I figure out what to support in terms of performance?"} {"_id": 37, "text": "Has anyone used PhoneGap to make 2D games for the iPhone? I love simple casual games. I've been riding the bus a lot recently and so simple, no brainer games are great fun and well worth the small price I pay on the App Store. It got me thinking... I know HTML5, CSS3 and JS very well. I looked into PhoneGap and it looks like it's something I could use for making apps for the iPhone. The games I've been fleshing out myself are very simple 2D affairs. Fun, simple and high quality. That's what I'm after with my games... I also make music and my friend is an digital illustrator so together we have all the media covered. Does any one make 2D games for the iPhone using PhoneGap? I'm presuming that because I want to code in JS and use the HTML5 Canvas tag, that PhoneGap does nothing more than provide me a wrapper with a WebKit view? I know it won't be as fast as using native... But is using PhoneGap a viable option?"} {"_id": 37, "text": "Best way to learn iphone game development? I know php and some python, but not much c. Where should I start to learn iphone game development? Is there some recommended books tutorials for beginners? I'm looking at using cocos2d but I'm open to anything that isn't too limited."} {"_id": 37, "text": "Cocos2d Using single timer scheduler for multiple sprites want to know if is it possible to use single timer or scheduler method for multiple sprites ? Like I am now working on a game and there could be any number of sprites and i want to perform some actions on all of that sprites, So do I have to use as many timers or schedulers as sprites ? Or How can the job be done using only a single timer or scheduler ? What is I schedule a method and use it for, Say 10 sprites ? Will it affect the performance..?"} {"_id": 37, "text": "How do I randomly create and store enemy data for my iPhone game? In my game you need to protect something from enemies. There can be many on the screen at once. But I don't know how to create the enemies randomly, and how I can save the data to each enemy? Can give good tips or good links to tutorials?"} {"_id": 37, "text": "How do you get textures out of a png file I have 1 png of many different textures. I want to use these textures in my iphone game using cocos2d. I found the program \"Zwoptex\" where you can combine many textures to one png and create a plist file that you can use in your program. But if you have already a png file how do you get all these textures out of this file automatically OR how do I create a plist file from this png file?"} {"_id": 37, "text": "Saving data in games? I'm soon going to make a game for the iPhone as a school project. My idea was to make a TLOZ remake, with Tiled Maps. However, I'm not quite sure how save the data. In TLOZ you have a lot of sub quests, treasures, items, and much more. I want the user to only be able to open a treasure once. Therefore I have to save this information somehow. However, I'm not sure how to assign the data to that certain object, for example that treasure that Link has opened. I thought about making id's for every object, but I'll have multiple maps, and it doesn't seem like the right solution. Are there any standards for this? Or does anyone have another idea?"} {"_id": 37, "text": "What to think about when designing a simple GUI for a quiz game I am coming close to finish my first iPhone game ever, as a matter of fact also my first programming experience ever, which is a quiz game. I have all the functionality i want and is currently polishing it both from a code point of view as well as looking at the GUI. My initial idea was not to use any specific graphics but rather focus on the game experience and simplicity and by that only using background color, orange, and white text as well as buttons. The design is based on that all ages, from learning to read, should be able to host and play this game. However, as i am now getting close to the finish line i am starting to think what is needed from a GUI point of view. I would like to ask for some advice what to think about when designing a GUI. Is it considered OK without any 'fancy' graphics, what is the risk without it etc.? Also, what colors goes well together if i choose to use a simple GUI. I am thinking about color blindness etc. In other words how do i design a good and effective GUI for a simple game as mine? Thanks"} {"_id": 37, "text": "Updating games for iOS 6 and new iPhone iPod Touch Say I have a game that runs full screen on iPhone 4S and older devices. The balance of the game is just right for the 480 x 320 screen and associated aspect ratio. Now I want to update my game to run full screen on the new iPhone iPod Touch where the aspect ratio of the screen is different. It seems like this can be challenging for some games in terms of maintaining the \"balance\". For example if the extra screen space was just tacked onto the right side of Jet Pack Joyride the balance would be thrown off since the user now has more time to see and react to obstacles. Also it could be challenging in terms of code maintenance. Perhaps Jet Pack Joyride would slightly increase the speed of approaching obstacles when the game is played on newer devices. However this quickly becomes messy when extra conditional statements are added all over the code. One solution is to have some parameters that are set in once place at start up depending on the device type. What are some strategies for updating iOS games to run on the new iPhone and iPod Touch? Edit more info I wonder what happens with a game like Plants vs Zombies? There's quite a bit of artwork that's probably sized to the 320x480 screen. Perhaps the lawn background's width can be increased while the size of the zombies and the row heights stay the same."} {"_id": 37, "text": "Looking for the reference tutorials for the joints in the Box2D for iphone I can't find the tutorials of joints class in the Box2D for iPhone. I am unable to run a Testbed for iPhone Box2D. (void)ccTouchesBegan (NSSet )touches withEvent (UIEvent )event if ( mouseJoint! NULL)return UITouch mytouch touches anyObject CGPoint location mytouch locationInView mytouch view location CCDirector sharedDirector convertToGL location b2Vec2 locationWorld b2Vec2(location.x PTM RATIO,location.y PTM RATIO) ristrict the player within the ground limit keep stucking the player with grounditself..... if ( playerFixture gt TestPoint(locationWorld)) b2MouseJointDef md md.bodyA groundBody md.bodyB playerBody md.target locationWorld md.collideConnected true md.maxForce 100.0f playerBody gt GetMass() mouseJoint (b2MouseJoint ) world gt CreateJoint( amp md) playerBody gt SetAwake(true) (void)ccTouchesMoved (NSSet )touches withEvent (UIEvent )event if ( mouseJoint NULL) return UITouch myTouch touches anyObject CGPoint location myTouch locationInView myTouch view location CCDirector sharedDirector convertToGL location if (location.y lt 240.00 amp amp location.y gt 20.0f) b2Vec2 locationWorld b2Vec2(location.x PTM RATIO, location.y PTM RATIO) mouseJoint gt SetTarget(locationWorld) (void)ccTouchesEnded (NSSet )touches withEvent (UIEvent )event if ( mouseJoint) world gt DestroyJoint( mouseJoint) mouseJoint NULL"} {"_id": 37, "text": "As an Android dev, what should I keep in mind for porting to iPhone? As an Android game developer, what should I keep in mind while developing my game if I ever wanted to cross platform the game to the iPhone? Any strategies, tips, etc. on porting to both of these mobile platforms?"} {"_id": 37, "text": "How can I create a smooth simulation for a fast paced, multiplayer table hockey game? I'm adding multiplayer to an iPhone game that we have in our company. It's a sort of 'table hockey' game, with a puck and two mallets. It's a pretty fast game, so I need a smooth experience at both ends. What I'm doing right now is using Game Center, and setting up the iPhone that starts the game as the \"server.\" So, the client runs its physics the same as the server, but the server adjusts the speed of the puck on the client and adjust its position when they are going on the same direction. The problem that it has some glitches, when the physics simulations differs a bit between then and the server sends the command to correct and the client kind of jumps around. Does anyone has a suggestion how should I can handle this? Or should I try a different way?"} {"_id": 37, "text": "What does everyone like to use for UI elements for their games on the iPhone? I'm asking this to get everyone's opinion I realize there isn't one \"right way\" to do this. I've tried a few ways myself, including using Cocoa for everything including the game itself (good for simpler games, like card games for example), using Cocoa for the screens outside of the game and using my game engine to present game objects on the screen as UI. What do people prefer to use for game UI? I'm particularly interested in hearing about why you chose to go that way and if you found that your choice was a good one after implementing it."} {"_id": 37, "text": "Make a layer over an image and adjust its co ordinates by touch I need to make a layer over an image and adjust the layer to fit to image and get its co ordinates of the layer. I need to adjust the layer by touch and pinch. The sample image is as below. I need to do this in ios, and can I get any ideas to do this?"} {"_id": 37, "text": "What should I use for the event name when logging metrics with Flurry? I'm working on a multiplayer game and I want to use Flurry to record game events. In the game you can build, grow and train troops. In Flurry you can log an event (optionally with parameters). It would be great to be able to track the progress of a player depending upon what kinds of things they build, grow and so on and at what experience levels they do that at, but I don't know whether it's best to just have different sets of events for different types of actions... like this NSDictionary buildParams NSDictionary dictionaryWithObjectsAndKeys \"Build Type\", \"Castle\", \"EXP\", \"234523\", Capture user status nil Flurry logEvent \"Build Action\" withParameters buildParams And so on... so another for growing something, another for training, et cetera. Or is it better to have one global type of record of an event like this NSDictionary actionParams NSDictionary dictionaryWithObjectsAndKeys \"Action\", \"Build\", \"Type\", \"Castle\", \"EXP\", \"44234\", nil Flurry logEvent \"Game Action\" withParameters actionParams In this method all the data is stored in the one event type. I'm not sure which will give me the best result when it comes to funneling, segmentation, and all that?"} {"_id": 37, "text": "Game Development Resources? I want to make an iPhone game and I was wondering if somebody could point me to some resources. Before you rage and close this, I am not looking for just a tutorial on programming, I could just google that. I need to find a tutorial on how to actually make a game, as in how to organize your code, what type of methods to run in separate threads, how to manage these threads in a game, etc. I already know everything I need I can write a physics engine from scratch, I can write a 3D graphics pipeline from scratch, and so on. What I cannot figure out is how to combine all of this knowledge into correctly and efficiently making a game. Obviously for this one would probably go to college, but seeing as I am still in high school, that is not an option. If anyone would know some tutorials or resources, any pointers would be appreciated."} {"_id": 37, "text": "Cocos 2D Hold down CCMenuItem I am using the following code to move a CCSprite left and right. (id)init CCMenuItemImage moveLeftButton CCMenuItemImage itemFromNormalImage \"Move Left Button.png\" selectedImage \"Move Left Button.png\" target self selector selector(moveLeftVoid ) (void)moveLeftVoid id moveLeft CCMoveBy actionWithDuration .3 position ccp( 10, 0) mainSprite runAction moveLeft This does work, but only as a single tap. What I want for the CCSprite to move continously in that direction when the CCMenuItem is held down. Then when it's released the character stops moving. If you need to see more code, please just ask. ) Thanks"} {"_id": 37, "text": "iPhone app activated before associated in app purchase activated? I recently submitted my iPhone game for review. I also approved the in app purchase for my game (and provided the in app purchase screenshot). It's a few days later and the app status has been updated from \"waiting for review\" to \"in review\"... while the in app purchase status is still \"waiting for review\". Could the app go live in the store before the in app purchase? If so what happens when the user tries to make the in app purchase? Anything the developer can do to remedy this?"} {"_id": 37, "text": "Any way to track speed of hand movements below iPhone 3.2? I have used the pan gesture for tracking the Pixel Per Second (or speed of the movement of the hand) but the real trouble is that the PanGesture library doesn't support any deployment target less than 3.2. So how would I track the speed of hand movements below a deployment target of 3.2?"} {"_id": 37, "text": "What are the restrictions of 3g online games I am looking into make a 3g online multiplayer game for the iphone. Multiplayer is my main focus but I have noticed all game apps require wi fi. Dose anyone know if this is simply an issue with the speed of the 3g network or dose apple put restrictions on their 3g network that prevents developers from doing this?"} {"_id": 37, "text": "Moving 2d camera in the y direction I'm developing a simple game for the iphone and am struggling to work out the best way for the camera to follow the main character. The following picture hightlights the three main components There are 3 components to this Circle the main character Green line terrain Black background The terrain is simply made from an array of points (approx 20 points per screen width). The terrain is moved in the x direction relative to the black background in order to keep the circle in its position shown. The distance to move the terrain is simply movex circle.position.x terrain.position.x with a constant to fix the circle at some distance from the left of the screen. I am struggling to determine the best way to position the terrain in the y plane keep the focus in the character. I want to move the terrain in the y direction smoothly and not fix it to the position of the circle, so the circle can move in the y plane. If I take the same approach as the x positioning, the character is fixed at a point on the screen and the terrain moves. I could sample some terrain points either side of the character and produce an average, but in my implementation this was not smooth. I thought another approach might be to create a camera 'line' that is a smooth version of the terrain line and make the camerea follow this, but I'm not sure if this is the optimum solution. Any advice is much appreciated!"} {"_id": 37, "text": "How can I implement temporary effects in Objective C? How could I use this IBAction (IBAction)shield (id)sender appDelegate.healthInt 150 and simply make it work for a limited time. I want to set appDelegate.healthint 150 for about 20 seconds. I'd assume this works with some sort of NSTimer. Not really sure. I'm not using any frameworks."} {"_id": 37, "text": "How do I open the camera in a CCScene node in a Cocos2D application? I am new to Cocos2D and I can't find the way to open the camera from the library. I want to open the camera in the my game, can any one help me with with this? Thank you in advance."} {"_id": 37, "text": "Issues with background coordinate configuration in objective c with runAction? In my game I want to have two backgrounds going one after the other creating a continuous loop moving to the left. However, right now one goes, and the other does not follow it. Here's what I currently have, which isn't working. if((self super init )) self.isTouchEnabled YES background CCSprite spriteWithFile \"testbackground88.png\" self addChild background z 1 background.position ccp(500,240) id repeat1 CCRepeatForever actionWithAction CCSequence actions CCMoveTo actionWithDuration 7 position ccp( 300,240) , CCPlace actionWithPosition ccp(800,240) ,nil background runAction repeat1 background2 CCSprite spriteWithFile \"testbackground92.png\" self addChild background2 z 1 background2.position ccp(500,240) id repeat2 CCRepeatForever actionWithAction CCSequence actions CCMoveTo actionWithDuration 7 position ccp( 300,240) , CCPlace actionWithPosition ccp(800,240) ,nil background2 runAction repeat2"} {"_id": 37, "text": "RTS game engine for iOS iPhone Anyone know any free or non free RTS engine that can be used for iOS game development?"} {"_id": 37, "text": "Detecting right left collisions with a bounding box I'm building a platformer in cocos2d, my first game project. I'm working on movement and collision detection. I'm using a tilemap with a \"meta\" layer of invisible blocks that are designated collidable. Everything seems to work pretty well except for one minor detail when the character jumps from above into a platform, he does not fall but clips through it. If he jumps from below, it recognizes it and resets his Y velocity accordingly. I know that it's because of how I'm detecting the collisions, and just doing a simple comparison of the origin.y's, but I'm unsure of how to refactor this code better (void) update (ccTime) dt CGPoint scaledVelocity ccpMult(leftJoystick.velocity, 35.0f) CGPoint newPosition ccp(player.position.x scaledVelocity.x dt, player.position.y) CGPoint oldPosition player position float velocityX player.Velocity.x scaledVelocity.x dt float velocityY player.Velocity.y BOOL isCollision NO BOOL isCollisionBelow NO BOOL isCollisionRight NO BOOL isCollisionLeft NO NSMutableArray collisionSprites NSMutableArray alloc init if (oldPosition.x gt newPosition.x) player.flipX YES else if (oldPosition.x lt newPosition.x) player.flipX NO for (CCSprite sprite in gameplayLayer.collidableTiles) if (CGRectIntersectsRect(player.boundingBox, sprite.boundingBox)) isCollision YES collisionSprites addObject sprite Figure out which direction collision is in if (isCollision) for (CCSprite collisionSprite in collisionSprites) if (collisionSprite.boundingBox.origin.y lt player.boundingBox.origin.y) isCollisionBelow YES if ((collisionSprite.boundingBox.origin.x gt player.boundingBox.origin.x) amp amp (collisionSprite.boundingBox.origin.y gt player.boundingBox.origin.y)) isCollisionRight YES if ((collisionSprite.boundingBox.origin.x lt player.boundingBox.origin.x) amp amp (collisionSprite.boundingBox.origin.y gt player.boundingBox.origin.y)) isCollisionLeft YES if (isCollisionLeft) velocityX 0.5f else if (isCollisionRight) velocityX 0.5f if (isCollision amp amp !isCollisionBelow amp amp player.characterState ! kStateFalling) velocityY 0 velocityY 0.8f player setCharacterState kStateFalling else if (!isCollisionBelow) velocityY 0.7f else if (isCollisionBelow) velocityY 0 player setCharacterState kStateIdle if (rightButton.active) if (player.characterState ! kStateJumping) velocityY 15.0f player setCharacterState kStateJumping Ground friction if (player.Velocity.x gt 0) if (player.Velocity.x lt 0.5f) velocityX 0 else velocityX 0.5f if (player.Velocity.x lt 0) velocityX 0.5f player setVelocity ccp(velocityX, velocityY) player setPosition ccp(player.position.x player.Velocity.x, player.position.y player.Velocity.y) gameplayLayer setViewpointCenter newPosition player setOldPosition player.position How can I refactor this code to work properly from all angles and reduce the complexity (I feel that there's too many booleans, and they all get a bit confusing)."} {"_id": 38, "text": "Why does my sprite player move faster when I move the mouse? I'm trying to develop a simple game made with Pygame (Python library). I have a sprite object which's the player and I move it using arrow keys. If I don't move the mouse, the sprite moves normally, but when I move the mouse, the sprite moves faster (like x2 or x3). The player object is inside the charsGroup var. I've run the game in W7 and in Ubuntu. Same thing happens in both OS. I have more entities which move like NPCs and bullets but they don't get affected, just the player. Given this, I think that the problem maybe has a direct connection with the player moving system (arrow keys). Here is the update() method of the player object def update(self) for event in pygame.event.get() key pygame.key.get pressed() mouseX, mouseY pygame.mouse.get pos() if event.type pygame.MOUSEBUTTONDOWN self.bulletsGroup.add(Bullet(pygame.image.load(\"bullet.png\"), self.rect.x (self.image.get width() 2), self.rect.y (self.image.get height() 2), mouseX, mouseY, 50, 50)) if key pygame.K RIGHT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K LEFT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K UP if not self.checkCollision() self.rect.y 10 else self.rect.y 10 if key pygame.K DOWN if not self.checkCollision() self.rect.y 10 else self.rect.y 10 And here is the while loop while True if PLAYER.healthBase lt 0 GAMEOVER True if not GAMEOVER mapTilesGroup.draw(SCREEN) charsGroup.update() charsGroup.draw(SCREEN) npcsGroup.update() npcsGroup.draw(SCREEN) drawBullets() for event in pygame.event.get() if event.type pygame.QUIT pygame.quit() sys.exit() if GAMEOVER myfont pygame.font.SysFont(\"monospace\", 30) label myfont.render(\"GAME OVER!\", 1, (255, 255, 0)) SCREEN.blit(label, (400, 300)) freq.tick(0) pygame.display.flip() I don't know what more you can need to help me, but anything you need (more info or code) just ask for it!"} {"_id": 38, "text": "Varying framerate (FPS) In my game loop, I am using fixed time step for physics and interpolation for rendering as suggested on Gaffer on Games Fix Your Timestep! However, when the framerate is varying between 30 60fps during the game, the game looks jumpy. For example, balls suddenly look accelerated when the frame rate increases from 35 to 45 suddenly. Is there a way to make the game look smooth while framerate is varying? Here is my game loop protected void update(float deltaTime) do some pre stuff deltaTimeAccumulator deltaTime deltaTimeAccumulator is a class member holding the accumulated frame time while(deltaTimeAccumulator gt FIXED TIME STEP) world.step(FIXED TIME STEP, 6, 2) perform physics simulation deltaTimeAccumulator FIXED TIME STEP world.step(deltaTime, 6, 2) destroyBodiesScheduledForRemoval() render(deltaTimeAccumulator FIXED TIME STEP) interpolate according to the remaining time Here is the part related to the interpolation (related inner works of render() method) this.prevPosition this.position get previously simulated position this.position body.getPosition() get currently simulated position interpolate Vector2 renderedPosition new Vector2() if (prevPosition ! null) amp amp !isFloatApproximatelyEquals(this.prevPosition.x, this.position.x) amp amp !isFloatApproximatelyEquals(this.prevPosition.y, this.position.y)) renderedPosition.x this.position.x interpolationAlpha this.prevPosition.x (1 interpolationAlpha) renderedPosition.y this.position.y interpolationAlpha this.prevPosition.y (1 interpolationAlpha) else renderedPosition position Draw the object at renderedPosition"} {"_id": 38, "text": "How and when should I update events occuring after a while? This question is not language specific but a more generic approach on how to deal with lazy updates for some game variables. Let's say, for instance, that I want to implement a \"character age system\" for a game. I guess that the \"age\" attribute does not need to be updated 60 times per second for each of my 10.000 or so RTS MMO characters. So, how to implement in the game loop the update of this \"long term\" variables that may have it value changed very sparsely? At the moment, I would implement some global variables to accumulate the delta time between the frames until it reaches a certain value, then, it resets and updates that variables. Is that correct? I mean, that's how things work? Or depending on the language plataform you would set some timers, or events that trigger the update of these variables?"} {"_id": 38, "text": "random spike in delta time The title pretty much sums it up. I'm using delta time to move my objects and every few seconds the delta time will spike and all the objects will jump forward. Should I just Interpolate the delta time to eliminate spikes, I don't want to do this because it could cause other problems but it could be a solution"} {"_id": 38, "text": "Design of a turn based game where actions have side effects I am writing a computer version of the game Dominion. It is a turn based card game where action cards, treasure cards, and victory point cards are accumulated into a player's personal deck. I have the class structure pretty well developed, and I am starting to design the game logic. I'm using python, and I may add a simple GUI with pygame later. The turn sequence of the players is governed by a very simple state machine. Turns pass clockwise, and a player can't exit the game before it is over. The play of a single turn is also a state machine in general, players pass through an \"action phase\", a \"buy phase\", and a \"clean up phase\" (in that order). Based on the answer to the question How to implement turn based game engine?, the state machine is a standard technique for this situation. My problem is that during a player's action phase, she can use an action card that has side effects, either on herself, or on one or more of the other players. For example, one action card allows a player to take a second turn immediately following the conclusion of the current turn. Another action card causes all other players to discard two cards from their hands. Yet another action card does nothing for the current turn, but allows a player to draw extra cards on her next turn. To make things even more complicated, there are frequently new expansions to the game that add new cards. It seems to me that hard coding the results of every action card into the game's state machine would be both ugly and unadaptable. The answer to Turn based Strategy Loop does not go into a level of detail that addresses designs to solve this problem. What kind of programming model should I use to encompass the fact that the general pattern for taking turns can be modified by actions that take place within the turn? Should the game object keep track of the effects of every action card? Or, if the cards should implement their own effects (e.g. by implementing an interface), what setup is required to give them enough power? I have thought up a few solutions to this problem, but I am wondering if there is a standard way to solve it. Specifically, I'd like to know what object class whatever is responsible for keeping track of the actions that every player must do as a consequence of an action card being played, and also how that relates to temporary changes in the normal sequence of the turn state machine."} {"_id": 38, "text": "Implement an upper FPS limit in the gameloop I implemented my game loop as described in deWiTTER's article, using the last approach with an unlimited FPS and a constant game speed. My problem is, that the unlimited FPS cranks up my CPU usage to nearly 100 . I understand that this is desired (as the hardware does as much as it can), but for my game, it's not really necessary (it's pretty simple). So I'd like to limit the FPS to some upper bound. Consider my game loop private static final int UPDATES PER SECOND 25 private static final int WAIT TICKS 1000 UPDATES PER SECOND private static final int MAX FRAMESKIP 5 long next update System.currentTimeMillis() int frames skipped float interpolation Start the loop while (isRunning) Update game frames skipped 0 while (System.currentTimeMillis() gt next update amp amp frames skipped lt MAX FRAMESKIP) Update input, move objects, do collision detection... Schedule next update next update WAIT TICKS frames skipped Calculate interpolation for smooth animation between states interpolation ((float)(System.currentTimeMillis() WAIT TICKS next update)) ((float)WAIT TICKS) Render events repaint(interpolation) How would I implement a maximum FPS? If i implement the repaint the way I implemented the update (or use a sleep instead of \"do nothing cycles\"), then the FPS is locked, right? That is not what I want. I want the game to be able to work with lower FPS (just as it does now), but limit the FPS to a maximum of, say 250."} {"_id": 38, "text": "Windows Forms game loop There is a very good game loop in the link which is tailored for windows forms. I need it in c cli so I converted the code as below. Here is my main loop. using namespace System using namespace System Windows Forms HWND g theAppHandle nullptr bool IsApplicationIdle() MSG msg return PeekMessage( amp msg, g theAppHandle, 0, 0, 0) 0 void OnIdle(System Object sender, System EventArgs e) while (IsApplicationIdle()) if (PunkEd ABTCLI g initSuccess) PunkEd ABTCLI Frame(0.0f) STAThread int CALLBACK WinMain( In HINSTANCE hInstance, In HINSTANCE hPrevInstance, In LPSTR lpCmdLine, In int nCmdShow ) CrtMemState memstate CrtMemCheckpoint( amp memstate) PunkEd PunkEdMain theApp gcnew PunkEd PunkEdMain g theAppHandle (HWND)theApp gt Handle.ToPointer() Application Idle gcnew System EventHandler( amp OnIdle) Application Run(theApp) CrtMemDumpAllObjectsSince( amp memstate) return 0 This loop triggers PunkEd ABTCLI Frame(0.0f) every time the application is idle. And Frame(float deltaTime) function triggers everyting related to game. Like render and physics. However my rendering window is a panel. And I override its mouse move callback as below. private System Void panel1 MouseMove(System Object sender, System Windows Forms MouseEventArgs e) Debug WriteLine(e gt Location) glm vec3 cp glm vec3(e gt Location.X, e gt Location.Y, 0) glm mat4 view g camera gt GetViewMatrix() glm mat4 project g camera gt m projection glm unProject(cp, view, project, glm vec4(0.0f, 0.0f, (float)panel1 gt Width, (float)panel1 gt Height)) cp.x panel1 gt Width 2.0f cp.y panel1 gt Height 2.0f g cursor gt m node gt m translation cp.xzy This function updates my curser's position in the game. However my render function is get called after I stop moving the mouse. How can I overcome this stuation such that my curser position gets update and renders immediatly after I moved mouse."} {"_id": 38, "text": "JavaFX AnimationTimer VS Swing Game Loop After looking at some code sources out there I noticed Java Swing Games usually create a class implementing Runnable, create a new Thread and set up the game loop in the run() call. But JavaFX games seem to simply extend from Application and run the game loop in a new AnimationTimer() ... public void handle() ... What gives?"} {"_id": 38, "text": "NodeJS setTimeOut How to run callback before delay time exceeded I'm developing a card game server. I want to do this While server process a turn for players, players have 20 seconds to do something. If players send a request to server within 20 secs, timer will stop and the callback will fire. I'm doing like this self.tables table.id .currentTimer setTimeout(function () callback() , 20 1000) How should I run the callback before delay time exceeded ?"} {"_id": 38, "text": "Windows Forms game loop There is a very good game loop in the link which is tailored for windows forms. I need it in c cli so I converted the code as below. Here is my main loop. using namespace System using namespace System Windows Forms HWND g theAppHandle nullptr bool IsApplicationIdle() MSG msg return PeekMessage( amp msg, g theAppHandle, 0, 0, 0) 0 void OnIdle(System Object sender, System EventArgs e) while (IsApplicationIdle()) if (PunkEd ABTCLI g initSuccess) PunkEd ABTCLI Frame(0.0f) STAThread int CALLBACK WinMain( In HINSTANCE hInstance, In HINSTANCE hPrevInstance, In LPSTR lpCmdLine, In int nCmdShow ) CrtMemState memstate CrtMemCheckpoint( amp memstate) PunkEd PunkEdMain theApp gcnew PunkEd PunkEdMain g theAppHandle (HWND)theApp gt Handle.ToPointer() Application Idle gcnew System EventHandler( amp OnIdle) Application Run(theApp) CrtMemDumpAllObjectsSince( amp memstate) return 0 This loop triggers PunkEd ABTCLI Frame(0.0f) every time the application is idle. And Frame(float deltaTime) function triggers everyting related to game. Like render and physics. However my rendering window is a panel. And I override its mouse move callback as below. private System Void panel1 MouseMove(System Object sender, System Windows Forms MouseEventArgs e) Debug WriteLine(e gt Location) glm vec3 cp glm vec3(e gt Location.X, e gt Location.Y, 0) glm mat4 view g camera gt GetViewMatrix() glm mat4 project g camera gt m projection glm unProject(cp, view, project, glm vec4(0.0f, 0.0f, (float)panel1 gt Width, (float)panel1 gt Height)) cp.x panel1 gt Width 2.0f cp.y panel1 gt Height 2.0f g cursor gt m node gt m translation cp.xzy This function updates my curser's position in the game. However my render function is get called after I stop moving the mouse. How can I overcome this stuation such that my curser position gets update and renders immediatly after I moved mouse."} {"_id": 38, "text": "How do games implement client server frame rate? Do games have a frame rate at X fps that updates logic and also renders? Or do games update logic at a much slower frame rate than rendering? Let's say 20 25 fps for logic, and 60 fps for rendering. I am writing a game engine and I am a bit confused on how frame rate is handled. If I were to run logic slower than rendering, then wouldn't I just be wasting the rendering frames because it is rendering the same thing over and over...? Unless I also interpolate the rendering with a delta. I have read some game servers run at a much slower frame rate (let's say 20 FPS), so shouldn't the client also run logic at 20 FPS?"} {"_id": 38, "text": "What is the point of update independent rendering in a game loop? There are dozens of articles, books and discussions out there on game loops. However, I pretty often come across something like this while(running) processInput() while(isTimeForUpdate) update() render() What basically is bothering me about this approach is the \"update independent\" rendering e.g. render a frame when there is no change at all. So my question is why this approach is often taught?"} {"_id": 38, "text": "Game Loop Problem Growth and Recharge as Integer Values I have a question about game loops. I understand that you shouldn't have a static loop, say 100ms and set something's speed to 1px frame so it moves 10px sec. You should have a speed and multiple that by the elapsed time so frame rate does not effect game speed. This works fine for values that can be floats, but what if I need integer values? Say shields recharging or something. I have a damage system is my game and I would really love to stay away from float damage values, both for memory and game design reasons. However if I just have a running total of elapsed time, and I recharge one point once this elapsed time is over 1 second then over the course of time won't I have some consistency errors between recharging over one set of 100 real seconds and another set of 100 real seconds because those two sets may not have the same number of frames in them. This questions also comes up in rate of fire. If I need a turret to fire every .5seconds, won't there be some variance if I do a running total of elapsed time? Sometimes it may fire every .501 seconds and other time .510 seconds? I guess my question is, how exact are games really? Do most games just do a check every frame and say, \"Well your rate of fire is .5 seconds, and its been .504 since you last fired, so fire now.\" If so would it work out for the next fire cycle to only check for .496 seconds to average out? I know it most games under 10 minutes this would barely be noticeable, but over the long term this may actually mater in some cases."} {"_id": 38, "text": "Separate draw and physics loops I there a point in updating the physics at a different rate than drawing taking input? Is it just to exploit parallelism? I've heard that many engines update the physics at 15FPS but render at 60FPS. What's the point in rendering the same image four times until it changes if it doesn't add fluidity?"} {"_id": 38, "text": "LUA Keeping track of game state for a digital card trading game I am building a card game. Let's say it's similar to Magic the Gathering, Hearthstone, etc. The problem I am trying to figure out is how to architect \"auras\" and how much damage each card takes. Right now I have a deck and I store card data as follows. I've made up names for the types of cards that will exist. M.card Minion cards have health and damage M.card 1 .name \"Minion\" M.card 1 .hp 1 M.deck 1 .dmg 1 Super Minions have more health and damage M.card 2 .name \"Super Minion\" M.card 2 .hp 4 M.card 2 .dmg 4 Spell cards have no health and damage. Instead they affect the health and damage of other cards. M.card 3 .name \"Heal\" M.card 3 .details \"This card heals any character for 2 health\" M.card 3 .healthboost 2 M.card 4 .name \"Damage Boost\" M.card 4 .details \"This card gives 1 damage to any other card for 1 turn\" M.card 4 .dmgboost 1 Super damage boost gives more damage boost to other cards M.card 5 .name \"Super Damage Boost\" M.card 5 .details \"This card gives 3 damage to any other card permanently\" M.card 5 .dmgboost 3 So when one card attacks another card, I need to keep track of the damage taken by both cards. I don't want to change the base stats of each card so I need to keep track of adjustments. I could do something like this Super Minion takes 3 damage M.card 2 .newHp 1 or M.card 2 .adjHp 3 Not sure which is better. During the battle I need to keep track of which auras are played. So for example if the Damage boost card is played. I need to give another card 1 damage for just one turn. Let's say that I am keep track of each turn number starting from 1. Should I do something like this M.aura 1 4 ( aura 1 is card 4) M.aura 1 .target 2 (this aura is applied to card 2) M.aura 1 .expires 5 (this aura expires on turn 5) M.aura 2 3 ( second active aura is heal, card 3 ) M.aura 2 .target 2 M.aura 2 .expires 0 this is a one time aura. So I need to apply it to card 2 and then immediately expire it so it never activates again. Then on every new turn I loop through all the auras and make sure they are still active before a fight begins? Just wondering architecturally what is the best way to keep track of Damage that characters have taken and spells that are active that are giving characters special abilities."} {"_id": 38, "text": "Game loops using Hard realtime systems vs Soft realtime systems I have read the article here about realtime systems and am looking for examples specific to game loops. Am I correct in saying Hard realtime systems will lag and slow down gameplay causing slow motion if processing of AI, collision detection, or user input is delayed past the rendering deadline set by the realtime system. Example, must render every 1 30 sec but processing caused delay to 1 20 sec. Soft realtime systems will render at 30 FPS regardless of the other subsystems processing but if there is a delay in AI, collision detection, or user inputs, the game will be presented in stop motion instead of slow motion every 1 30 sec."} {"_id": 38, "text": "Delta times and frame lag in the game loop Let's say we have a standard gameloop like this, in pseudocode while (true) dt GetDeltaTime() Update(dt) Render() Here Update(dt) either uses a true variable timestep, or it determines how many cycles of a fixed timestep physics loop to execute based on dt. Now say we have the common case where we have mostly constant framerate except for infrequent single frame hiccups, so let's say we have dt values like 1 60, 1 60, 1 60, 1 6, 1 60, 1 60, ... By the time our GetDeltaTime() detects the larger timestep in the fourth frame, we have already rendered and presented the fourth frame! So one frame will already have been rendered with a wrong (too small) timestep no matter what we do. So if we now use the larger dt 1 6 to render the fifth frame, my understanding is that we artificially create a second frame where a wrong timestep is used, this time a too large one. I wonder if this problem is acknowledged anywhere. Wouldn't it be better, say, to use the averaged dt over the previous few frames to combat this? Here are some pictures to illustrate what I mean. I use the example of an object moving along a fixed axis with a constant speed, and using a variable timestepping scheme. The problem is essentially the same with fixed timesteps, though. The plots have time on the x axis, and the object position on the y axis. Let's say the object moving at 1 unit s, and framerate is 1 Hz. This is the ideal situation. Now let's say we have a frame where the time interval is 2 instead of 1. With a classical dt based scheme, we get this So we have one frame where the velocity is perceived too low, and one where it is perceived too high and which corrects for the velocity in the previous frame. What if we instead, say, always use a constant (or very slowly changing) dt? We get this The perceived velocity seems smoother using this approach to me. Of course, the object position is now not the \"true\" one, but I think humans perceive abrupt changes in velocity more clearly than such small positional offsets. Thoughts? UPDATE At least Ogre can do this http ogre.sourcearchive.com documentation 1.6.4.dfsg1 1 classOgre 1 1Root 1f045bf046a75d65e6ddc71f4ebe0b2c.html So I guess I just got downvoted for people not understanding my question, which is rather frustrating."} {"_id": 38, "text": "UPS and FPS What should I limit and why? I'm currently writing a game using C and SDL2 and there's one thing that I'm wondering about does it make sense to limit my frames per second (FPS) and or my updates per second (UPS)? I get the idea that if you limit the UPS, you essentially control the speed of the game if the player moves 1px per update and you always update it 30 times per second, he'll move at a speed of 30px s and you'll probably also relieve the CPU since the amount of calculations per second decreases. If you limit the FPS, the amount of drawcalls per second decreases, therefore you relieve your GPU. I hope I understood all of that correctly, if not, feel free to correct me. My question is what am I supposed to limit in my game? FPS? UPS? Both? Neither? Is there another, better approach to this? How is this done in most games and why? Answers are greatly appreciated!"} {"_id": 38, "text": "render draw or input first? When creating the main game loop, what order should things generally happen? IE, should i be getting input, doing logic and then rendering, or something else? does this even matter? when i was coding with python and pygame the tutorial i was using pointed me towards the aforementioned method. however, A tutorial for LWJGL2 (http thecodinguniverse.com lwjgl window ) does it like this while (!Display.isCloseRequested()) While no attempt to close the display is made.. Put render code here. Put input handling code here. Display.update() Refresh the display and poll input. Display.sync(60) Wait until 16.67 milliseconds have passed. (Maintain 60 frames per second) and (so far) doesn't seem to have hinted at logic (though i assume it will later on, and looks like it might put it last) so which should i be using? does it matter at all? i'm using LWJGL2."} {"_id": 38, "text": "JavaFX AnimationTimer VS Swing Game Loop After looking at some code sources out there I noticed Java Swing Games usually create a class implementing Runnable, create a new Thread and set up the game loop in the run() call. But JavaFX games seem to simply extend from Application and run the game loop in a new AnimationTimer() ... public void handle() ... What gives?"} {"_id": 38, "text": "Delta times and frame lag in the game loop Let's say we have a standard gameloop like this, in pseudocode while (true) dt GetDeltaTime() Update(dt) Render() Here Update(dt) either uses a true variable timestep, or it determines how many cycles of a fixed timestep physics loop to execute based on dt. Now say we have the common case where we have mostly constant framerate except for infrequent single frame hiccups, so let's say we have dt values like 1 60, 1 60, 1 60, 1 6, 1 60, 1 60, ... By the time our GetDeltaTime() detects the larger timestep in the fourth frame, we have already rendered and presented the fourth frame! So one frame will already have been rendered with a wrong (too small) timestep no matter what we do. So if we now use the larger dt 1 6 to render the fifth frame, my understanding is that we artificially create a second frame where a wrong timestep is used, this time a too large one. I wonder if this problem is acknowledged anywhere. Wouldn't it be better, say, to use the averaged dt over the previous few frames to combat this? Here are some pictures to illustrate what I mean. I use the example of an object moving along a fixed axis with a constant speed, and using a variable timestepping scheme. The problem is essentially the same with fixed timesteps, though. The plots have time on the x axis, and the object position on the y axis. Let's say the object moving at 1 unit s, and framerate is 1 Hz. This is the ideal situation. Now let's say we have a frame where the time interval is 2 instead of 1. With a classical dt based scheme, we get this So we have one frame where the velocity is perceived too low, and one where it is perceived too high and which corrects for the velocity in the previous frame. What if we instead, say, always use a constant (or very slowly changing) dt? We get this The perceived velocity seems smoother using this approach to me. Of course, the object position is now not the \"true\" one, but I think humans perceive abrupt changes in velocity more clearly than such small positional offsets. Thoughts? UPDATE At least Ogre can do this http ogre.sourcearchive.com documentation 1.6.4.dfsg1 1 classOgre 1 1Root 1f045bf046a75d65e6ddc71f4ebe0b2c.html So I guess I just got downvoted for people not understanding my question, which is rather frustrating."} {"_id": 38, "text": "Exchanging data between custom built hardware and games I have a built my own steering wheel and motion platform that I would like to connect to popular car racing games (e.g. iRacing, Dirt Rally). I need to read data such as the car's acceleration (to send to the motion platform) from these games and send information such as steering wheel's angle to the game. I have written an SDK in C to communicate with my steering will and motion platform. Now I need to interface different games with to that SDK. I searched quite a bit but could not find much information about how this is generally done. Do game developers provide some sort of extension which allows third party hardware developers to communicate with their game? Any guidance from the community is much appreciated. Kam"} {"_id": 38, "text": "How and when should I update events occuring after a while? This question is not language specific but a more generic approach on how to deal with lazy updates for some game variables. Let's say, for instance, that I want to implement a \"character age system\" for a game. I guess that the \"age\" attribute does not need to be updated 60 times per second for each of my 10.000 or so RTS MMO characters. So, how to implement in the game loop the update of this \"long term\" variables that may have it value changed very sparsely? At the moment, I would implement some global variables to accumulate the delta time between the frames until it reaches a certain value, then, it resets and updates that variables. Is that correct? I mean, that's how things work? Or depending on the language plataform you would set some timers, or events that trigger the update of these variables?"} {"_id": 38, "text": "Events and objects being skipped in GameMaker Update Turns out it's not an issue with this code (or at least not entirely). Somehow the objects I use for keylogging and player automation (basic ai that plays the game) are being 'skipped' or not loaded about half the time. These are invisible objects in a room that have basic effects such are simulating button presses, or logging them. I don't know how to better explain this problem without putting up all my code, so unless someone has heard of this issue I guess I'll be banging my head against the desk for a bit Update I've been continuing work on modifying Spelunky, but I've run into a pretty major issue with GameMaker, which I hope is me just doing something wrong. I have the code below, which is supposed to write log files named sequentially. It's placed in a End Room event such that when a player finishes a level, it'll write all their keypress's to file. The problem is that it randomly skips files, and when it reaches about 30 logs it stops creating any new files. var file name file count 4 file name file find first(\"logs .txt\", 0) while (file name ! \"\") file count 1 file name file find next() file find close() file file text open write(\"logs log\" string(file count) \".txt\") for(i 0 i lt ds list size(keyCodes) i 1) file text write string(file, string(ds list find value(keyCodes, i))) file text write string(file, \" \") file text write string(file, string(ds list find value(keyTimes, i))) file text writeln(file) file text close(file) My best guess is that the first counting loop is taking too long and the whole thing is getting dropped? Also, if anyone can tell me of a better way to have sequentially numbered log files that would also be great. Log files have to continue counting over multiple start stops of the game."} {"_id": 38, "text": "how to handle interactive choice in the middle of the game loop? I am programming a turn based game, 2D tile based, overhead view. I have an update function and a render function running in separate threads. When it's the player's turn, the player can e.g. select a target tile from the map then a popup menu with the available interactions appears player selects interaction and the interaction gets executed One tedious way is the following GameLoopUpdate() switch( interaction state ) case tile selected lookup interactions for selected tile() break case tile and interaction selected() execute interaction at tile() break default break Of course the above does not scale when the interactions get complex. Conceptually, I would like it to be more like KeyListener() if tile is clicked set tile selected() GameLoopUpdate() if tile is selected interaction spawn thread interaction selection() execute interaction at tile( interaction ) where the spawned thread would somehow override the input listeners AND the rendering. But this looks bad as well. Another idea (I'm starting to consider implementing this) is the following GameLoopUpdate() if it's player's turn set next state as PlayerState Base else run ai turn PlayerState Base() if tile is selected set next state as PlayerState TileSelected PlayerState TileSelected() if interaction is selected execute interaction set player's turn as done where each state above would have dedicated key listener and rendering functions Any other ideas?"} {"_id": 38, "text": "Is creating a separate thread for each game session a bad idea? I'm currently working on iocp game server. My game is just like diablo3 basically. 1 4 players join a separate session. I did basic iocp preparations and now I'm working on game session class. The reason why I'm stuck right now is that I'm not sure if I should create a separate thread for each game session. This concept is the first idea that I came up with but I can't come up with other ideas to avoid creating so many threads for sessions when there are so many game sessions. So here's my question. Should I create a separate game logic loop(thread) for each game session? Because that sounds so inefficient when it comes to the situation where only one player joins each session. If there are some other ways to design the server, please let me know what I should look for to study. Thanks for your help in advance and sorry for my bad English."} {"_id": 38, "text": "random spike in delta time The title pretty much sums it up. I'm using delta time to move my objects and every few seconds the delta time will spike and all the objects will jump forward. Should I just Interpolate the delta time to eliminate spikes, I don't want to do this because it could cause other problems but it could be a solution"} {"_id": 38, "text": "Why does the triangle rendered by OpenGL ES 2.0 , with SDL 2.0 context, vanishes after a single render, if events are not polled? I was experimenting with OpenGL ES 2.0 and being new to OpenGL, I was trying to render a simple triangle. But I was shocked to see that, if I do not call SDL PollEvent(...) after glDrawArrays(...) in the game loop, I see the triangle render on the screen for a split second and then it vanishes altogether ! But, if I call SDL PollEvent then everything is fine ! Can anyone explain to me the reason for this abnormal behavior??? However, this is the interesting part of my code This code works perfectly, if I uncomment the commented block of code uint32 t vbo glGenBuffers(1, amp vbo) glBindBuffer(GL ARRAY BUFFER, vbo) glBufferData(GL ARRAY BUFFER, sizeof(vertices), vertices, GL STATIC DRAW) glEnableVertexAttribArray(pos) glVertexAttribPointer(pos, 3, GL FLOAT, GL FALSE, 3 sizeof(float), (void )0) bool run true SDL Event e while (run) glDrawArrays(GL TRIANGLES, 0, 3) SDL GL SwapWindow(window) while(SDL PollEvent( amp e)) switch(e.type) case SDL QUIT run false break Vertex Shader precision mediump float attribute vec3 pos void main() gl Position vec4(pos.xyz, 1.0) Fragment Shader precision mediump float void main() gl FragColor vec4(0.0, 0.0, 1.0, 1.0) Every help will be greatly appreciated, Thankyou everyone in advance !"} {"_id": 38, "text": "JavaFX AnimationTimer VS Swing Game Loop After looking at some code sources out there I noticed Java Swing Games usually create a class implementing Runnable, create a new Thread and set up the game loop in the run() call. But JavaFX games seem to simply extend from Application and run the game loop in a new AnimationTimer() ... public void handle() ... What gives?"} {"_id": 38, "text": "Varying framerate (FPS) In my game loop, I am using fixed time step for physics and interpolation for rendering as suggested on Gaffer on Games Fix Your Timestep! However, when the framerate is varying between 30 60fps during the game, the game looks jumpy. For example, balls suddenly look accelerated when the frame rate increases from 35 to 45 suddenly. Is there a way to make the game look smooth while framerate is varying? Here is my game loop protected void update(float deltaTime) do some pre stuff deltaTimeAccumulator deltaTime deltaTimeAccumulator is a class member holding the accumulated frame time while(deltaTimeAccumulator gt FIXED TIME STEP) world.step(FIXED TIME STEP, 6, 2) perform physics simulation deltaTimeAccumulator FIXED TIME STEP world.step(deltaTime, 6, 2) destroyBodiesScheduledForRemoval() render(deltaTimeAccumulator FIXED TIME STEP) interpolate according to the remaining time Here is the part related to the interpolation (related inner works of render() method) this.prevPosition this.position get previously simulated position this.position body.getPosition() get currently simulated position interpolate Vector2 renderedPosition new Vector2() if (prevPosition ! null) amp amp !isFloatApproximatelyEquals(this.prevPosition.x, this.position.x) amp amp !isFloatApproximatelyEquals(this.prevPosition.y, this.position.y)) renderedPosition.x this.position.x interpolationAlpha this.prevPosition.x (1 interpolationAlpha) renderedPosition.y this.position.y interpolationAlpha this.prevPosition.y (1 interpolationAlpha) else renderedPosition position Draw the object at renderedPosition"} {"_id": 38, "text": "Games development with a game loop that's abstracted away Most game development happens with a main game loop. Are there any good articles blog posts discussions about games without a game loop? I imagine they'd mostly be web games, but I'd be interested in hearing otherwise. (As a side note, I think it's really interesting that the concept is almost exclusively used in gaming as far as I'm aware, perhaps that may be another question.) Edit I realize there's probably a redraw loop somewhere. I guess what I really mean is a loop that is hidden to you. Frames are something you as the developer are not concerned with as you're working on a higher level of abstraction. E.g. someLootItem.moveTo(inventory, someAnimatationType) and that will move from the loot box to your inventory using the specified animation type without the game developer having to worry about the implementation details of that animation. Maybe that's how \"real\" games end up working, but from reading most tutorials they seem to imply a much more granular level of control is used, but that might just be an artifact of being a tutorial. Edit2 I think most people are misunderstanding what I'm trying to ask, likely because I'm having trouble describing exactly what I'm trying to ask. After some more thinking perhaps what I'm referring to is more along the lines of what I believe is referred to as \"scripting\" where you're working at a very high level and having some game engine take care of the low level details. For example, take custom maps in Starcraft II or Warcraft III. Many of the \"maps\" have gameplay that deviates enough from the primary game that they could be considered a separate game written on the same engine. What I'm referring to then is along those lines. I may be wrong because I only dabbed in the Warcraft III editor, but as far as I remember no where in the map editor do you control the game loop, and yet you can create many different games out of it. In my mind, these are games in their own right. If you're playing DotA you don't say you're playing Warcraft III, you say you're playing DotA because that's the actual game you're playing. Such a system may impose limitations that don't exist if you're creating a game from scratch, but it greatly reduces development time because much of the \"hard\" work has already been done for you. Hopefully that clarifies what I'm asking. Another example of what is I mean, is when you write a web app, of course it communicates through sockets and TCP. But does the average web developer doesn't explicitly write code for connecting sockets. They just need to know about receiving a request and sending a response. There are unique scenarios where you do occasionally need to use raw sockets, but it's generally rare in web development. In a similar fashion, it's very possible to write a game without directly using the game loop, even though one is used behind the scenes. Probably not a AAA title, but there must be hundreds of smaller scale games that can and possibly are written this way. Are there any good resources on writing these \"simpler\" games?"} {"_id": 38, "text": "Why does my sprite player move faster when I move the mouse? I'm trying to develop a simple game made with Pygame (Python library). I have a sprite object which's the player and I move it using arrow keys. If I don't move the mouse, the sprite moves normally, but when I move the mouse, the sprite moves faster (like x2 or x3). The player object is inside the charsGroup var. I've run the game in W7 and in Ubuntu. Same thing happens in both OS. I have more entities which move like NPCs and bullets but they don't get affected, just the player. Given this, I think that the problem maybe has a direct connection with the player moving system (arrow keys). Here is the update() method of the player object def update(self) for event in pygame.event.get() key pygame.key.get pressed() mouseX, mouseY pygame.mouse.get pos() if event.type pygame.MOUSEBUTTONDOWN self.bulletsGroup.add(Bullet(pygame.image.load(\"bullet.png\"), self.rect.x (self.image.get width() 2), self.rect.y (self.image.get height() 2), mouseX, mouseY, 50, 50)) if key pygame.K RIGHT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K LEFT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K UP if not self.checkCollision() self.rect.y 10 else self.rect.y 10 if key pygame.K DOWN if not self.checkCollision() self.rect.y 10 else self.rect.y 10 And here is the while loop while True if PLAYER.healthBase lt 0 GAMEOVER True if not GAMEOVER mapTilesGroup.draw(SCREEN) charsGroup.update() charsGroup.draw(SCREEN) npcsGroup.update() npcsGroup.draw(SCREEN) drawBullets() for event in pygame.event.get() if event.type pygame.QUIT pygame.quit() sys.exit() if GAMEOVER myfont pygame.font.SysFont(\"monospace\", 30) label myfont.render(\"GAME OVER!\", 1, (255, 255, 0)) SCREEN.blit(label, (400, 300)) freq.tick(0) pygame.display.flip() I don't know what more you can need to help me, but anything you need (more info or code) just ask for it!"} {"_id": 38, "text": "Game Logic Update Order Is there a commonly accepted general approach to the order of processing logic updates? My current 2D platformer has objects that implement different concerns, including the following Notifiable can be event driven and scripted Collidable can interact with solid tiles (eg NPCs) Intersectable exists in 2D space and can intersect with the player (eg doors) In general the order of events in a game loop is Get input Act on input and update stuff Render I'm not sure what order to do things in point 2. I've concluded moving things like moving platforms that the player can stand on first is a good idea, but I don't know when to consider scripting. The scripting in my game can give NPCs behaviours (walk between here and there), suspend player input for 'cutscenes', show dialog screens, and move the player to a new level."} {"_id": 38, "text": "Game Loop design that is speed hack proof I'm not sure if this is possible, but it's worth a shot asking. How does one design a game loop in such a way that hooking and enabling a speed hack app to the game(dx11) doesn't matter? I found this in stackoverflow I think the reason why i does not work in some applications (mostly games) is because some games link the in game clock to the frames per second. Therefore your game will either tank or crash altogether if you try to speedhack it ref https stackoverflow.com questions 17512906 how does cheatengines speed hack work"} {"_id": 38, "text": "What is the point of update independent rendering in a game loop? There are dozens of articles, books and discussions out there on game loops. However, I pretty often come across something like this while(running) processInput() while(isTimeForUpdate) update() render() What basically is bothering me about this approach is the \"update independent\" rendering e.g. render a frame when there is no change at all. So my question is why this approach is often taught?"} {"_id": 38, "text": "Multiple pipelined game loops I am considering using the following game engine design pattern, but I am unsure if it's a good idea or not Each major task (drawing, physics, logic, networking, disk I O) will have its own isolated thread or subprocess Each of these threads can be put to sleep if it is running too quickly, so as to not consume an excess of CPU resources Threads can only talk to each other through some well defined interface to avoid messy, buggy, thread unsafe conditions from occurring This approach enables parallelism and scalability, but causes a thread safety problem what if one thread is accessing data that another thread is currently processing? We could introduce fine grained locking, but it still can't be guaranteed that the collective states of all of a thread's data objects are coherent. To solve this, collections of objects are maintained inside state objects, and state objects are double buffered. The intent of this is to ensure that other threads only see a valid, coherent set of data. If one thread happens to be processing data that another thread wants to read, then the other thread reads from a buffered state, which is guaranteed not to be written to. However, buffering these states introduces a delay where one thread sees old data from the last cycle of the other thread. Another problem might occur when a reading thread has a slower \"tick rate\" than a writing thread the writing thread may have flipped the state buffer multiple times, while the reading thread is still processing one \"tick\" using the same state. However this can be solved using OO references. Pipelining should be achievable using this approach, because the draw thread could be drawing information that entered the pipeline 30 milliseconds ago, while more information is being processed Ultimately, what I'd like to see is completely decoupled processing for all of the tasks in a game, implemented in a way that helps leverage multi core environments, and maybe leaves some future expansion room for scaling the server side of things amongst multiple machines. I am aware that this is probably overkill for most purposes ) What are the criticisms or pitfalls of this approach? Is this the \"right\" way to do things? Am I thinking about this backwards?"} {"_id": 38, "text": "Game Loop design that is speed hack proof I'm not sure if this is possible, but it's worth a shot asking. How does one design a game loop in such a way that hooking and enabling a speed hack app to the game(dx11) doesn't matter? I found this in stackoverflow I think the reason why i does not work in some applications (mostly games) is because some games link the in game clock to the frames per second. Therefore your game will either tank or crash altogether if you try to speedhack it ref https stackoverflow.com questions 17512906 how does cheatengines speed hack work"} {"_id": 38, "text": "Should I bother with SDL WaitEvent? When I wrote my first application in SDL, it looked like this while (!quit) SDL PollEvent( amp event) switch (event) ... But then one time I left my app running while I went to do something else, and when I came back my laptop was boiling hot. I checked the system monitor and one of my cores was maxed out by my program! So I did some research, and now my loop looks like this while (!quit) SDL WaitEvent( amp event) switch (event) ... Great, so now my program doesn't max the CPU. But now I need to introduce rendering, and the problem is, currently this loop runs one iteration per event. If input and other events don't occur, my program won't render the next frame, no matter where the rendering code goes in the loop. So that's no good. I could have threads, but that seems like a lot of extra complexity when I could just do while (!quit) SDL PollEvent( amp event) switch (event) ... SDL Delay(10) This won't melt the CPU, and I can render at about 100 frames per second. My questions are Which approach quot should quot I use? I don't see any reason to not just use (3). What's the point of SDL WaitEvent, if you can't use it the moment you want to do anything other than handle events in your game loop? I assume SDL WaitEvent does something like approach (3) under the hood, so even though ostensibly approach (3) should introduce more latency, in practice it won't. Is this correct? How low should the integer passed to SDL Delay be to get a responsive app?"} {"_id": 38, "text": "Exchanging data between custom built hardware and games I have a built my own steering wheel and motion platform that I would like to connect to popular car racing games (e.g. iRacing, Dirt Rally). I need to read data such as the car's acceleration (to send to the motion platform) from these games and send information such as steering wheel's angle to the game. I have written an SDK in C to communicate with my steering will and motion platform. Now I need to interface different games with to that SDK. I searched quite a bit but could not find much information about how this is generally done. Do game developers provide some sort of extension which allows third party hardware developers to communicate with their game? Any guidance from the community is much appreciated. Kam"} {"_id": 38, "text": "Should I send the elapsed time to the fixed step update function from my game loop? I am making a basic game loop based on this article. This is the nearly final version double previous getCurrentTime() double lag 0.0 while (true) double current getCurrentTime() double elapsed current previous previous current lag elapsed processInput() while (lag gt MS PER UPDATE) update() lag MS PER UPDATE render() But I think the update function should have elapsed time passed to it so that the game state is calculate based on that. So this should be the correct version double previous getCurrentTime() double lag 0.0 while (true) double current getCurrentTime() double elapsed current previous previous current lag elapsed processInput() while (lag gt MS PER UPDATE) update(elapsed) gt gt gt ?? lag MS PER UPDATE render() Am I right? Because I think a physics engine should always have a delta time to calculate state changes."} {"_id": 38, "text": "Design of a turn based game where actions have side effects I am writing a computer version of the game Dominion. It is a turn based card game where action cards, treasure cards, and victory point cards are accumulated into a player's personal deck. I have the class structure pretty well developed, and I am starting to design the game logic. I'm using python, and I may add a simple GUI with pygame later. The turn sequence of the players is governed by a very simple state machine. Turns pass clockwise, and a player can't exit the game before it is over. The play of a single turn is also a state machine in general, players pass through an \"action phase\", a \"buy phase\", and a \"clean up phase\" (in that order). Based on the answer to the question How to implement turn based game engine?, the state machine is a standard technique for this situation. My problem is that during a player's action phase, she can use an action card that has side effects, either on herself, or on one or more of the other players. For example, one action card allows a player to take a second turn immediately following the conclusion of the current turn. Another action card causes all other players to discard two cards from their hands. Yet another action card does nothing for the current turn, but allows a player to draw extra cards on her next turn. To make things even more complicated, there are frequently new expansions to the game that add new cards. It seems to me that hard coding the results of every action card into the game's state machine would be both ugly and unadaptable. The answer to Turn based Strategy Loop does not go into a level of detail that addresses designs to solve this problem. What kind of programming model should I use to encompass the fact that the general pattern for taking turns can be modified by actions that take place within the turn? Should the game object keep track of the effects of every action card? Or, if the cards should implement their own effects (e.g. by implementing an interface), what setup is required to give them enough power? I have thought up a few solutions to this problem, but I am wondering if there is a standard way to solve it. Specifically, I'd like to know what object class whatever is responsible for keeping track of the actions that every player must do as a consequence of an action card being played, and also how that relates to temporary changes in the normal sequence of the turn state machine."} {"_id": 38, "text": "Turn based Strategy Loop I'm working on a strategy game. It's turn based and card based (think Dominion style), done in a client, with eventual AI in the works. I've already implemented almost all of the game logic (methods for calculations and suchlike) and I'm starting to work on the actual game loop. What is the \"best\" way to implement a game loop in such a game? Should I use a simple \"while gameActive\" loop that keeps running until gameActive is False, with sections that wait for player input? Or should it be managed through the UI with player actions determining what happens and when? Any help is appreciated. I'm doing it in Python (for now at least) to get my Python skills up a bit, although the language shouldn't matter for this question."} {"_id": 38, "text": "NodeJS setTimeOut How to run callback before delay time exceeded I'm developing a card game server. I want to do this While server process a turn for players, players have 20 seconds to do something. If players send a request to server within 20 secs, timer will stop and the callback will fire. I'm doing like this self.tables table.id .currentTimer setTimeout(function () callback() , 20 1000) How should I run the callback before delay time exceeded ?"} {"_id": 38, "text": "Delta times and frame lag in the game loop Let's say we have a standard gameloop like this, in pseudocode while (true) dt GetDeltaTime() Update(dt) Render() Here Update(dt) either uses a true variable timestep, or it determines how many cycles of a fixed timestep physics loop to execute based on dt. Now say we have the common case where we have mostly constant framerate except for infrequent single frame hiccups, so let's say we have dt values like 1 60, 1 60, 1 60, 1 6, 1 60, 1 60, ... By the time our GetDeltaTime() detects the larger timestep in the fourth frame, we have already rendered and presented the fourth frame! So one frame will already have been rendered with a wrong (too small) timestep no matter what we do. So if we now use the larger dt 1 6 to render the fifth frame, my understanding is that we artificially create a second frame where a wrong timestep is used, this time a too large one. I wonder if this problem is acknowledged anywhere. Wouldn't it be better, say, to use the averaged dt over the previous few frames to combat this? Here are some pictures to illustrate what I mean. I use the example of an object moving along a fixed axis with a constant speed, and using a variable timestepping scheme. The problem is essentially the same with fixed timesteps, though. The plots have time on the x axis, and the object position on the y axis. Let's say the object moving at 1 unit s, and framerate is 1 Hz. This is the ideal situation. Now let's say we have a frame where the time interval is 2 instead of 1. With a classical dt based scheme, we get this So we have one frame where the velocity is perceived too low, and one where it is perceived too high and which corrects for the velocity in the previous frame. What if we instead, say, always use a constant (or very slowly changing) dt? We get this The perceived velocity seems smoother using this approach to me. Of course, the object position is now not the \"true\" one, but I think humans perceive abrupt changes in velocity more clearly than such small positional offsets. Thoughts? UPDATE At least Ogre can do this http ogre.sourcearchive.com documentation 1.6.4.dfsg1 1 classOgre 1 1Root 1f045bf046a75d65e6ddc71f4ebe0b2c.html So I guess I just got downvoted for people not understanding my question, which is rather frustrating."} {"_id": 38, "text": "What are \"frame rate\" and \"fps?\" Can someone give me a detailed explanation about frame rate and fps concepts?"} {"_id": 38, "text": "Varying framerate (FPS) In my game loop, I am using fixed time step for physics and interpolation for rendering as suggested on Gaffer on Games Fix Your Timestep! However, when the framerate is varying between 30 60fps during the game, the game looks jumpy. For example, balls suddenly look accelerated when the frame rate increases from 35 to 45 suddenly. Is there a way to make the game look smooth while framerate is varying? Here is my game loop protected void update(float deltaTime) do some pre stuff deltaTimeAccumulator deltaTime deltaTimeAccumulator is a class member holding the accumulated frame time while(deltaTimeAccumulator gt FIXED TIME STEP) world.step(FIXED TIME STEP, 6, 2) perform physics simulation deltaTimeAccumulator FIXED TIME STEP world.step(deltaTime, 6, 2) destroyBodiesScheduledForRemoval() render(deltaTimeAccumulator FIXED TIME STEP) interpolate according to the remaining time Here is the part related to the interpolation (related inner works of render() method) this.prevPosition this.position get previously simulated position this.position body.getPosition() get currently simulated position interpolate Vector2 renderedPosition new Vector2() if (prevPosition ! null) amp amp !isFloatApproximatelyEquals(this.prevPosition.x, this.position.x) amp amp !isFloatApproximatelyEquals(this.prevPosition.y, this.position.y)) renderedPosition.x this.position.x interpolationAlpha this.prevPosition.x (1 interpolationAlpha) renderedPosition.y this.position.y interpolationAlpha this.prevPosition.y (1 interpolationAlpha) else renderedPosition position Draw the object at renderedPosition"} {"_id": 38, "text": "LUA Keeping track of game state for a digital card trading game I am building a card game. Let's say it's similar to Magic the Gathering, Hearthstone, etc. The problem I am trying to figure out is how to architect \"auras\" and how much damage each card takes. Right now I have a deck and I store card data as follows. I've made up names for the types of cards that will exist. M.card Minion cards have health and damage M.card 1 .name \"Minion\" M.card 1 .hp 1 M.deck 1 .dmg 1 Super Minions have more health and damage M.card 2 .name \"Super Minion\" M.card 2 .hp 4 M.card 2 .dmg 4 Spell cards have no health and damage. Instead they affect the health and damage of other cards. M.card 3 .name \"Heal\" M.card 3 .details \"This card heals any character for 2 health\" M.card 3 .healthboost 2 M.card 4 .name \"Damage Boost\" M.card 4 .details \"This card gives 1 damage to any other card for 1 turn\" M.card 4 .dmgboost 1 Super damage boost gives more damage boost to other cards M.card 5 .name \"Super Damage Boost\" M.card 5 .details \"This card gives 3 damage to any other card permanently\" M.card 5 .dmgboost 3 So when one card attacks another card, I need to keep track of the damage taken by both cards. I don't want to change the base stats of each card so I need to keep track of adjustments. I could do something like this Super Minion takes 3 damage M.card 2 .newHp 1 or M.card 2 .adjHp 3 Not sure which is better. During the battle I need to keep track of which auras are played. So for example if the Damage boost card is played. I need to give another card 1 damage for just one turn. Let's say that I am keep track of each turn number starting from 1. Should I do something like this M.aura 1 4 ( aura 1 is card 4) M.aura 1 .target 2 (this aura is applied to card 2) M.aura 1 .expires 5 (this aura expires on turn 5) M.aura 2 3 ( second active aura is heal, card 3 ) M.aura 2 .target 2 M.aura 2 .expires 0 this is a one time aura. So I need to apply it to card 2 and then immediately expire it so it never activates again. Then on every new turn I loop through all the auras and make sure they are still active before a fight begins? Just wondering architecturally what is the best way to keep track of Damage that characters have taken and spells that are active that are giving characters special abilities."} {"_id": 38, "text": "Do game programming just let all the objects in the program to interact with themselves and what about preventing infinite loop? Does game programming use the method of 1) using time as the main controller to let objects interact with each other, so each step, let 1 object send messages to N objects, and the second object to any number of objects, and 3rd, 4th, until all objects done, and that's it, and display the results on screen (or think of it as just a loop that always repeat, with each iteration considered \"a tick in time\") (so object 1 call object 2's method, and object 2 cannot call other object's method immediately? otherwise, there can be infinite loop like (2) below. but how do you implement \"cannot call other objects until next time?\" ) Or, 2) let the objects freely call other objects' methods (send messages to them), with no \"Time\" concept like the above Are they both feasible solutions? But what if in (2), you have stones in a circular tube, and stone 1 pushes stone 2, and 2 pushes 3, and so forth, until stone N pushes stone 1 again, then the program will go into infinite loop and not able to do anything else (say if the program is a single process, single thread)"} {"_id": 38, "text": "Pro's Con's of separating game logic and render threads Originally, I have thought that it is good practice to separate my game logic (updating) from my rendering thread. In this threading model, the rendering thread has no limitation on frame rate and simply draws whatever information is currently made available by the updating thread. On the other hand, the updating thread is monitored, and has a capped frame rate. I'm led to believe this is BAD and will lead to many coding struggles down the road... So, I'm wondering what are the POTENTIAL benefits for separating updating from rendering? Likewise, what are the POTENTIAL benefits gained when keeping the updating and rendering in the same thread? What are the losses for each method?"} {"_id": 38, "text": "Multiple pipelined game loops I am considering using the following game engine design pattern, but I am unsure if it's a good idea or not Each major task (drawing, physics, logic, networking, disk I O) will have its own isolated thread or subprocess Each of these threads can be put to sleep if it is running too quickly, so as to not consume an excess of CPU resources Threads can only talk to each other through some well defined interface to avoid messy, buggy, thread unsafe conditions from occurring This approach enables parallelism and scalability, but causes a thread safety problem what if one thread is accessing data that another thread is currently processing? We could introduce fine grained locking, but it still can't be guaranteed that the collective states of all of a thread's data objects are coherent. To solve this, collections of objects are maintained inside state objects, and state objects are double buffered. The intent of this is to ensure that other threads only see a valid, coherent set of data. If one thread happens to be processing data that another thread wants to read, then the other thread reads from a buffered state, which is guaranteed not to be written to. However, buffering these states introduces a delay where one thread sees old data from the last cycle of the other thread. Another problem might occur when a reading thread has a slower \"tick rate\" than a writing thread the writing thread may have flipped the state buffer multiple times, while the reading thread is still processing one \"tick\" using the same state. However this can be solved using OO references. Pipelining should be achievable using this approach, because the draw thread could be drawing information that entered the pipeline 30 milliseconds ago, while more information is being processed Ultimately, what I'd like to see is completely decoupled processing for all of the tasks in a game, implemented in a way that helps leverage multi core environments, and maybe leaves some future expansion room for scaling the server side of things amongst multiple machines. I am aware that this is probably overkill for most purposes ) What are the criticisms or pitfalls of this approach? Is this the \"right\" way to do things? Am I thinking about this backwards?"} {"_id": 39, "text": "Tilemap Collision Generation Tracing Polygons with Slopes I've been using Godot for my game, but it has a unfortunate quirks with tilemap collision where physics objects can bounce weirdly near tile seams and kinematic bodies can often get stuck in seams as well. For early alpha work, I've been able to get around this by not using tilemap collision and then tracing the contours by hand... Well this isn't going to scale well to 200 rooms (or whatever I end up having) and could easily lead to mismatched collision data, so I've decided that this process needs to be automated. Tilemaps have a few different tile types fully solid, diagonal slopes, and 2 1 slopes. My first attempt matched each of these types to a half tile size, marking each vertex as solid or not solid, and then combining all the vertices (with their overlap) into a single grid of vertices. I could then use all of these together by marching along the perimeter and probing ahead to detect corners. Turns out this works well for convex corners but has serious issues in concave corners, plus there isn't enough data to detect slopes properly, so it often resulted in extra slopey parts or cutting into slopes just slightly. From there I decided to add some extra information on the vertex grid, such as whether a vertex is a slope edge and doing clever things surrounding the properties of how it overlaps, but it's quickly blowing up into a lot of specific cases. I spent much of today thinking about adding vertex normals to each tile definition, but I realized it wasn't going to work without adding a bunch of different tile solidity types. Are there better approaches than what I'm thinking that don't involve brittle lossy intermediate representations or ridiculous amounts of special cases?"} {"_id": 39, "text": "How to calculate the magnitude of the drag in Corona sdk? I'm making a game on Corona that launches a ball. The force is based on the magnitude of the drag the larger is the drag the higher is the force. I'm having some trouble to do this, because I can't calculate the magnitude of the drag. I tried a simple (finalX initialX) but that's not a good idea. local function onTouch(event) if \"began\" event.phase then end if \"ended\" event.phase then local finalX event.x local finalY event.y forceX event.x event.xStart forceY event.y event.yStart print(forceX, forceY) end end local function gameComponents() local crate display.newImageRect( \"images sonic.png\", 90, 90 ) crate.x, crate.y 60, 360 crate.rotation 0 physics.addBody( crate, \"static\", friction 0.3 ) Runtime addEventListener( \"touch\", onTouch ) return crate end local Game Game.new gameComponents return Game"} {"_id": 39, "text": "Calculating angle a segment forms with a ray I am given a point C and a ray r starting there. I know the coordinates (xc, yc) of the point C and the angle theta the ray r forms with the horizontal, theta in ( pi, pi . I am also given another point P of which I know the coordinates (xp, yp) how do I calculate the angle alpha that the segment CP forms with the ray r, alpha in ( pi, pi ? Some examples follow I can use the the atan2 function."} {"_id": 39, "text": "Getting the bounding box of a sphere I have a sphere with values center,radius and I need to convert the sphere to a bounding box with values min,max. How do I convert a sphere into a bounding box?"} {"_id": 39, "text": "Find projecting triangle for UV mapping in RuneScape model format I am using an old Runescape model format, also used by Thief and Quake. In this format, instead of specifying UV coordinates for each vertex ABC, we specify a second trio of vertices PMN. Those vertices are then used to project UV texture coordinates onto ABC. Some previous Q amp A explains this projection algorithm and how to reverse it. I have a mesh with UVs that I want to save in this format. To do that, I want to find a trio of vertices PMN for each triangle ABC that reproduce the correct UVs. These PMN vertices are chosen from the collection of vertices already in my mesh. I could search every possible ordered triangle in my mesh, but that scales as O(n 3) and would be impractical for meshes with high vertex counts. How can I more efficiently find a PMN triangle that produces my desired UV coordinates on each triangle ABC?"} {"_id": 39, "text": "How to calculate the magnitude of the drag in Corona sdk? I'm making a game on Corona that launches a ball. The force is based on the magnitude of the drag the larger is the drag the higher is the force. I'm having some trouble to do this, because I can't calculate the magnitude of the drag. I tried a simple (finalX initialX) but that's not a good idea. local function onTouch(event) if \"began\" event.phase then end if \"ended\" event.phase then local finalX event.x local finalY event.y forceX event.x event.xStart forceY event.y event.yStart print(forceX, forceY) end end local function gameComponents() local crate display.newImageRect( \"images sonic.png\", 90, 90 ) crate.x, crate.y 60, 360 crate.rotation 0 physics.addBody( crate, \"static\", friction 0.3 ) Runtime addEventListener( \"touch\", onTouch ) return crate end local Game Game.new gameComponents return Game"} {"_id": 39, "text": "How can I determine the first visible tile in an isometric perspective? I am trying to render the visible portion of a diamond shaped isometric map. The \"world\" coordinate system is a 2D Cartesian system, with the coordinates increasing diagonally (in terms of the view coordinate system) along the axes. The \"view\" coordinates are simply mouse offsets relative to the upper left corner of the view. My rendering algorithm works by drawing diagonal spans, starting from the upper right corner of the view and moving diagonally to the right and down, advancing to the next row when it reaches the right view edge. When the rendering loop reaches the lower left corner, it stops. There are functions to convert a point from view coordinates to world coordinates and then to map coordinates. Everything works when rendering from tile 0,0, but as the view scrolls around the rendering needs to start from a different tile. I can't figure out how to determine which tile is closest to the upper right corner. At the moment I am simply converting the coordinates of the upper right corner to map coordinates. This works as long as the view origin (upper right corner) is inside the world, but when approaching the edges of the map the starting tile coordinate obviously become invalid. I guess this boils down to asking \"how can I find the intersection between the world X axis and the view X axis?\""} {"_id": 39, "text": "How can I tell whether an object is moving CW or CCW around a connected path? Lets say we have a jagged shape And two creatures moving along it's outline. Then we smooth the shape completely by pulling the corners out. We get this It is easy to see now that Orange is moving CW and green CCW. How can I tell in which direction they are moving without smoothing out the shape? New image"} {"_id": 39, "text": "Finding the normals of an oriented bounding box? Here is my problem. I'm working on the physics for my 2D game. All objects are oriented bounding boxes (OBB) based on the separate axis theorem. In order to do collision resolution, I need to be able to get an object out out of the object it is penetrating. To do this I need to find the normal of the face(s) that the other OBB is touching. Example The small red OBB is a car lets say, and the big OBB is a static building. I need to determine the unit vector that is the normal of the building edge(s) the car is penetrating to get the car out of there. Here are my questions How do I determine which edges the car is penetrating. I know how to determine the normal of an edge, but how do I know if I need ( dy, dx) or (dy, dx)? In the case I'm demonstrating the car is penetrating 2 edges, which edge(s) do I use to get it out? Answers or help with any or all of these is greatly appreciated. Thank you"} {"_id": 39, "text": "which quarter of a triangle the point is in I've got a world made out of squares. The square are devided in four triangles like this The corners have their heights stored in a 2D array and the center height is the average of the corners. To calculate the players Y coordinate I have to know in which triangle he is standing on. How can you calculate in which quarter the player is by the X and Y coordinates? EDIT My algorithm bool h1 false, h2 false if(posZ lt posX posZ) something weird going on here h1 true if(posX lt posZ posX) and here h2 true if(h1 amp amp h2) triangle 0 if(h1 amp amp !h2) triangle 1 if(!h1 amp amp !h2) triangle 2 if(!h1 amp amp h2) triangle 3 This algorithm tries to find in which triangle you are. There is something wrong in that math."} {"_id": 39, "text": "How do I make a low pass filter (average of readings over time) for compass? I'm making a prototype for android that pulls compass data from the phone. I want to stabilize it so it is less jerky, by taking the average of the last couple of readings. I have done this for accelerometer readings with great success, but adding every measurement to a queue and then collapsing it and dividing it by the queue size ( calculating the average) but for angles this is different. If my measurements are for example 350, 359, 360 I could calculate the average as 356.3 But if my measurements are 350 359, 1 Then my average is 236 which is a radically different angle. Is there any way you guys can think of I could deal with this?"} {"_id": 39, "text": "Intersect of vector and triangle side I'm trying to create a triangular touch surface for iOS where the user can drag around a point inside this triangle. Using information from this page, it is easy to figure out if the dragged point is inside or outside the triangle. However, I want to clip the point to the triangle edges if the user drags outside the triangle. This is easy for side AB and side AC, because I just have to set vectors u or v to zero respectively if the user's finger drags outside of these edges. However, I'm not sure how to find point p, on side BC. I need to find this point of intersection if the user drags their finger outside of edge BC."} {"_id": 39, "text": "How can I find the reflection of a point in a perpendicular line? From the image below I know the positions A and B. How can I find positions C and D and the reflection (Er) of an object E in the line CD? I saw the solution in How can I reflect a point about a line in Unity? but I don't understand it enough to apply it in my case. Please note that I'm trying to achieve this in 2D."} {"_id": 39, "text": "How to know if two surface are in the same direction? In my code I creat a Mesh that are composed by multiple tile. those tile can have edge that are shared, and I need to know if the normal of the tile that have shared edge have the same direction, because I calculat the normal of the edge to smooth the light. before I used the Vector.Dot() , but I've sometimes two tile that have a curve that make impossible to use this function as you can see in the 4th image. and the only information that i have in the calcul is the 2 normal of the tile. img 1 diferent direction img 2 diferent direction img 3 same direction img 4 same direction img 5 same direction"} {"_id": 39, "text": "Segment Cylinder intersection What is the complete code (C , pseudo, does not matter) for calculating the resulting segment (or its absence) for the intersection of asegment and a cylinder? The segment is defined by Vector3(x,y,z) as Start andVector3(x,y,z) as End. The cylinder is defined by the same parameters plus a value for Radius."} {"_id": 39, "text": "Circles within circle (PUBG safe zone) I'm attempting to do something that resembles the safe zone in PUBG (PLAYERUNKNOWN'S BATTLEGROUNDS), a circular area on the map that shrinks over time. On map screen draw circle at rand X Y, 300 pixels wide After say 5 minutes, I want to edit the X, Y and WIDTH of the circle so the new, smaller circle sits at a random position inside the old one."} {"_id": 39, "text": "Calculating the center of a turning circle I'm trying to understand how to calculate the midpoint of a turning circle. In the attached picture, my unit is at location U. I want to compute the trajectory of the unit as it turns toward the starred location. I understand that to achieve this I need to know the location of point P, whose coordinates are (a,b). I also understand that I can do this using some simple trig a x cos(theta) r b y sin(theta) r My problem is that I do not know the value of the angle Theta which sits between the sides of the right triangle named \"R\" and \"X A\". All I know is The radius of the turning circle. The orientation of the unit. How can I solve this problem and others like it more generally?"} {"_id": 39, "text": "Calculating approximations of contact between two meshes I'm looking for ways to calculate the degree of contact between two objects in a scene. I was thinking that calculating the hausdorff distance would be a useful approximation if it is then normalized somehow using the surface area volume of the objects. Does anyone have any experience calculating this in Unity? Or have any suggestions for other ways to approximate this? Edit For some context, I'm working on a project which involves looking at the relationship between geometric properties and relations of objects, and what language words people use to describe objects and I am using scenes in unity to test this. The notion of 'contact' appears to be an important one and it would be useful to be able to quantify the amount of contact between two objects in a scene"} {"_id": 39, "text": "How to access Maya Bonus Tools 2012 in Maya 2014 I have been trying to use the paint geometry tool for Maya 2014 but it isnt showing up. I downloaded Bonus Tools 2012 and installed it. Where can I find this tool in Maya 2014?"} {"_id": 39, "text": "Getting the bounding box of a sphere I have a sphere with values center,radius and I need to convert the sphere to a bounding box with values min,max. How do I convert a sphere into a bounding box?"} {"_id": 39, "text": "Move object forward according to rotation How do I make an object (like a bullet) go forward according to its rotation in vanilla nodejs (my game server language)? For example, if an object's rotation is 0 degrees, then it goes straight up."} {"_id": 39, "text": "Moving and shrinking circle to a circle inside of it (PUBG like zone) I am trying to create a battle royale circle gamemode within Arma3 that would work like in PUBG. For anyone who doesn't know how it looks like Red circle should smoothly shrink into the blue one (that means sides that close to each other should move very slowly by adjusting speed of the red circle center) Global variables Center (getMarkerPos quot marker start quot ) eg. 1000, 1000 ClosingSpeed 0.5 CurrentRadius 1000 EndingRadius 250 Offset 1 Code for generating new circle Determines maximum radius of a new circle private maxRadius CurrentRadius 0.7 Generates radius of the new circle private randomRadius maxRadius 0.6, maxRadius call BIS fnc randomNum Generates new circle center private randomCenter CurrentRadius 0.1, (CurrentRadius randomRadius) call BIS fnc randomNum Randomizes position of the new circle within the old one FinalCenter Center getPos randomCenter, random 360 EndingRadius randomRadius ClosingSpeed ClosingSpeed 2 This number should be somehow calculated to make the closing circle animation work properly Offset 0.75 Shrinking code, executed every 100 ms Decreases radius CurrentRadius CurrentRadius ClosingSpeed Gets the angle between two center points in degrees private angle ((FinalCenter select 1) (Center select 1)) atan2 ((FinalCenter select 0) (Center select 0)) if (CurrentRadius gt EndingRadius) then This sets new position of the circle Center set 0, (Center select 0) ((Offset ClosingSpeed) cos ( angle)) Center set 1, (Center select 1) ((Offset ClosingSpeed) sin ( angle)) Without the correct Offset it shrinks like this center points (red circle center was moving at a wrong velocity)"} {"_id": 39, "text": "Easy way to project point onto triangle (or plane) I have a mesh of triangles (navigation mesh), and a point in 3d space. This point should be \"over\" one of the triangles all the times. I'm trying to determine which triangle is the one the point is \"over\", but I can't quite figure it out. I have found a way to tell if the point is in the triangle using one of the techniques described here, but I can't quite figure out how to project the point on the triangle (or the plane the triangle is in, for that matter). I've been looking online but I can't find anything helpful. Does anyone know how to project a point onto a triangle (or plane)? Also, if someone knows of a better way to test which triangle is the one the point is over, it would be appreciated."} {"_id": 39, "text": "Tilemap Collision Generation Tracing Polygons with Slopes I've been using Godot for my game, but it has a unfortunate quirks with tilemap collision where physics objects can bounce weirdly near tile seams and kinematic bodies can often get stuck in seams as well. For early alpha work, I've been able to get around this by not using tilemap collision and then tracing the contours by hand... Well this isn't going to scale well to 200 rooms (or whatever I end up having) and could easily lead to mismatched collision data, so I've decided that this process needs to be automated. Tilemaps have a few different tile types fully solid, diagonal slopes, and 2 1 slopes. My first attempt matched each of these types to a half tile size, marking each vertex as solid or not solid, and then combining all the vertices (with their overlap) into a single grid of vertices. I could then use all of these together by marching along the perimeter and probing ahead to detect corners. Turns out this works well for convex corners but has serious issues in concave corners, plus there isn't enough data to detect slopes properly, so it often resulted in extra slopey parts or cutting into slopes just slightly. From there I decided to add some extra information on the vertex grid, such as whether a vertex is a slope edge and doing clever things surrounding the properties of how it overlaps, but it's quickly blowing up into a lot of specific cases. I spent much of today thinking about adding vertex normals to each tile definition, but I realized it wasn't going to work without adding a bunch of different tile solidity types. Are there better approaches than what I'm thinking that don't involve brittle lossy intermediate representations or ridiculous amounts of special cases?"} {"_id": 39, "text": "Calculating approximations of contact between two meshes I'm looking for ways to calculate the degree of contact between two objects in a scene. I was thinking that calculating the hausdorff distance would be a useful approximation if it is then normalized somehow using the surface area volume of the objects. Does anyone have any experience calculating this in Unity? Or have any suggestions for other ways to approximate this? Edit For some context, I'm working on a project which involves looking at the relationship between geometric properties and relations of objects, and what language words people use to describe objects and I am using scenes in unity to test this. The notion of 'contact' appears to be an important one and it would be useful to be able to quantify the amount of contact between two objects in a scene"} {"_id": 39, "text": "Finding the normals of an oriented bounding box? Here is my problem. I'm working on the physics for my 2D game. All objects are oriented bounding boxes (OBB) based on the separate axis theorem. In order to do collision resolution, I need to be able to get an object out out of the object it is penetrating. To do this I need to find the normal of the face(s) that the other OBB is touching. Example The small red OBB is a car lets say, and the big OBB is a static building. I need to determine the unit vector that is the normal of the building edge(s) the car is penetrating to get the car out of there. Here are my questions How do I determine which edges the car is penetrating. I know how to determine the normal of an edge, but how do I know if I need ( dy, dx) or (dy, dx)? In the case I'm demonstrating the car is penetrating 2 edges, which edge(s) do I use to get it out? Answers or help with any or all of these is greatly appreciated. Thank you"} {"_id": 39, "text": "Calculating surface normal numerically Say I have a 2D surface defined with the use of bitmap. I want to use this bitmap for collision detection (white color is where object can move freely, with black I mark the walls). How can I numerically calculate the surface normal vector at given point? For example, in the attached picture, how can I calculate the surface normal vector for the red point?"} {"_id": 39, "text": "Rasterizing euclidean planes I'd like to visualize a BSP tree. To do this, I need to project an arbitrary euclidean plane onto a projection plane. I was thinking about calculating the intersections of the plane with the viewing frustum (in world space), then triangulating the resulting quadrangle and projecting the 2 triangles. Is there a better way? For example, I thought about transforming the plane into the viewing space first, creating an ONB (from the transformed plane normal). Then I would simply stretch the quadrangle, until it is outside of the frustum and transform the quadrangle back into world space and send it into the rendering queue. How should I got about shading the plane approximation (quadrangle)?"} {"_id": 39, "text": "Get triangles after subdivision I was able to do subdivision on a triangle mesh with midpoints but then I get polygons with too many faces. How do I convert to triangles after? Similar to this picture"} {"_id": 39, "text": "How to avoid destroying information when scaling I'm in the progress of making a simple 3D editor, just for developing skills on 3d graphics. After implementing some basic tools, I realize that scaling isn't working as I expected. For example, when you scale down a model to a flat plane along some axis, how is it possible to restore that model when you scale up again on that axis? Every vertex has been crunched to the same position, so they will all be scaling in the same way, so the model's vertex layout will be lost. I assume that I need some metadata or quot shadow copy quot of the model, but I'm not sure. How can I solve this problem in my editor?"} {"_id": 39, "text": "ray polygon intersection I am looking for an elegant way to do ray and polygon intersections in 2d. I don't care about languages. Now what I'm doing is taking a line that lies on the ray (with a screen length) and testing line to line intersections between this derived ray and all lines formed by each consecutive vertices in the polygon. This, for now, is good even if I don't know which parts of the ray are inside or outside the polygon (in cases it is concave one). But for now I don't need this information, even if a general approach could maybe give it. I don't care about self intersection polygons. Any advice? Maybe triangulating the polygons could be an idea?"} {"_id": 39, "text": "Procedural Geometry Generation I have recently been looking into SceneKit for OS X and noticed that there are several factory methods to create geometric shapes such as Box, Capsule, Cone, Cylinder, Plane, Pyramid, Sphere, Torus and Tube. I am interested in adding such primitive shapes to my renderer but am struggling to find any reasonable source from which I can gather an understanding of procedural generation. There are several resources which detail the theory, but lack the appropriate source code to back it up. SceneKit provides factory methods which allow for dynamically setting the attributes of such shapes. In the case of the Box, you can provide integer values for the number of width, height and depth segments which each face should be divided into. I understand the theory but lack the knowledge to begin subdividing geometry faces to achieve the desired effect. The vertices for each shape are most likely quite easy to generate in simple loops. What stumps me is knowing how to create the faces, or rather the appropriate texture coordinates for each face. Normals can be calculated per face so I'm fairly confident I could achieve what I want, it's just knowing where to start. Can anyone provide any details on procedural geometry? What I really need is some source code to glean some information from. I have searched high and low for tutorials but have so far come up with only a few reasonable sites or blogs. Any good books, tutorials, blogs or research papers would be appreciated. Edit based on comments I should have clarified that I know how to create vertices for basic shapes, most of these can probably be achieved by simple loops. What I don't comprehend is how to create faces from the generated array of vertices. How do I create a triangle strip, or triangles, from a seemingly unordered array of vertices? I assume that once I get past this point, I can create the normals from each face. Whilst I haven't delved into this yet, I have seen a lot of references to this and am sure it will be easy enough to implement. Ideally, i'd like to be able to generate geometry from a given set of properties such as the way that SceneKit provides. Given SceneKit has done it, and you can do similar things in Blender and Maya etc, I assume i'm not trying to implement the impossible. The final aspect would be applying textures. Again, this isn't something I have implemented but have read up on and am aware of the requirements. The main problem here is that I know what I want to achieve but am struggling to decipher how to implement for the aforementioned primitives. I was hopeful that I would be able to find some semblance of knowledge by way of source code but I really haven't come across anything suitable so far."} {"_id": 39, "text": "Finding the position of a point inside a triangle, based on the position of a point in another triangle (barycentric coordinates in Godot) I'm trying to translate a UV coordinate into a world coordinate. (this is not in a shader, it's in GDScript in Godot, to bake out a texture based on some raycasts). So I find out which triangle in the UV map the coordinate is in and then I find the corresponding triangle in the mesh and get it's world position, that's all good. But then I can't figure out how to translate the points relative position inside the UV triangle to the mesh triangle. I've been trying to use the distance from the point to each of the triangle points as weights to how much of each of the mesh points I should use to find the point I'm looking for, but having no luck. Any help would be much appreciated. Not sure how best to illustrate this. But imagine you had a triangle where you knew the corner points a, b, and c, and a position inside it p. And you had another triangle where you knew the corner points A, B and C, how would you find a point that was relative in the same as p is to abc in triangle ABC. EDIT I added an answer based on the comments from DMGregory"} {"_id": 39, "text": "which quarter of a triangle the point is in I've got a world made out of squares. The square are devided in four triangles like this The corners have their heights stored in a 2D array and the center height is the average of the corners. To calculate the players Y coordinate I have to know in which triangle he is standing on. How can you calculate in which quarter the player is by the X and Y coordinates? EDIT My algorithm bool h1 false, h2 false if(posZ lt posX posZ) something weird going on here h1 true if(posX lt posZ posX) and here h2 true if(h1 amp amp h2) triangle 0 if(h1 amp amp !h2) triangle 1 if(!h1 amp amp !h2) triangle 2 if(!h1 amp amp h2) triangle 3 This algorithm tries to find in which triangle you are. There is something wrong in that math."} {"_id": 39, "text": "How can you tell if you are a large player on a large map or a small player on a small map? If everything is scaled by a constant factor, can you tell that the world is smaller or larger? I think you could look down at the ground and see that it's \"closer\". But how do you know what should be the correct distance? What visual clues give it away? Edit The player controller has an FPS camera!"} {"_id": 39, "text": "Is there a 3D equivalent of hex tile maps? Probably the biggest advantage of a hex based versus square based map tiling is that the center of each hex has the same distance to all its neighboring hexes. Is there a similar shape that tiles this way in 3D, and an engine that supports such a model?"} {"_id": 39, "text": "What shapes interlock solidly like cubes? What basic geometric shapes, besides cubes, interlock \"minecraft\" style like cubes? A small edit to make question more suited to Game Dev I am experimenting with game dynamics to create geometric solids interlock seamlessly on their faces much the way the cubes do in minecraft. The objective is to create an interlock system that is also memory efficient consistent enough to maintain interlock over the course of many connections without deviating from the main grid."} {"_id": 39, "text": "How can I convert my list of vertices and indices to a list of triangles? I have a full 3D collision mesh that is represented by a list of vertices and another list of indices. I need to convert the list of vertices and the list of indices into a set of triangles. First I tried to group every three vertices from the vertex list into a triangle, so vertices 0 2 were triangle 0, vertices 3 5 were triangle 1, etc. But that method did not produce the same triangles I see on the original mesh. Then I remembered the indices list, but I didn't know how to use them. So I came here to ask how can I use the indices list to make my list of triangles?"} {"_id": 39, "text": "Puzzle game clipping of non convex polygons on the figures I have an original figure in the SVG file. I need to break it randomly on parts, an example of which is specified below I have an idea, to use for partitioning Voronoi diagram (Fortune's algorithm). Can I then change the line of intersection of figures to give them a curvature? Can be obtained to identify each shape as a path? To create a game I'll be using cocos2d x."} {"_id": 39, "text": "Finding the normals of an oriented bounding box? Here is my problem. I'm working on the physics for my 2D game. All objects are oriented bounding boxes (OBB) based on the separate axis theorem. In order to do collision resolution, I need to be able to get an object out out of the object it is penetrating. To do this I need to find the normal of the face(s) that the other OBB is touching. Example The small red OBB is a car lets say, and the big OBB is a static building. I need to determine the unit vector that is the normal of the building edge(s) the car is penetrating to get the car out of there. Here are my questions How do I determine which edges the car is penetrating. I know how to determine the normal of an edge, but how do I know if I need ( dy, dx) or (dy, dx)? In the case I'm demonstrating the car is penetrating 2 edges, which edge(s) do I use to get it out? Answers or help with any or all of these is greatly appreciated. Thank you"} {"_id": 39, "text": "Circles within circle (PUBG safe zone) I'm attempting to do something that resembles the safe zone in PUBG (PLAYERUNKNOWN'S BATTLEGROUNDS), a circular area on the map that shrinks over time. On map screen draw circle at rand X Y, 300 pixels wide After say 5 minutes, I want to edit the X, Y and WIDTH of the circle so the new, smaller circle sits at a random position inside the old one."} {"_id": 39, "text": "What shapes interlock solidly like cubes? What basic geometric shapes, besides cubes, interlock \"minecraft\" style like cubes? A small edit to make question more suited to Game Dev I am experimenting with game dynamics to create geometric solids interlock seamlessly on their faces much the way the cubes do in minecraft. The objective is to create an interlock system that is also memory efficient consistent enough to maintain interlock over the course of many connections without deviating from the main grid."} {"_id": 39, "text": "How can you tell if you are a large player on a large map or a small player on a small map? If everything is scaled by a constant factor, can you tell that the world is smaller or larger? I think you could look down at the ground and see that it's \"closer\". But how do you know what should be the correct distance? What visual clues give it away? Edit The player controller has an FPS camera!"} {"_id": 39, "text": "Why is the depth test not done on geometry before rasterization? It seems the only time depth is used to discard data is during rasterization, i.e. at the fragment level. In the geometry stage, I've only see culling and clipping of vertices. Is it not possible to determine whether if a triangle is behind another triangle using just vertex data (depth?) and discard if so? Wouldn't this save all the work later in scan conversion?"} {"_id": 39, "text": "Calculating angle a segment forms with a ray I am given a point C and a ray r starting there. I know the coordinates (xc, yc) of the point C and the angle theta the ray r forms with the horizontal, theta in ( pi, pi . I am also given another point P of which I know the coordinates (xp, yp) how do I calculate the angle alpha that the segment CP forms with the ray r, alpha in ( pi, pi ? Some examples follow I can use the the atan2 function."} {"_id": 39, "text": "How can I randomly pick points on a triangle? Please can help me for a geometry query, I am working out fast mesh to voxel algorithm without using rays and complex maths... What are the maths to sample N points on a triangle randomly? If you can sample randomly i think it means you know the same equation that can distribute points on a triangle at same spacing. I found some info here but it's too difficult to understand https math.stackexchange.com questions 18686 uniform random point in triangle http mathworld.wolfram.com TrianglePointPicking.html The reason is to sample N points on every triangle and round each into a voxel space and send the rounded position of every sample as a true value to a boolean spacial voxel array of X,Y,Z true false values to represent voxels. Thanks for any info's you may provide!"} {"_id": 39, "text": "Puzzle game clipping of non convex polygons on the figures I have an original figure in the SVG file. I need to break it randomly on parts, an example of which is specified below I have an idea, to use for partitioning Voronoi diagram (Fortune's algorithm). Can I then change the line of intersection of figures to give them a curvature? Can be obtained to identify each shape as a path? To create a game I'll be using cocos2d x."} {"_id": 39, "text": "Push cube outside triangle face I'm creating a 3D game, and I need to know how to push a player (axis aligned box cube) outside a triangle. How can I get get the push direction?"} {"_id": 39, "text": "Intersection points of plane set forming convex hull Mostly looking for a nudge in the right direction here. Given a set of planes (defined as a normal and distance from origin) that form a convex hull, I would like to find the intersection points that form the corners of that hull. More directly, I'm looking for a way to generate a point cloud appropriate to provide to Bullet. Bonus points if someone knows of a way I could give bullet the plane list directly, since I somewhat suspect that's what it's building on the backend anyway."} {"_id": 39, "text": "Testing whether two cubes are touching in space Does anyone have any clean ideas on testing whether two cubes in 3D space touch? By touch I mean, touch at corners or on a face or on an edge. Say that the cubes are axis aligned and there is no nesting of the cubes. So either the cubes touch or they don't. There is no overlap of the cubes at all (except of course possibly an edge or corner point). Everything I have thought of ends up needing a ton of cases. Also numerical stability is a factor. I don't want to just test on all the edges points. I guess I could utilize some sort of epsilon instead of testing whether something 0. The main thing however is minimizing the number of cases to test."} {"_id": 40, "text": "Implementing a Deferred Renderer (Basic Understanding) I am trying to implement a Deferred Renderer in Direct3D11. I am fairly new to this. I already bought a book Practical Rendering amp Computation with Direct3D 11. However, this book doesnt answer many of my questions. The Book just says \"Call one of the Draw Commands to execute the Pipeline\" In the context of a deferred Renderer I would like to know How I can actually render the different GBuffers, merge them and put actual Lighting to my scene. Let's say my GBuffers should represent Diffuse, Specular and Normals. I understand that Vertex Shaders have Constant Buffers that represent my Camera through Matrices. Vertices get Transformed in shaders into ViewSpace. How Do I get my Diffuse Specular Normal information out of that? Do I have to execute the Rendering Pipeline for every GBuffer? Technically do I just need to transform my vertices once in a VS and just execute my different GBuffer PS? The Context Object offers functions like \"OMSetRenderTarget\". The OutputMerger however is the last stage of the Pipeline, not the first... The Book itself just calls \"Present(0,0)\" exactly once and doesnt explain how you actually put things together. Sorry, quite a lot of different questions ("} {"_id": 40, "text": "Independent blending with DXGI FORMAT R16G16 SINT I'm implementing direct volume rendering engine with volume bricking, but I'm stuck with this problem For each volume brick I render to color render target CRT (for visualization) and to data render target DRT (used for isosurface object picking). DRT is of the DXGI FORMAT R16G16 SINT format. All works fine and smooth except wrong handling of blending DRTs of multiple volume bricks together. Closer brick always occludes further brick DRT. Here are the pictures to illustrate my point (if the object has proper DRT data it's outlined as you can se in the highlighted area, there are objects parts with no data) Could somebody please give me a tip, how to handle this? Of course I could always render every brick to separate DRT and write own shader to merge them properly, but isn't there a way of only properly setting blending modes? (now I'm rendering with blending disabled for DRTs) Thanks"} {"_id": 40, "text": "How to blend multiple normal maps? I want to achieve a distortion effect which distorts the full screen. For that I spawn a couple of images with normal maps. I render their normal map part on some camera facing quads onto a rendertarget which is cleared with the color (127,127,255,255). This color means that there is no distortion whatsoever. Then I want to render some images like this one onto it If I draw one somewhere on the screen, then it looks correct because it blends in seamlessly with the background (which is the same color that appears on the edges of this image). If I draw another one on top of it then it will no longer be a seamless transition. For this I created a blendstate in directX 11 that keeps the maximum of two colors, so it is now a seamless transition, but this way, the colors lower than 127 (0.5f normalized) will not contribute. I am not making a simulation and the effect looks quite convincing and nice for a game, but in my spare time I am thinking how I could achieve a nicer or a more correct effect with a blend state, maybe averaging the colors somehow? I I did it with a shader, I would add the colors and then I would normalize them, but I need to combine arbitrary number of images onto a rendertarget. This is my blend state now which blends them seamlessly but not correctly D3D11 BLEND DESC bd bd.RenderTarget 0 .BlendEnable true bd.RenderTarget 0 .SrcBlend D3D11 BLEND SRC ALPHA bd.RenderTarget 0 .DestBlend D3D11 BLEND INV SRC ALPHA bd.RenderTarget 0 .BlendOp D3D11 BLEND OP MAX bd.RenderTarget 0 .SrcBlendAlpha D3D11 BLEND ONE bd.RenderTarget 0 .DestBlendAlpha D3D11 BLEND ZERO bd.RenderTarget 0 .BlendOpAlpha D3D11 BLEND OP MAX bd.RenderTarget 0 .RenderTargetWriteMask 0x0f Is there any way of improving upon this? (PS. I considered rendering each one with a separate shader incementally on top of each other but that would consume a lot of render targets which is unacceptable)"} {"_id": 40, "text": "How can I prevent other applications from interrupting my game's exclusive fullscreen mode? I am developing a game using D3D 11. When I got a pop up message from a chat client (HipChat), my game's full screen mode is disabled because IDXGISwapChain Present returns DXGI STATUS OCCLUDED. How can I avoid or prevent this? I don't want my game's exclusive full screen access interrupted."} {"_id": 40, "text": "Direct3D11 Depth buffer problem Encountered a strange error when using Direct3D11, feature level 10.0. If the depth buffer texture is created with the format DXGI FORMAT R24G8 TYPELESS, bind flag D3D11 BIND DEPTH STENCIL D3D11 BIND SHADER RESOURCE and the depth stencil view format DXGI FORMAT D24 UNORM S8 UINT, everything is correct. Also, there are no problems when the depth buffer texture format is DXGI FORMAT R32G8X24 TYPELESS and the depth stencil view format is DXGI FORMAT D32 FLOAT S8X24 UINT. However, when the depth buffer format is DXGI FORMAT R32 TYPELESS, and the depth stencil view format is DXGI FORMAT D32 FLOAT, the whole geometry is not rendered at all, only the clear color is visible. I used Visual Studio 2015's Graphics Debugger to check if the geometry is rendered as desired, but during the Output Merger stage the whole geometry is discarded because it failed the depth test. Every Direct3D function call returns no error and the Direct3D debugging output reports no error (only INFO messages about creation destruction of resources). I do not use the stencil functionality at all, and it is disabled. I use a Windows 7 virtual machine as a developer machine and using DXGI FORMAT R32 TYPELESS and DXGI FORMAT D32 FLOAT worked flawlessly before I switched from a Windows 7 host to an Arch Linux host, because the old hard drive started to fail and the operating system was unable to read its own files during boot. After I switched the host operating system, this problem started to occur inside the virtual machine. Is it possible to have a bug somewhere else in my code? Is there a limitation when using DXGI FORMAT D32 FLOAT and sometimes it may not be possible to use DXGI FORMAT D32 FLOAT or the other depth formats on every machine (considering D3D11 feature level 10.0 is available)? Or is this a bug somewhere else, possibly in VMware player or Linux or Bumblebee (Optimus Intel HD 4000 GeForce GTX 650M)?"} {"_id": 40, "text": "IsoSurface Normals Texture Coords Problems(DX11 SharpDX) Hi and thanks for your time! So over the past few days I have been playing with isosurface construction from volume textures, I have it running on the cpu and all is well from a \"just got it working\" stand point eg. surface reconstruction works and I have my really cool voxel mesh drawing. I have based my code(converted to VB.net) on Paul Bourke's work here Polygonising a scalar field and like I said it works well apart from the fact that my normals are wrong and I have these strange fully black on both sides triangles, I think I'm doing my normals wrong but the way they are now is the beast I can get, I tried a few ways to build the normals and this one is the only way I could get smooth normals. Here you can see how my normals are wrong, green should be up, gray dark should be unlit and the hay'ish colour is the lit side. I have tried to flip and invert them but as you can see they are not wrong all the same way. HLSL Normals 1st try float3x3 cotangent frame(float3 N, float3 p, float2 uv) get edge vectors of the pixel triangle float3 dp1 ddx(p) float3 dp2 ddy(p) float2 duv1 ddx(uv) float2 duv2 ddy(uv) solve the linear system float3 dp2perp cross(dp2, N) float3 dp1perp cross(N, dp1) float3 T dp2perp duv1.x dp1perp duv2.x float3 B dp2perp duv1.y dp1perp duv2.y construct a scale invariant frame float invmax sqrt(max(dot(T, T), dot(B, B))) return float3x3(T invmax, B invmax, N) HLSL Normals 2nd try NormalData CalcWS Normal(float2 WS TexCoord, float3 WS Pos) NormalData dout float3 dp1 ddx(WS Pos) float3 dp2 ddy(WS Pos) float2 duv1 ddx(WS TexCoord) float2 duv2 ddy(WS TexCoord) float3x3 M float3x3(dp1, dp2, cross(dp1, dp2)) float2x3 inverseM float2x3(cross(M 1 , M 2 ), cross(M 2 , M 0 )) float3 t mul(float2(duv1.x, duv2.x), inverseM) float3 b mul(float2(duv1.y, duv2.y), inverseM) float3 normal normalize(cross(normalize(b), normalize(t))) dout.Normal normal dout.Tang t dout.BiTang b return dout Heres is how I'm doing it now, takes a vertex and then samples the volume texture VB.net Private Function vGetNormal(fX As Single, fY As Single, fZ As Single, fScale As Single) As Vector3 Dim rfNormal As Vector3 rfNormal.X fSample1(fX fScale, fY, fZ) fSample1(fX fScale, fY, fZ) rfNormal.Y fSample1(fX, fY fScale, fZ) fSample1(fX, fY fScale, fZ) rfNormal.Z fSample1(fX, fY, fZ fScale) fSample1(fX, fY, fZ fScale) Return Vector3.Normalize(rfNormal) End Function Private Function vGetNormal(fX As Single, fY As Single, fZ As Single, fScale As Vector3) As Vector3 Dim rfNormal As Vector3 rfNormal.X fSample1(fX fScale.X, fY, fZ) fSample1(fX fScale.X, fY, fZ) rfNormal.Y fSample1(fX, fY fScale.Y, fZ) fSample1(fX, fY fScale.Y, fZ) rfNormal.Z fSample1(fX, fY, fZ fScale.Z) fSample1(fX, fY, fZ fScale.Z) Return Vector3.Normalize(rfNormal) End Function Volume sampling code VB.net Public Function GetVolumeData( pos As Vector3) As Half Dim x2 As Single Math.Abs(( pos.X CellsPerPatch 32) Mod mWidth) Dim y2 As Single Math.Abs(( pos.Y CellsPerPatch 8) Mod mDepth) Dim z2 As Single Math.Abs(( pos.Z CellsPerPatch 32) Mod mHeight) Return mScalars(CInt(Math.Truncate(x2)) (CInt(Math.Truncate(z2)) mWidth) (CInt(Math.Truncate(y2) mWidth mWidth))) End Function The rest of the isosurface construction code is just a copy convert paste of Paul Bourke's c code. Just to makes sure everyone knows what I'm asking Can anyone tell me what I'm doing wrong? Is it a problem with my normals or the isosurface stuffs or both? All of the above is just so u have some context, I'm happy to post more code if ppl need to see it EDIT Black squares come from having no depth info at that point so my deferred render hates those spots, this is leading back to maybe a problem with the surface reconstruction? But why its only happening in those spots, one would think that it would happen everywhere?"} {"_id": 40, "text": "The Pixel Shader unit expects a Sampler configured for default filtering to be set at Slot 0 ... I don't understand this error. The full output being The Pixel Shader unit expects a Sampler configured for default filtering to be set at Slot 0, but the sampler bound at this slot is configured for comparison filtering. Here is how I create the sampler state. Skybox sampler description D3D11 SAMPLER DESC skyboxSamplerDesc ZeroMemory( amp skyboxSamplerDesc, sizeof(D3D11 SAMPLER DESC)) skyboxSamplerDesc.Filter D3D11 FILTER COMPARISON MIN MAG LINEAR MIP POINT skyboxSamplerDesc.AddressU D3D11 TEXTURE ADDRESS CLAMP skyboxSamplerDesc.AddressV D3D11 TEXTURE ADDRESS CLAMP skyboxSamplerDesc.AddressW D3D11 TEXTURE ADDRESS CLAMP skyboxSamplerDesc.MipLODBias 0.0f skyboxSamplerDesc.MaxAnisotropy 16 skyboxSamplerDesc.ComparisonFunc D3D11 COMPARISON EQUAL skyboxSamplerDesc.MinLOD 0 skyboxSamplerDesc.MaxLOD D3D11 FLOAT32 MAX Create the skybox texture sampler state hr g d3dDevice gt CreateSamplerState( amp skyboxSamplerDesc, amp g SkyboxSamplerState) if (FAILED(hr)) return false The bindings. ID3D11SamplerState samplerStates 2 samplerStates 0 g SkyboxSamplerState samplerStates 1 g PixelDepthSamplerState g d3dDeviceContext gt PSSetSamplers(0, 2, samplerStates) HLSL side. SamplerState sbSamplerState register (s0) Filter MIN MAG LINEAR MIP POINT AddressU CLAMP AddressV CLAMP AddressW CLAMP ComparisonFunc EQUAL"} {"_id": 40, "text": "How to make use of resizable BAR? From what I understand, resizable BAR (aka. Smart Access Memory) makes it possible to access the whole GPU memory from CPU code. But how can a programmer make use of that? Is there an example or code snippet somewhere, that makes use of that feature? Or is that just an automatic that improves the performance of staging resources? I'd also be happy if you can recommend further search terms that I can look up."} {"_id": 40, "text": "Update DXGI swapchain sample count without recreating swapchain in full screen mode I'm implementing the ability to tweak graphics settings in my application at runtime (resolution, refresh rate, v sync, multisampling). It is possible to update the resolution, format and refresh rate using IDXGISwapChain ResizeTarget and IDXGISwapChain ResizeBuffers. However, I cannot find any way to update the swapchain's sampling(count and quality) in the same way. The only option I have is to go to windowed mode using IDXGISwapChain SetFullscreenState, then release the swapchain, recreate the swapchain with a new DXGI SWAP CHAIN DESC, and then go back to fullscreen again. (Didn't mention releasing and recreating back buffer and depth stencil since it is a must do).I am willing to stay at full screen mode before and after the settings are applied."} {"_id": 40, "text": "Game only runs at 60fps in windowed mode with a 120hz monitor? In fullscreen the game will run at 120fps fine, the correct refresh rate for the monitor, but in windowed mode it only runs at 60fps. If I disable VSync then it runs at thounsands of fps so it's not a case of a lack of performance. I've correctly set the refresh rate in the ModeDescription."} {"_id": 40, "text": "Fbx SDK Importer issue (texture uv related) I am using the latest autodesk FBX Importer SDK, but whatever I do, I am unable to get the uvs right. Some parts are textured properly while others are not. I am using Direct3D9 and Direct3D11 (same result in both). Image 360 image https i.gyazo.com 5a2e5f6e127521915508c9c300eb03e5.mp4 The model uses a single texture and a single material shared among 4 meshes. Is there someone who sees immediately what the problem could be? Or is there someone who can replicate the issue for me and figure out what I am missing? FBX Test File http www.4shared.com rar o WG0Crpce Peach64FBX.html My UV reading method int vertexCounter 0 for (int j 0 j lt nbPolygons j ) for (int k 0 k lt 3 k ) int vertexIndex pFbxMesh gt GetPolygonVertex(j, k) Vector2 uv readUV(pFbxMesh, vertexIndex, pFbxMesh gt GetTextureUVIndex(j, k), uv) pVertices vertexIndex .uv.x uv.x pVertices vertexIndex .uv.y 1.0 uv.y vertexCounter void readUV(fbxsdk FbxMesh pFbxMesh, int vertexIndex, int uvIndex, Vector2 amp uv) fbxsdk FbxLayerElementUV pFbxLayerElementUV pFbxMesh gt GetLayer(0) gt GetUVs() if (pFbxLayerElementUV nullptr) return switch (pFbxLayerElementUV gt GetMappingMode()) case FbxLayerElementUV eByControlPoint switch (pFbxLayerElementUV gt GetReferenceMode()) case FbxLayerElementUV eDirect fbxsdk FbxVector2 fbxUv pFbxLayerElementUV gt GetDirectArray().GetAt(vertexIndex) uv.x fbxUv.mData 0 uv.y fbxUv.mData 1 break case FbxLayerElementUV eIndexToDirect int id pFbxLayerElementUV gt GetIndexArray().GetAt(vertexIndex) fbxsdk FbxVector2 fbxUv pFbxLayerElementUV gt GetDirectArray().GetAt(id) uv.x fbxUv.mData 0 uv.y fbxUv.mData 1 break break case FbxLayerElementUV eByPolygonVertex switch (pFbxLayerElementUV gt GetReferenceMode()) Always enters this part for the example model case FbxLayerElementUV eDirect case FbxLayerElementUV eIndexToDirect uv.x pFbxLayerElementUV gt GetDirectArray().GetAt(uvIndex).mData 0 uv.y pFbxLayerElementUV gt GetDirectArray().GetAt(uvIndex).mData 1 break break I am doing V 1.0 uv.y because I am using Direct3D11. NOTE the MappingMode is always eByPolygonVertex and ReferenceMode is always eIndexToDirect Rendering Info Rendered as a Triangle List Uv wrapping mode Wrap (Repeat) Culling None"} {"_id": 40, "text": "Can state setting warnings be ignored? If I am running DirectX 11 in debug mode (D3D11 CREATE DEVICE DEBUG), I am constantly getting these warnings D3D11 WARNING ID3D11DeviceContext OMSetRenderTargets Resource being set to OM DepthStencil is still bound on input! STATE SETTING WARNING 9 DEVICE OMSETRENDERTARGETS HAZARD D3D11 WARNING ID3D11DeviceContext OMSetRenderTargets AndUnorderedAccessViews Forcing PS shader resource slot 6 to NULL. STATE SETTING WARNING 7 DEVICE PSSETSHADERRESOURCES HAZARD It is because I am setting a resource as a render target while it is currently bound to the PS. However, my rendering flow is set up such as it relies on the api to force the resource slot to null, and it works. Is there any reason I should be bothered with these warnings or I can rely on the api to enforce this every time? I only tested on 2 GPU s Intel HD 3000 and Nvidia GT525m."} {"_id": 40, "text": "How can I render a 2D image to my screen using Direct X 11? I am trying to render an image to my window using Direct X but I don't really want a \"3D\" world as such, and I don't really want to set up all the vertex index buffers as I won't need them. I am performing all of my calculations and operations using compute shaders which returns me an image. As the file io is quite a bottleneck, I am looking to just render the image directly to the screen to increase performance. My question is, how would I go about this using Direct X 11? I have looked at some examples already such as rastertek and other questions on SO but they are either over complicating the matter, or they want a solution to font drawing etc. At the moment I am able to produce a blank screen using the following code and the screen size is the size of the image retrieved from the GPU. I am looking to draw this entire image to my back buffer or some render target, and then display it. void Application Draw() float ClearColor 4 0.5f, 0.125f, 0.3f, 1.0f context gt ClearRenderTargetView( pRenderTargetView, ClearColor) compute shader operations, retrieve image data from gpu draw image to back buffer render target then present swapChain gt Present(0, 0) From Why can 39 t I write to my render targets?, I have tried the solution using ID3D11Resource backBufferResource pRenderTargetView gt GetResource( amp backBufferResource) backbuffer render target context gt CopyResource(backBufferResource, gpuResource) This doesn't seem to throw any errors, but it doesn't change the output on the screen. It is mentioned that the back buffer must be the exact same format as the image we're trying to copy to it so this may be the issue. My swap chain desc is as follows DXGI SWAP CHAIN DESC sd ZeroMemory( amp sd, sizeof(sd)) sd.BufferCount 1 sd.BufferDesc.Width WindowWidth sd.BufferDesc.Height WindowHeight sd.BufferDesc.Format DXGI FORMAT R8G8B8A8 UNORM FORMAT DIFFERENT sd.BufferDesc.RefreshRate.Numerator 60 sd.BufferDesc.RefreshRate.Denominator 1 sd.BufferUsage DXGI USAGE RENDER TARGET OUTPUT sd.OutputWindow hWnd sd.SampleDesc.Count 1 sd.SampleDesc.Quality 0 sd.Windowed TRUE and my image format is DXGI FORMAT R32G32B32A32 FLOAT If I try to change the swap chain format it throws a memory access violation."} {"_id": 40, "text": "How do I use com ptr t with RenderTargetView and DepthStencilView? I have successfully used com ptr t with the ID3D11Device and IDXGISwapChain but when applying the same reasoning to the RenderTargetView and DepthStencilView, the function m spD3DImmediateContext gt OMSetRenderTargets(...) sets the m spRenderTargetView smart COM pointer to null! Then, subsequent draw calls fail on ClearRenderTargetView and ClearDepthStencilView. Is it because I am passing the smart pointer incorrectly? HR(m spD3DDevice gt CreateRenderTargetView(pBackBuffer, 0, amp m spRenderTargetView)) ... HR(m spD3DDevice gt CreateTexture2D( amp stDepthStencilDesc, 0, amp m spDepthStencilBuffer)) ... m spD3DImmediateContext gt OMSetRenderTargets(1, amp m spRenderTargetView, m spDepthStencilView) assert(m spRenderTargetView) lt FAIL I think the smart pointer overloads the operator amp so that it returns an Interface (see Extractors in com ptr t class)."} {"_id": 40, "text": "What are the tessellation factors Direct3D11? I don't quite understand the documentation but if I was to tessellate a mesh using 3 control points in Direct3D11 with the \"tri\" domain am I right in thinking that SV TessFactor is how many times to split up each edge and SV InsideTessFactor is how many points inside the triangle to create?"} {"_id": 40, "text": "Can't get Direct3D11 depth buffer to work I can't get the depth buffer to work correctly. I am rendering 2 cubes in a single Draw function, and from one angle it looks great But swing the camera around to view the opposite sides, and I discover it's just Painter's Algorithm. This is my code to setup the depth stencil buffer void Graphics CreateDepthStencilBuffer(ID3D11Texture2D backBuffer) D3D11 TEXTURE2D DESC dsTextureDesc backBuffer gt GetDesc( amp dsTextureDesc) dsTextureDesc.Format DXGI FORMAT D24 UNORM S8 UINT dsTextureDesc.Usage D3D11 USAGE DEFAULT dsTextureDesc.BindFlags D3D11 BIND DEPTH STENCIL dsTextureDesc.MipLevels 1 dsTextureDesc.ArraySize 1 dsTextureDesc.CPUAccessFlags 0 dsTextureDesc.MiscFlags 0 Microsoft WRL ComPtr lt ID3D11Texture2D gt dsBuffer ASSERT SUCCEEDED(g Device gt CreateTexture2D( amp dsTextureDesc, NULL, dsBuffer.ReleaseAndGetAddressOf())) D3D11 DEPTH STENCIL DESC dsDesc dsDesc.DepthEnable true dsDesc.DepthWriteMask D3D11 DEPTH WRITE MASK ALL dsDesc.DepthFunc D3D11 COMPARISON LESS ... snipped stencil properties ... ASSERT SUCCEEDED(g Device gt CreateDepthStencilState( amp dsDesc, g DepthStencilState.GetAddressOf())) g pDevCon gt OMSetDepthStencilState(g DepthStencilState.Get(), 1) D3D11 DEPTH STENCIL VIEW DESC depthStencilViewDesc depthStencilViewDesc.Format dsTextureDesc.Format depthStencilViewDesc.ViewDimension D3D11 DSV DIMENSION TEXTURE2D depthStencilViewDesc.Texture2D.MipSlice 0 ASSERT SUCCEEDED(g Device gt CreateDepthStencilView(dsBuffer.Get(), amp depthStencilViewDesc, g depthStencilView.GetAddressOf())) And I'm calling g pDevCon gt OMSetRenderTargets(1, g renderTargetView.GetAddressOf(), g depthStencilView.Get()) after every Present call. I've been scratching my head for ages wondering what the problem is. Any clues will be much appreciated! Edit I used the graphics debugger, and apparently the output merger is doing its job, as seen in the screenshot below, but that isn't what I am seeing on screen. At the top of the pic is the state of the depth buffer, but I can't make sense of it to determine if it's correct or not."} {"_id": 40, "text": "How can I prevent other applications from interrupting my game's exclusive fullscreen mode? I am developing a game using D3D 11. When I got a pop up message from a chat client (HipChat), my game's full screen mode is disabled because IDXGISwapChain Present returns DXGI STATUS OCCLUDED. How can I avoid or prevent this? I don't want my game's exclusive full screen access interrupted."} {"_id": 40, "text": "Create Render Target View 138 140 need to Bind the back buffer to the render target view DirectX 11 This is the error D3D11 ERROR ID3D11Device CreateRenderTargetView A RenderTargetView cannot be created of a Resource that did not specify the RENDER TARGET BindFlag. STATE CREATION ERROR 138 CREATERENDERTARGETVIEW INVALIDRESOURCE D3D11 ERROR ID3D11Device CreateRenderTargetView Returning E INVALIDARG, meaning invalid parameters were passed. STATE CREATION ERROR 140 CREATERENDERTARGETVIEW INVALIDARG RETURN So as i see here i need to set the BindFlag of the backBuffer to D3D11 BIND RENDER TARGET, but in all the tutorial i saw nobody is doing it, they all create the render target view by using this code hr m swapChain gt GetBuffer(0, uuidof(ID3D11Texture2D), reinterpret cast lt void gt ( amp m backBuffer)) if (FAILED(hr)) MessageBox(0, L\"Failed get buffer\", 0, 0) hr m device gt CreateRenderTargetView(m backBuffer, NULL, amp m renderTargetView) if (FAILED(hr)) MessageBox(0, L\"Failed to create rendertargetview\", 0, 0) And nobody, nowhere is doing as the msdn site says, that the render target view must be created with this specific flag D3D11 BIND RENDER TARGET So I tried doing it by myself. I created a texture2d desc like this for the back buffer D3D11 TEXTURE2D DESC backBufferDescription backBufferDescription.BindFlags D3D11 BIND RENDER TARGET backBufferDescription.ArraySize 1 backBufferDescription.CPUAccessFlags 0 backBufferDescription.Format DXGI FORMAT R8G8B8A8 UNORM backBufferDescription.Height 600 backBufferDescription.Width 800 backBufferDescription.MipLevels 1 backBufferDescription.MiscFlags 0 backBufferDescription.SampleDesc.Quality 0 backBufferDescription.SampleDesc.Count 1 backBufferDescription.Usage D3D11 USAGE DEFAULT m device gt CreateTexture2D( amp backBufferDescription, NULL, amp m backBuffer) if (FAILED(hr)) MessageBox(0, L\"Fallito back buffer desc\", 0, 0) And it doesn't work the same. Help please"} {"_id": 40, "text": "Why isn't my cbuffer updating? I am really frustrated because my cbufer isn't updating. This is my VS cbuffer MatrixBuffer register(b0) float4x4 worldViewProj struct VertexIn float4 Pos POSITION float4 Color COLOR struct PixelIn float4 PosH SV POSITION float4 Color COLOR PixelIn VS (VertexIn vin) PixelIn vout vin.Pos.w 1.0f vout.PosH mul(vin.Pos, worldViewProj) vout.Color vin.Color return vout PixelIn VS1(VertexIn vin) PixelIn vout vin.Pos.w 1.0f vout.PosH vin.Pos vout.Color vin.Color return vout When using VS1 it draws correctly, but when using VS it doesn't draw anything? Here is my CBUFFER update code bool Game UpdateShaders() HRESULT result D3D11 MAPPED SUBRESOURCE mappedResource MatrixBufferType dataPtr worldViewProjM worldM viewM projM worldViewProjM XMMatrixTranspose(worldViewProjM) result md3dDeviceContext gt Map(mMatrixBuffer, 0, D3D11 MAP WRITE DISCARD, 0, amp mappedResource) if (FAILED(result)) MessageBoxW(mMainWnd, L\"FAOE \", 0, 0) return false dataPtr (MatrixBufferType )mappedResource.pData dataPtr gt worldViewProj worldViewProjM md3dDeviceContext gt Unmap(mMatrixBuffer, 0) int NBuffers 0 md3dDeviceContext gt VSSetConstantBuffers(0, 1, amp mMatrixBuffer) md3dDeviceContext gt PSSetConstantBuffers(0, 1, amp mMatrixBuffer) return true Here is my MATRIXBUFFERTYPE struct struct MatrixBufferType XMMATRIX worldViewProj This is called after I clear my depth stencil view and render target view. Does somebody know why my CBUFFER isn't updating? Thanks in advance."} {"_id": 40, "text": "DX11 Handle Device removed I get the DXGI ERROR DEVICE REMOVED error on some machines. According to this (https msdn.microsoft.com en us windows uwp gaming handling device lost scenarios) MSDN article this can happen and it should be handled by your application. I've managed to recreate the device but I'm unsure how to handle all content. It seems I have to create all vertex buffers and textures again, which essentially means I have to reload almost the entire scene. Is this really the correct way?"} {"_id": 40, "text": "Send empty vertex buffer data but keep Vertex Shader Input Structure? lets say i have the following structure defined in a header (for reusage) struct VertexShaderInput float3 Position POSITION float3 Normal NORMAL float2 UV TEXCOORD float4 Color COLOR however, some meshes dont have normals or colors and some passes (such as Depth PrePass) doesn't need Normal or Color. Is there a way to keep the struct definition above in my shaders and simply sending \"zero\" bytes for Normals and Colors?"} {"_id": 40, "text": "How do I specify ARGB format textures in my input declaration? const D3D11 INPUT ELEMENT DESC InputLayoutDesc Basic32 3 \"POSITION\", 0, DXGI FORMAT R32G32B32 FLOAT, 0, 0, D3D11 INPUT PER VERTEX DATA, 0 , \"NORMAL\", 0, DXGI FORMAT R32G32B32 FLOAT, 0, 12, D3D11 INPUT PER VERTEX DATA, 0 , \"TEXCOORD\", 0, DXGI FORMAT R32G32B32A32 FLOAT, 0, 24, D3D11 INPUT PER VERTEX DATA, 0 The TEXCOORD, There is no support for a image that is ARGB. Only DXGI FORMAT R32G32B32A32 FLOAT How can I load ARBG? Or can I convert a ARGB TO A RGBA IMAGE?"} {"_id": 40, "text": "Adding mesh's objects to procedural isosurface terrain Thanks again for reading! So following on from my last question, I have my fully working isosurface terrain and now its time to add my trees and grass and whatever to the world. The old way I was doing it was to cast rays in a grid faceing down over the terrain, I would then read the normal from the ray hit and place things if the normal was lt as value. I would do this at different grid resolutions for each plant tree grass time and offset there x, z and scale by some random value then adding the object to my 2d BV tree because I was only working with height map terrain so I only had one row of bounding volumes for the tree. I can still use the above method but as you know it will only place objects on parts of the terrain that can see the sky. Part of building my new terrain system involved making a real octree so I no that I will use that to store my objects but what is the best way to generate my object positons. From what I have read around I should somehow use the voxels I build but I'm not really sure how I would go about it."} {"_id": 40, "text": "Full screen quad in the HLSL Directx 11 I want to create a full screen Triangle Quad so I can blur the box that is the quad I made. I want to do this in the vertex buffer. I tried this code struct VSQuadOut float4 position SV POSITION float2 uv TEXCOORD outputs a full screen triangle with screen space coordinates input three empty vertices VSQuadOut VSQuad( uint vertexID SV VertexID ) VSQuadOut result result.uv float2((vertexID lt lt 1) amp 2, vertexID amp 2) result.position float4(result.uv float2(2.0f, 2.0f) float2( 1.0f, 1.0f), 0.0f, 1.0f) return result I want something like this Any ideas?"} {"_id": 40, "text": "How do I use com ptr t with RenderTargetView and DepthStencilView? I have successfully used com ptr t with the ID3D11Device and IDXGISwapChain but when applying the same reasoning to the RenderTargetView and DepthStencilView, the function m spD3DImmediateContext gt OMSetRenderTargets(...) sets the m spRenderTargetView smart COM pointer to null! Then, subsequent draw calls fail on ClearRenderTargetView and ClearDepthStencilView. Is it because I am passing the smart pointer incorrectly? HR(m spD3DDevice gt CreateRenderTargetView(pBackBuffer, 0, amp m spRenderTargetView)) ... HR(m spD3DDevice gt CreateTexture2D( amp stDepthStencilDesc, 0, amp m spDepthStencilBuffer)) ... m spD3DImmediateContext gt OMSetRenderTargets(1, amp m spRenderTargetView, m spDepthStencilView) assert(m spRenderTargetView) lt FAIL I think the smart pointer overloads the operator amp so that it returns an Interface (see Extractors in com ptr t class)."} {"_id": 40, "text": "What is the AlphaToCoverage blend state useful for? Alright, just finished most of my early UI stuff and I wanted the windows to have some transparency. So I expanded my application to initialize and bind blend states so that my UI shader could implement alpha blending. I was initially having no luck but I got the blend state configured to achieve my purpose, however the way it is configured doesn't make sense to me so I must be missing something. Here is how I initialize my blend state. bool BlendState StartUp() D11DeviceManager pDeviceManager D11DeviceManager GetSingleton() D3D11 BLEND DESC desc desc.AlphaToCoverageEnable false desc.IndependentBlendEnable false desc.RenderTarget 0 .BlendEnable true desc.RenderTarget 0 .SrcBlend D3D11 BLEND SRC COLOR desc.RenderTarget 0 .DestBlend D3D11 BLEND DEST COLOR desc.RenderTarget 0 .BlendOp D3D11 BLEND OP ADD desc.RenderTarget 0 .SrcBlendAlpha D3D11 BLEND SRC ALPHA desc.RenderTarget 0 .DestBlendAlpha D3D11 BLEND DEST ALPHA desc.RenderTarget 0 .BlendOpAlpha D3D11 BLEND OP ADD desc.RenderTarget 0 .RenderTargetWriteMask 7 return !FAILED( pDeviceManager gt GetDevice() gt CreateBlendState( amp desc, amp pBlendState)) Right now my alpha blending only works when the AlphaToCoverage bool is set to false... I thought this was just a bool enabling the pixel fragment blending (which upon retrospection would be redundant considering the BlendEnable flags...) but looking at the MSDN documentation is appears to do this... You can use the AlphaToCoverageEnable member of D3D11 BLEND DESC1 or D3D11 BLEND DESC to toggle whether the runtime converts the .a component (alpha) of output register SV Target0 from the pixel shader to an n step coverage mask (given an n sample RenderTarget). The runtime performs an AND operation of this mask with the typical sample coverage for the pixel in the primitive (in addition to the sample mask) to determine which samples to update in all the active RenderTargets. Could someone explain this to me and how it differs from when the AlphaToCoverageEnable bool is false? I see that it adds a new mask to the fragment but I don't quite follow what the mask exactly is."} {"_id": 40, "text": "Sharpdx DirectX11 MapSubresource is failing trying to map a staging texture I'm trying to render to a texture and then pull the image data out. I've created one texture as a render target and another as a staging texture. After rendering to the render target, I use CopyResource to copy from the render target texture to the staging texture. So far, so good. However, when I use DeviceContext.MapSubresource to get the data from the staging texture, I get E INVALIDARGS exception, and I can't figure out why. Here is how I create the staging texture textureDesc new Texture2DDescription() ArraySize 1, BindFlags BindFlags.None, CpuAccessFlags CpuAccessFlags.Read, Format Format.B8G8R8A8 UNorm, Height 256, MipLevels 1, SampleDescription new SampleDescription(1, 0), Usage ResourceUsage.Staging, Width 256 renderStaging new Texture2D( dev, textureDesc) Here is how I populate the staging texture and then try to map it DataStream stream con.CopyResource( renderTarget, renderStaging) The following is the line that fails box con.MapSubresource( renderStaging, 0, MapMode.Read, MapFlags.None, out stream) I have the same code working in C , so I know I have the general idea right. This is the working C code textureDesc.Width 256 textureDesc.Height 256 textureDesc.MipLevels 1 textureDesc.ArraySize 1 textureDesc.Format DXGI FORMAT B8G8R8A8 UNORM textureDesc.SampleDesc.Count 1 textureDesc.MiscFlags 0 textureDesc.Usage D3D11 USAGE STAGING textureDesc.BindFlags 0 textureDesc.CPUAccessFlags D3D10 CPU ACCESS READ hr dev gt CreateTexture2D( amp textureDesc, NULL, amp renderStagingTexture) devcon gt CopyResource(renderStagingTexture, renderTargetTextureMap) D3D11 MAPPED SUBRESOURCE mappedResource devcon gt Map(renderStagingTexture, 0, D3D11 MAP READ, 0, amp mappedResource)"} {"_id": 40, "text": "How can I check the shader model capabilities of an adapter? I'm writing an application that targets Direct3D11 (through SlimDX) and shader model 5. When I'm running it on a system that doesn't have SM5 capable hardware, I will get a NullReferenceException when trying to access the techniques in the compiled effect instance. How can I check if the adapter is capable of this before I even attempt to use any of these features?"} {"_id": 40, "text": "What is the format of DXGI FORMAT D24 UNORM S8 UINT? I'm trying to read the values in a depth texture of type DXGI FORMAT D24 UNORM S8 UINT. I know this means \"24 bits for depth, 8 bits for stencil\" \"A 32 bit z buffer format that supports 24 bits for depth and 8 bits for stencil.\", but how do you interpret those 24 bits? It's clearly not going to be a 32 bit int, and it's not going to be a 32 bit float. If it is an integer value, how \"far away\" is a value of \"1\" in the depth texture?"} {"_id": 40, "text": "Is object space the same as local space? I was in directx 11 and was wondering is local space the same as object space and if not, what is object space?"} {"_id": 40, "text": "Using a DirectX Vertex Shader to Modify the Vertex Data in VRAM? I'm working on a GPU side particle system in DirectX 11 where the vertex shader uses a vector field encoded into the color channels of a texture to modify the positions of the vertices before drawing them to the screen. I'm trying to keep the computations on the GPU rather than calculating the updated particle positions on the CPU and send the new vertex data to the GPU every frame, so I've been investigating the possibility of having the vertex shader overwrite the vertex buffer in VRAM with the updated vertex positions each frame. So far, I haven't managed to find anything on the topic. Would this be possible, and if so, how would I accomplish it?"} {"_id": 40, "text": "Geometry shader Dynamic output? I'm currently using a geometry shader to generate grass blades out of single root points that are layed out in a grid. For each root point, I generate a grass blade with, right now, a constant number of vertices. However, for level of detail, I would like to generate a number of vertices depending on the distance to the camera. Now, since there are no dynamic arrays, I tried to declare multiple techniques which call the geometry shader with the number of vertices. I would then be able to divide my grass into patches smaller grids, calculate the distance to the camera for this patch and then call the technique with the appropriate number of vertices. The HLSL part looks something like this maxvertexcount(24) void GS LOD1(point GEO IN points 1 , inout TriangleStream lt GEO OUT gt output) GS Shader(points, 8, output) maxvertexcount(24) void GS LOD2(point GEO IN points 1 , inout TriangleStream lt GEO OUT gt output) GS Shader(points, 16, output) technique LevelOfDetail1 pass Pass1 VertexShader compile vs 4 0 VS Shader() GeometryShader compile gs 4 0 GS LOD1() PixelShader compile ps 4 0 PS Shader() technique LevelOfDetail2 pass Pass1 VertexShader compile vs 4 0 VS Shader() GeometryShader compile gs 4 0 GS LOD2() PixelShader compile ps 4 0 PS Shader() And the definition of the GS function void GS Shader(point GEO IN points 1 , in const int realVertexCount, inout TriangleStream lt GEO OUT gt output) ... GEO OUT v realVertexCount However, even this way the compiler complains array dimensions must be literal scalar expressions Is this possible in any way? I guess what would is just writing several geometry shaders that basically do the same thing but with a already defined number of vertices this sounds a bit messy though. Thanks!"} {"_id": 40, "text": "Resizing D3D Buffers within a frame I have a particle system. So far it worked like this I have a dynamic vertex buffer for a system, which is created with a size that can hold for example 100 000 particles. I map unmap this and write the new data into it every frame. But what if the particle count gets bigger than the buffer can hold? I thought of recreating the vertex buffer with the double of its previous capacity (then map unmap into it). Is this the right direction for this or should I solve it in a different way? A short example ID3D11VertexBuffer buffer ID3D11Device graphicsDevice ... D3D11 BUFFER DESC desc buffer gt GetDesc( amp desc) if(dataSize gt (int)desc.ByteWidth) data can't fit, so destroy and recreate buffer gt Release() desc.ByteWidth 2 graphicsDevice gt CreateBuffer( amp desc, nullptr, amp buffer ) returns S OK Update I want to use it for other things, not just particles but for example instanced meshes. If I spawn a couple of instances, I'd only like to resize a buffer, without creating an other one."} {"_id": 40, "text": "Why does my game not update unless I'm moving the mouse? I'm pretty confused by what's happening. Now that I've finally put something moving on my screen, I notice it doesn't update unless I move the mouse, or press a key, or trigger other events. Using PIX, the \"Frame \" counter only goes up when I fire these events. This is all that happens in my game loop while(GetMessage( amp msg, NULL, 0, 0) gt 0 amp amp m isRunning) TranslateMessage( amp msg) DispatchMessage( amp msg) m gameGraphics gt BeginRender() m gameGraphics gt EndRender() BeginRender clears the screen, and EndRender presents to the swap chain. I thought maybe it was a problem with WndProc, but comparing it to other DirectX 11 game WndProcs, I don't see any major differences. I'm pretty confused, never seen this problem before, and I have no idea what causes it. I'm just hoping maybe someone will have some insight on why this might be happening."} {"_id": 40, "text": "FormatMessage not working for HRESULTs returned by Direct3D 11 I am using Windows 7 x64 and Visual Studio 17 (v15.9.7). Say I try to create a swap chain using IDXGIFactory2 CreateSwapChainForHwnd and pass in DXGI SCALING NONE. I will get the following message in debug output (if I have enabled Direct3D debugging) DXGI ERROR IDXGIFactory CreateSwapChain DXGI SCALING NONE is only supported on Win8 and beyond. DXGI SWAP CHAIN DESC SwapChainType ... HWND, BufferDesc DXGI MODE DESC1 Width 816, Height 488, RefreshRate DXGI RATIONAL Numerator 0, Denominator 1 , Format B8G8R8A8 UNORM, ScanlineOrdering ... UNSPECIFIED, Scaling ... UNSPECIFIED, Stereo FALSE , SampleDesc DXGI SAMPLE DESC Count 1, Quality 0 , BufferUsage 0x20, BufferCount 2, OutputWindow 0x0000000000290738, Scaling ... NONE, Windowed TRUE, SwapEffect ... FLIP SEQUENTIAL, AlphaMode ... UNSPECIFIED, Flags 0x0 MISCELLANEOUS ERROR 175 The function returns 0x887a0001 in form of a HRESULT. If I put err,hr in the watch window, I get a nice error message there ERROR MOD NOT FOUND The specified module could not be found. However, if I pass this HRESULT to FormatMessage, it just puts NULL in the output and returns 0. err,hr helpfully informs me that the new error is ERROR MR MID NOT FOUND The system cannot find message text for message number 0x 1 in the message file for 2. My questions are Why is FormatMessage not giving me right error string (the one starting with ERROR MOD NOT FOUND...)? Where is Visual Studio getting these pretty error strings from? Can I get them too? Who do I pay? PS. I am using the Windows 10 SDK version of DX11, not the older DirectX SDK version. Thus, I can't really link to dxerr.lib either. This is the code that is used to print the error message LPTSTR error text NULL FormatMessage(FORMAT MESSAGE FROM SYSTEM FORMAT MESSAGE ALLOCATE BUFFER FORMAT MESSAGE IGNORE INSERTS, NULL, hr, MAKELANGID(LANG NEUTRAL, SUBLANG DEFAULT), (LPTSTR) amp error text, 0, NULL)"} {"_id": 40, "text": "Direct3D11 Depth buffer problem Encountered a strange error when using Direct3D11, feature level 10.0. If the depth buffer texture is created with the format DXGI FORMAT R24G8 TYPELESS, bind flag D3D11 BIND DEPTH STENCIL D3D11 BIND SHADER RESOURCE and the depth stencil view format DXGI FORMAT D24 UNORM S8 UINT, everything is correct. Also, there are no problems when the depth buffer texture format is DXGI FORMAT R32G8X24 TYPELESS and the depth stencil view format is DXGI FORMAT D32 FLOAT S8X24 UINT. However, when the depth buffer format is DXGI FORMAT R32 TYPELESS, and the depth stencil view format is DXGI FORMAT D32 FLOAT, the whole geometry is not rendered at all, only the clear color is visible. I used Visual Studio 2015's Graphics Debugger to check if the geometry is rendered as desired, but during the Output Merger stage the whole geometry is discarded because it failed the depth test. Every Direct3D function call returns no error and the Direct3D debugging output reports no error (only INFO messages about creation destruction of resources). I do not use the stencil functionality at all, and it is disabled. I use a Windows 7 virtual machine as a developer machine and using DXGI FORMAT R32 TYPELESS and DXGI FORMAT D32 FLOAT worked flawlessly before I switched from a Windows 7 host to an Arch Linux host, because the old hard drive started to fail and the operating system was unable to read its own files during boot. After I switched the host operating system, this problem started to occur inside the virtual machine. Is it possible to have a bug somewhere else in my code? Is there a limitation when using DXGI FORMAT D32 FLOAT and sometimes it may not be possible to use DXGI FORMAT D32 FLOAT or the other depth formats on every machine (considering D3D11 feature level 10.0 is available)? Or is this a bug somewhere else, possibly in VMware player or Linux or Bumblebee (Optimus Intel HD 4000 GeForce GTX 650M)?"} {"_id": 40, "text": "DXGI Frame rate drops from 8000 FPS to 1500 FPS when switching to full screen mode I've created a simple app with a DirectX11 device and swap chain (IDXGISwapChain). All it does is clear the screen with a color and call Present(0, 0) on the swap chain. The app handles full screen windowed mode transition by itself (I passed DXGI MWA NO WINDOW CHANGES) to the IDXGIFactory object. After switching from windowed mode to full screen, the VS graphics profiler shows a drop in the frame rate, from 8000 FPS (window mode) to 1500 FPS (full screen mode). I think I'm resizing my buffers properly (in response to WM SIZE), I'm not getting any warnings about presentation inefficiencies in the debug window. The mode used to create the swap chain is obtained by enumerating the supported modes of the output device and selecting the proper resolution info. Isn't full screen mode supposed to be more efficient (as I understand, it can simply do a flip instead of a bit blit). The code is here in case you want to take a look."} {"_id": 40, "text": "Frustum culling instancing I've implemented instancing in my app and right now I have an instance buffer holding position data for all instances. But I'd like to also implement frustum culling which would cull some of the instances depending on the camera view. Now, how can I render only some of the instances in the buffer but not all? Do I have to rebuild the buffer every frame (so that it only holds visible instances) or is there a way in DirectX 11 to \"tell\" API which instances from the buffer I want drawn?"} {"_id": 40, "text": "Figure out why vertices are clipped I am trying to figure out why, at sharp cutoffs in geometry, some vertices seems to be culled for some reason. I have a heightmap for demonstrating it like this And this is the result I get See the red rectangles where the geometry is just cut and the skybox is shown behind. I am not quite sure where to start looking where the problem might be. I know for a fact it's not colliding with the z near value. Any non steep geometry is fine. Any pointers? EDIT at certain angles, re orienting the camera ever so slightly changes things, like this"} {"_id": 40, "text": "D3D11 Can only Pixel Shader and Compute Shader stages write to buffers? I am reading Practical Rendering and Computation with Direct3D 11. In the book the D3D11 pipeline is often described with this image In the Chapter about resources, Paragraph about buffers, I understood that the only stages that can write to buffers are the Pixel Shader and the Compute Shader, using Unordered Access Views. Is it correct? If so, why? Is it because of the inherent architecture of GPUs? Then, what would be the typical method to output data from a different stage? For example, how could one get the result of a computation done in the vertex shader, without needing to pass through the other stages?"} {"_id": 40, "text": "Fix Pixel Shader \"Stage did not run. No output\" I'm trying to set up a minimal D3D11 renderer but fail to get the pixel shader stage to run. The available answers here or the ones I found through Google couldn't help me, unfortunately. Using Visual Studio's Graphics Debugger I could verify that my vertices are set correctly and the vertex shader also runs as expected. The debug layer doesn't report any issues either. As a test I disabled depth testing, stencil testing and backface culling as shown below with no changes. I made sure that the viewport is set correctly as well as this seems to be a common source of this problem. At this moment I can't think of any other cause for this issue and would be happy about any advice of what else to look out for. Disable depth stencil test D3D11 DEPTH STENCIL DESC dsstate desc dsstate desc.DepthEnable false dsstate desc.StencilEnable false dsstate desc.DepthFunc D3D11 COMPARISON ALWAYS dsstate desc.DepthWriteMask D3D11 DEPTH WRITE MASK ALL dsstate desc.BackFace.StencilFailOp D3D11 STENCIL OP KEEP dsstate desc.BackFace.StencilPassOp D3D11 STENCIL OP KEEP dsstate desc.BackFace.StencilFunc D3D11 COMPARISON ALWAYS dsstate desc.FrontFace.StencilFailOp D3D11 STENCIL OP KEEP dsstate desc.FrontFace.StencilPassOp D3D11 STENCIL OP KEEP dsstate desc.FrontFace.StencilFunc D3D11 COMPARISON ALWAYS d3d11device gt CreateDepthStencilState( amp ds state, amp this gt ds state) d3d11context gt OMSetDepthStencilState(this gt ds state, 0) Disable backface culling D3D11 RASTERIZER DESC rasterizer desc rasterizer desc.AntialiasedLineEnable false rasterizer desc.CullMode D3D11 CULL NONE rasterizer desc.DepthBias 0 rasterizer desc.DepthBiasClamp 0.0f rasterizer desc.DepthClipEnable false rasterizer desc.FillMode D3D11 FILL SOLID rasterizer desc.FrontCounterClockwise true rasterizer desc.MultisampleEnable false rasterizer desc.ScissorEnable false rasterizer desc.SlopeScaledDepthBias 0.0f d3d11device gt CreateRasterizerState( amp rasterizer desc, amp this gt rasterizer state) d3d11context gt RSSetState(this gt rasterizer state) Pipeline view in debugger Vertex shader transformation Vertex shader struct VertexIn float3 position POSITION float3 normal NORMAL float4 color COLOR struct VertexOut float4 color COLOR float4 position SV POSITION VertexOut main(VertexIn i) VertexOut o o.position float4(i.position, 1.0f) o.color i.color return o Pixel shader struct FragmentIn float4 color COLOR float4 pos SV POSITION float4 main(FragmentIn i) SV TARGET return float4(1.0f, 0.0f, 0.0f, 1.0f)"} {"_id": 40, "text": "Using DirectWrite to write text on a IDirect3DTexture9 I'm trying to write text using the DirectWrite API on a IDirect3DTexture9. I've heard that people were capable of doing this but I do not see directly how I can glue these two APIs together. It seems I need a IDXGISurface to create a valid ID2D1RenderTarget (with which I can draw the text). I can get this by creating a surface for the Window. But I think the idea is that I use the IDirect3DTexture9 as a surface for the render target so that I can use whatever is drawn on it in my application. I can get the underlying IDirect3DSurface9 from the IDrect3DTexture9 but then I have to convert it somehow to a IDXGISurface and this is where I'm stuck. Does anybody have a clue?"} {"_id": 40, "text": "Frame timer does not show time I am currently using DirectX11 and MFC. The top of the window should tell me how long it takes to render the cube (in seconds). At the moment the cube is rendered but when I try to work out how many seconds it took to render the cube I keep getting 0 on the top of the window. This cannot be right. Help please? This is my Ondraw function void CLearningVisualCView OnDraw(CDC pDC) I want the OnDraw function to create the cube.. CString TimerReports TODO add draw code for native data here CLearningVisualCDoc pDoc GetDocument() ASSERT VALID(pDoc) if (!pDoc) return Timer.GetStartTime() Render() This renders the cube Timer.GetEndTime() The counts stopwatch ends. Timer.DeltaCountDifference(Timer.StartTime, Timer.EndTime) Timer.GetSecondsPerCount() Timer.FrameTime(Timer.DeltaCounts, Timer.SecondsPerCount) TimerReports.Format( T(\" .100I64d\"), Timer.Time) TimerReports.Format( T(\" .5I64d\"), Timer.FrameTime(Timer.DeltaCounts, Timer.SecondsPerCount)) This converts the DeltaCountDifference into a CString. It has 5 d.p. AfxGetMainWnd() gt SetWindowText(TimerReports) This displays my count difference to the top of the window. This is my Timer class include \"stdafx.h\" include \"GameTimer.h\" GameTimer GameTimer() QueryPerformanceFrequency((LARGE INTEGER ) amp countsPerSec) SecondsPerCount 1.0 (double)countsPerSec GameTimer GameTimer() int64 GameTimer GetStartTime() QueryPerformanceCounter((LARGE INTEGER ) amp StartTime) return StartTime int64 GameTimer GetEndTime() QueryPerformanceCounter((LARGE INTEGER ) amp EndTime) return EndTime The int64 amp are references. We will link them to the StartTime and the EndTime in the CLearningVisualCView OnDraw(). This is done by adding them as arguments. int64 GameTimer DeltaCountDifference( int64 amp TimeA, int64 amp TimeB) int64 DeltaCounts TimeB TimeA return DeltaCounts float GameTimer GetSecondsPerCount() QueryPerformanceFrequency((LARGE INTEGER ) amp CountsPerSecond) SecondsPerCount 1 CountsPerSecond return SecondsPerCount int64 GameTimer FrameTime( int64 amp TheDeltaCounts, float amp SecsPerCount) Time TheDeltaCounts SecsPerCount return Time"} {"_id": 40, "text": "How to use dynamic resources with SharpDX by detail? I've looked through a lot of archives but still cannot figure out how it works. Taking this overridden one for example. public DataBox MapSubresource(Buffer resource, MapMode mode, MapFlags flags, out DataStream stream) Is this method aiming to change the resource with stream. If it is, why would the stream be marked out as if it is an output value rather than input? If the above one is true, where can I stream my data into the stream to update the buffer? Has it to be between the Map and Unmap methods? And typically how should I stream it (Take vertex buffer for example, what would the format of streaming be like?) Is it advisable to call the MapSubresource method whenever GPU access is finished(after every frame), and call the UnmapSubresource next frame to allow GPU access so it may save more time when I am keep updating the data? Thank you!"} {"_id": 40, "text": "How do I change rasterizer state properly? To set the rasterizer state I have to ID3D11Device CreateRasterizerState() and then ID3D11DeviceContext RSSetState. And then I should ID3D11RasterizerState Release() it, right? How about when I want to change the state? Do I follow the above 3 steps again? When I want to change just 1 setting (i.e. only CullMode) do I still have to fill and set whole structure? Also, do I have to create and release the state object each time (assuming I don't want to set the exact same state again in the future)? How about performance? If I set the exact same state again does it do anything? Is there a difference between changing only 1 setting or most all of them?"} {"_id": 40, "text": "Fbx SDK Importer issue (texture uv related) I am using the latest autodesk FBX Importer SDK, but whatever I do, I am unable to get the uvs right. Some parts are textured properly while others are not. I am using Direct3D9 and Direct3D11 (same result in both). Image 360 image https i.gyazo.com 5a2e5f6e127521915508c9c300eb03e5.mp4 The model uses a single texture and a single material shared among 4 meshes. Is there someone who sees immediately what the problem could be? Or is there someone who can replicate the issue for me and figure out what I am missing? FBX Test File http www.4shared.com rar o WG0Crpce Peach64FBX.html My UV reading method int vertexCounter 0 for (int j 0 j lt nbPolygons j ) for (int k 0 k lt 3 k ) int vertexIndex pFbxMesh gt GetPolygonVertex(j, k) Vector2 uv readUV(pFbxMesh, vertexIndex, pFbxMesh gt GetTextureUVIndex(j, k), uv) pVertices vertexIndex .uv.x uv.x pVertices vertexIndex .uv.y 1.0 uv.y vertexCounter void readUV(fbxsdk FbxMesh pFbxMesh, int vertexIndex, int uvIndex, Vector2 amp uv) fbxsdk FbxLayerElementUV pFbxLayerElementUV pFbxMesh gt GetLayer(0) gt GetUVs() if (pFbxLayerElementUV nullptr) return switch (pFbxLayerElementUV gt GetMappingMode()) case FbxLayerElementUV eByControlPoint switch (pFbxLayerElementUV gt GetReferenceMode()) case FbxLayerElementUV eDirect fbxsdk FbxVector2 fbxUv pFbxLayerElementUV gt GetDirectArray().GetAt(vertexIndex) uv.x fbxUv.mData 0 uv.y fbxUv.mData 1 break case FbxLayerElementUV eIndexToDirect int id pFbxLayerElementUV gt GetIndexArray().GetAt(vertexIndex) fbxsdk FbxVector2 fbxUv pFbxLayerElementUV gt GetDirectArray().GetAt(id) uv.x fbxUv.mData 0 uv.y fbxUv.mData 1 break break case FbxLayerElementUV eByPolygonVertex switch (pFbxLayerElementUV gt GetReferenceMode()) Always enters this part for the example model case FbxLayerElementUV eDirect case FbxLayerElementUV eIndexToDirect uv.x pFbxLayerElementUV gt GetDirectArray().GetAt(uvIndex).mData 0 uv.y pFbxLayerElementUV gt GetDirectArray().GetAt(uvIndex).mData 1 break break I am doing V 1.0 uv.y because I am using Direct3D11. NOTE the MappingMode is always eByPolygonVertex and ReferenceMode is always eIndexToDirect Rendering Info Rendered as a Triangle List Uv wrapping mode Wrap (Repeat) Culling None"} {"_id": 40, "text": "Is the new windows 8 sdk usable with visual c express 2010 on windows 7? This is inspired by and related to Is the June 2010 DX SDK really the latest? asked recently but it's a different question. I won't likely be purchasing the full visual studio 2012 for C , I intend to use the free visual c express 2012 that targets desktop applications when it is released so for now I'm using visual c express 2010 running on windows 7. The latest directx11 sdk is the one included in the windows 8 SDK now, it's not a separate release any more. So my question is, can I use the windows 8 SDK to build directx11 programs that work on windows 7 using visual studio express 2010 running on windows 7. Or do I need to stick to the final DirectX SDK release for now?"} {"_id": 40, "text": "How would I implement render scaling in a DX11 game? I would like to implement render scaling that could render a scene at a certain of the window resolution. How would I do this? I've tried resizing a number of things, then resizing them up or down to match the window size but I've never gotten it to work."} {"_id": 40, "text": "How can I read texel data on a separate thread in D3D11? In D3D10, I load a staging texture onto my GPU memory, then map it in order to access its texel data on the CPU. This is done on a separate thread, not the thread I render with. I just call the device methods, and it works. In D3D11 I load the staging texture onto my GPU, but to access it (i.e. Map it) I need to use the Context, not the device. Can't use the immediate context, since the immediate context can only be used by a single thread at a time. But I also can't use a deferred context to Read from the texture to the CPU \"If you call Map on a deferred context, you can only pass D3D11 MAP WRITE DISCARD, D3D11 MAP WRITE NO OVERWRITE, or both to the MapType parameter. Other D3D11 MAP typed values are not supported for a deferred context.\" http msdn.microsoft.com en us library ff476457.aspx Ok, so what am I supposed to do now? It is common to use textures to store certain data (heightmaps for instance) and you obviously have to be able to access that data for it to be useful. Is there no way for me to do this in a separate thread with D3D11?"} {"_id": 40, "text": "Occlusion culling of BV tree nodes behind terrain So I have a bounding volume tree, almost an octree but not quite. Anyway I'm trying to optimize my drawing, right now I have a few different culling frustums that I use to cull different ranges of the BV tree, its very fast, I can pull all my world data in less than 1ms but when it comes to culling the grass and the other mesh data I'm thinking that because I have lots of mountains and hill that I'm rendering stuff that is inside the frustum but occluded but hills and mountains. What would be the right way to cull this? Should I do a ray cast against my terrain from each corner of the bounding boxes to the player and cull anything that gets a hit? or should I find some fancy way to do it on the GPU?. I only have to test maybe 1k boxes x 8 corners, so the ray casting shouldn't take to long."} {"_id": 41, "text": "How can I make a character walk on uneven walls in a 2D platformer? I want to have a playable character who can \"walk\" on an organic surface at any angle, including sideways and upside down. By \"organic\" levels with slanted and curved features instead of straight lines at 90 degree angles. I'm currently working in AS3 (moderate amateur experience) and using Nape (pretty much a newbie) for basic gravity based physics, to which this walking mechanic will be an obvious exception. Is there a procedural way to do this kind of walk mechanic, perhaps using Nape constraints? Or would it be best to create explicit walking \"paths\" following the contours of the level surfaces and use them to constrain the walking movement?"} {"_id": 41, "text": "In AS3, is it necessary to remove the children from a parent who is also being removed? My point is this addChild(parentMC) parentMC.addChild(child1) parentMC.addChild(child2) If I want to then remove parentMC from the current container, is it necessary to also remove child1 and child2 from parentMC in order to properly clean up? Or is that handled automatically through removing parentMC?"} {"_id": 41, "text": "Export information to a custom file type from Air So I have an engine (air application) that basically (for now) is loading some windows on the screen stage, and you can drag them around. And later on, I'll be able to add other objects onto the stage. How would I export any kind of information (like co ordinates or sizes of windows) out of my application to an external custom file. And then I would use that file to reload a previous project if I were to re load the engine. I'm working in AS3 Air and in FlashDevelop. Thanks for the help and time. If anymore information is needed please let me know. Cheers."} {"_id": 41, "text": "Setting up speedtests in Actionscript 3 for an entire game I'm very new to this so please forgive the questions possibly ill stated nature. Firstly is this even a valid way to speedtest public function L1() tree.x 200 tree.y 200 tree.healthPoints 0 addChild(tree) var myTimer Timer new Timer(100,60) myTimer.addEventListener(TimerEvent.TIMER,someFunction) myTimer.start() addEventListener(Event.ENTER FRAME, speedTest) function someFunction(event TimerEvent) t public function speedTest (e Event) if (tree ! null) do tree.healthPoints 1 while (tree.healthPoints lt 10000) tree.healthPoints 0 trace (t) Secondly I want to actually speed test the entire game somehow to check if adding new features or rewriting current features actually optimizes the game or not. What are some ways to do this?"} {"_id": 41, "text": "Animating Tile with Blitting taking up Memory I am trying to animate a specific tile in my 2d Array, using blitting. The animation consists of three different 16x16 sprites in a tilesheet. Now that works perfect with the code below. BUT it's causing memory leakage. Every second the FlashPlayer is taking up 140 kb more in memory. What part of the following code could possibly cause the leak The variable Rectangle finds where on the 2d array we should clear the pixels Fillrect follows up by setting alpha 0 at that spot before we copy in nxt Sprite Tiletype is a variable that holds what kind of tile the next tile in animation is (from tileSheet) drawTile() gets Sprite from tilesheet and copyPixels it into right position on canvas public function animateSprite() void tileGround.bitmapData.lock() if(anmArray 0 .tileType gt 42) anmArray 0 .tileType 40 frameCount 0 var rect Rectangle new Rectangle(anmArray 0 .xtile ts, anmArray 0 .ytile ts, ts, ts) tileGround.bitmapData.fillRect(rect, 0) anmArray 0 .tileType 40 frameCount drawTile(anmArray 0 .tileType, anmArray 0 .xtile, anmArray 0 .ytile) frameCount tileGround.bitmapData.unlock() public function drawTile(spriteType int, xt int, yt int) void var tileSprite Bitmap getImageFromSheet(spriteType, ts) var rec Rectangle new Rectangle(0, 0, ts, ts) var pt Point new Point(xt ts, yt ts) tileGround.bitmapData.copyPixels(tileSprite.bitmapData, rec, pt, null, null, true) public function getImageFromSheet(spriteType int, size int) Bitmap var sheetColumns int tSheet.width ts var col int spriteType sheetColumns var row int Math.floor(spriteType sheetColumns) var rec Rectangle new Rectangle(col ts, row ts, size, size) var pt Point new Point(0,0) var correctTile Bitmap new Bitmap(new BitmapData(size, size, false, 0)) correctTile.bitmapData.copyPixels(tSheet, rec, pt, null, null, true) return correctTile"} {"_id": 41, "text": "How to set blur on mouse over and remove on mouse out in AS3? How can I do it? I want to active glow when the mouse is over a Sprite and remove it when the mouse is out. Is it possible? I have the following code var myGlow GlowFilter new GlowFilter() myGlow.color 0xFFFFFF myGlow.blurX glowMobilha.blurY 20 var miniatura MovieClip scene.d1 link miniatura.addEventListener(MouseEvent.CLICK, function(e Event) void MainSoundManager. sm.stopAllSounds() GameManager.loadSection(link, false) ) miniatura.addEventListener(MouseEvent.MOUSE OVER, function(e Event) void miniatura.filters myGlow miniatura.gotoAndStop(2) control.visible true controle.gotoAndPlay(2) ) miniatura.addEventListener(MouseEvent.MOUSE OUT, function(e Event) void miniatura.gotoAndStop(1) control.visible false control.gotoAndStop(1) ) miniatura.buttonMode true I set the blur at miniatura.addEventListener(MouseEvent.MOUSE OVER, function(e Event) void miniatura.filters myGlow miniatura.gotoAndStop(2) control.visible true controle.gotoAndPlay(2) ) How can I \"hide\" the blur at miniatura.addEventListener(MouseEvent.MOUSE OUT, function(e Event) void miniatura.gotoAndStop(1) control.visible false control.gotoAndStop(1) ) UPDATE I think I found the solution in the following code miniatura.addEventListener(MouseEvent.MOUSE OVER, function(e Event) void glowMobilha.alpha 1 miniatura.filters glowMobilha controle.visible true controle.gotoAndPlay(2) ) miniatura.addEventListener(MouseEvent.MOUSE OUT, function(e Event) void glowMobilha.alpha 0 miniatura.filters glowMobilha controle.visible false controle.gotoAndStop(1) ) is it the best solution?"} {"_id": 41, "text": "Air AS3 Desktop Detecting wrong screen resolution and coordinate offset I have an issue with developing an Air desktop app using FlashDevelop in ActionScript 3.0 I'm pretty much new to all this, but I think I made all I should and am wondering if this could be some bug outside my code. My screen and desktop composition is as follows 1x Surface pro 3 with Multitouch 2160x1440 screen on the left (Identified as Screen 1) 1x Dell P2314T Multitouch with 1920x1080 screen in the middle (Identified as Screen 2) 1x Dell P2314T Multitouch with 1920x1080 screen on the right (Identified as Screen 3) When I run Air app with fullscreen mode with stage.displayState StageDisplayState.FULL SCREEN stage.scaleMode StageScaleMode.NO SCALE I get it on the Surface's screen on fullscreen, it being the windows Main display. If I trace the stage.nativeWindow.width and stage.nativeWindow.height I get the correct resolution. Now since I wanted the app to run on the 23\" screen, I set Screen 2 to be the Main display in windows. Now AIR app is ran on the screen 2 by default, thus reporting the stage width and height being 1920 and 1080. However, the child sprites I have on stage with coordinate x 0 are outside my screen area! They are not visible on the screen on the left, but simply hidden like they're outside of the stage. If I put first child x offset to 120 (half of the difference between 1920 and 2160 screen widths), it's positioned approx on the left edge. To see better what's going on, I went to screen resolution manager and disabled the internal Surface's screen completely (\"Don't show desktop on this screen\", thus leaving me with 2x 1920x1080 screens only. If I run the code now, the stage.nativeWindow.width and height are reporting resolution of 2160x1440 that's screen 1, which is disabled and has no image on it at all. The Sprite x offset issue remains the same, being 120 in minus. The code is completely clear, having stage with single sprite and quad drawn. public class Main extends Sprite static public var instance Main public function Main() instance this Multitouch.inputMode MultitouchInputMode.TOUCH POINT stage.displayState StageDisplayState.FULL SCREEN stage.scaleMode StageScaleMode.NO SCALE stage.nativeWindow.alwaysInFront true trace( String(stage.nativeWindow.x) ' y ' String(stage.nativeWindow.y) ' size h ' String(stage.nativeWindow.height) ' w ' String(stage.nativeWindow.width) ) init() private function init() void frame new Sprite frame.x 120 frame.y 450 addChild(frame) trace('frame x ' frame.x) What could possibly cause such error? Could someone confirm whether this error is reproducible? Thanks! Edit 1 Ok, seems like the failed offset was fixed adding the stage align property in main stage.align StageAlign.TOP LEFT I'm still interested to know why the runtime default align happens using scree 1 instead of main's resolution, and therefore fails to be correct though! The magic about wrong resolution still stays the same, and can't be reproduced using two different screens (AOC 1920x1080 and Dell 1920x1200) in same composition, using same settings. Weird..."} {"_id": 41, "text": "AS3 Client not sending movement to server I am having trouble with multiplayer player movement in my game. The client is in AS3 and the server is in C . Here is my problem When I first launch the game, it connects to the server, and everything works fine. But... when I try to move my player, it isn't sending the UTF8 bytes over to the server. I even have it trace output after the socket sends the bytes. I sent the exact same bytes to the server when the game started just to see if the server recognized it, and it did. I am not sure why it isn't even sending it at all. This is very frustrating. private function keyDown(event KeyboardEvent) void switch(event.keyCode) case Keyboard.W up true break case Keyboard.S down true break case Keyboard.A left true break case Keyboard.D right true break private function keyUp(event KeyboardEvent) void switch(event.keyCode) case Keyboard.W up false break case Keyboard.S down false break case Keyboard.A left false break case Keyboard.D right false break private var playerSpdTemp int 5 private function enterFrame(e Event) void if (up) archer.y playerSpdTemp socket.writeUTFBytes(\"move \" archer.x \" \" archer.y) trace(\"Sent...\") if (left) archer.x playerSpdTemp if (down) archer.y playerSpdTemp if (right) archer.x playerSpdTemp I tried putting the socket.writeUTFBytes() in the keyDown and keyUp functions but nothing happens either... And yes, I have the correct event listeners set up. The player moves correctly but not the socket."} {"_id": 41, "text": "Read an object from compressed file generated from ActionScript 3 I have made a simple game Map Editor and I want to save a array that contain map tile info to a file, as below var arr Array .....2d tile info in it... var ba ByteArray new ByteArray() ba.writeObject(arr) ba.compress() var file File new File() file.save(ba) I had successfully saved a compressed object to a file. Now the problem is my server side need to read this file and decompress the array out from the file, then convert it to a Python list. Is that possible?"} {"_id": 41, "text": "Walk to nearest attackable range node My game has 3D environment which is partitioned in 2d cells(nodes). I have implemented A for path finding. Now I am just breaking my head to how to implement the algorithm to move the hero to the nearest attackable range node point when the enemy is out of attack able range. Which means, it should satisfy two conditions Target whithin attackable range No obstacles in between the target and attacker See below picture (pardon for my bad drawings) Brown boxes are obstacles Attacker hero is in the cell highlighted with Turquoise color dot, the circle is the radius size of the model. Target is the red dotted color cell, surrounded with red color circle to indicate the size of the model Green circle is the radius where hero has to move to some where inside that location to attack (its the radius of hero's attack range) Blue dots are the A path to reach from hero position to target position When the player issues attack command, hero should move to the nearest attack able node and start attacking. Finally I thought of below algorithm Calculate radius to scan This is the sum of attacker radius attacker weapon radius target radius Get nodes fall within the radius (from step 1) from targets position Find path from attacker to target using A Keep walking in the path (from step 3) check if current node is in the scanned nodes (from step 1) If true, Check that no obstacle are in between If true, attack, if false keep walking (repeat step 4) If we put together the algorithm and the figure1 The A gets the path of 9 node to reach the target After moving 5 steps, it enters the attackable range, since there is obstacle between the target, it take two more steps where it finds no obstacles and stats attacking. I am not sure if this is the optimized method to achieve this but I am not getting alternative solution. Very particular to the steps 2 5 which looks little weird and process intensive to me. I am using actionscript 3 and Flare3D (Stage3D API)"} {"_id": 41, "text": "How to use Pixel Bender (pbj) in ActionScript3 on large Vectors to make fast calculations? Remember my old question 2d game view camera zoom, rotation amp offset using 39 Filter 39 39 Shader 39 processing? I figured I could use a Pixel Bender Shader to do the computation for any large group of elements in a game to save on processing time. At least it's a theory worth checking. I also read this question Pass large array to pixel shader Which I'm guessing is about accomplishing the same thing in a different language. I read this tutorial http unitzeroone.com blog 2009 03 18 flash 10 massive amounts of 3d particles with alchemy source included I am attempting to do some tests. Here is some of the code private const SIZE int Math.pow(10, 5) private var testVectorNum Vector. lt Number gt private function testShader() void shader.data.ab.value 1.0, 8.0 shader.data.src.input testVectorNum shader.data.src.width SIZE 400 shader.data.src.height 100 shaderJob new ShaderJob(shader, testVectorNum, SIZE 4, 1) var time int getTimer(), i int 0 shaderJob.start(true) trace(\"TEST1 \", getTimer() time) The problem is that I keep getting a error saying Fault exception, information Error Error 1000 The system is out of memory. Update I managed to partially workaround the problem by converting the vector into bitmapData (Using this technique I still get a speed boost of 3x using Pixel Bender) private function testShader() void shader.data.ab.value 1.0, 8.0 var time int getTimer(), i int 0 testBitmapData.setVector(testBitmapData.rect, testVectorInt) shader.data.src.input testBitmapData shaderJob new ShaderJob(shader, testBitmapData) shaderJob.start(true) testVectorInt testBitmapData.getVector(testBitmapData.rect) trace(\"TEST1 \", getTimer() time)"} {"_id": 41, "text": "AS3 Using singletons for sound managers Is it necessarily a bad thing to use a singleton for a sound manager? I am having a really tough time determining whether or not I should go ahead and use a singleton (which is easy it works) or if I am shooting myself in the foot by deviating away from good OOP principles (since a singleton is basically a glorified single instance global variable of sorts)."} {"_id": 41, "text": "Can anyone explain step by step how the as3isolib depth sorts isometric objects? The library manages to depth sort correctly, even when using items of non 1x1 sizes. I took a look through the code but it's a big project to go through line by line! There are some questions about the process such as How are the x, y, z values of each object defined? Are they the center points of the objects or something else? I noticed that the IBounds defines the bounds of the object. If you were to visualise a cuboid of 40, 40, 90 in size, where would each of the IBounds metrics be? I would like to know how as3isolib achieves this although I would also be happy with a generalised pseudo code version. At present I have a system that works 90 of the time but in cases of objects that are along the same horizontal line, the depth is calculated as the same value. The depth calculation currently works like this x object horizontal center point y object vertical center point originX and Y the origin point relative to the object so if you want the origin to be the center, the value would be originX 0.5, originY 0.5. If you wanted the origin to be vertical center, horizontal far right of the object it would be originX 1.0, originY 0.5. The origin adjusts the position that the object is transformed from. AABB width The bounding box width. AABB height The bounding box height. depth x (AABB width originX) y (AABB height originY) z This generates the same depth for all objects along the same horizontal x."} {"_id": 41, "text": "Enemy collision detection with movie clips I have created multiple movieclips with animations within them. It is an obstacle avoidance game and I cannot seem to be able to get my enemies to contact my playableCharacter. The enemies I have created are each embedded on certain levels of my game. I have created an array, enemiesArray to have each of my enemies placed within it. Here is the code for that step 1 make sure array exists if(enemiesArray! null amp amp enemiesArray.length! 0) step 2 check all enemies against villain for(var i int 0 i lt enemiesArray.length i ) step 3 check for collision if(villain.hitTestObject(enemiesArray i )) step 4 do stuff trace(\"HIT!\") removeChild(enemiesArray i ) enemiesArray.splice(i,1) removeChild(villain) villain null What I am unsure of is whether or not my enemiesArray is actually holding the movieclips I have suggested. If it was, this code would be tracing back a \"HIT\" for every time I ran into an enemy and would kill my character. It is not doing that however. I am thinking I have to push my movieclips into my array but I don't know how to do that or where for that matter. Any and all help would be much appreciated."} {"_id": 41, "text": "Tiny Wings Placing items I'm currently developing a Flash game like 'Tiny Wings'. I have a lot of work done, but i'm currently working on placing the items ( coins and obstacles ) on the terrain. My player it is moving on a auto generated terrain (based on Emanuele Feronato's tutorials) so every time the player's x position is greater than (screenWidth x) another hill is generated and so on. I'm currently having problems placing the items in a correct angle and put 5 or more items together on a hill. Could you please help me with this? Thanks, Regards. PS This is the URL to the Emanuele Feronato post and the code to make the hills http www.emanueleferonato.com 2011 10 04 create a terrain like the one in tiny wings with flash and box2d E2 80 93 adding more bumps"} {"_id": 41, "text": "Is there any way to change the layering of objects in Actionscript 3 without altering the run order? I'm making a simple platformer in Adobe Animate, and I need the player to be layered in front of the stage because of a gimmick in the game. Unfortunately, whenever I change the layering order, it also seems to change the order that AS3 runs the instances. Is there any way to change the layering order without affecting the instance order, or vice versa? I'm only just starting with programming, so please bear in mind that I probably won't understand many of the technical terms. Thanks in advance!"} {"_id": 41, "text": "How to use Pixel Bender (pbj) in ActionScript3 on large Vectors to make fast calculations? Remember my old question 2d game view camera zoom, rotation amp offset using 39 Filter 39 39 Shader 39 processing? I figured I could use a Pixel Bender Shader to do the computation for any large group of elements in a game to save on processing time. At least it's a theory worth checking. I also read this question Pass large array to pixel shader Which I'm guessing is about accomplishing the same thing in a different language. I read this tutorial http unitzeroone.com blog 2009 03 18 flash 10 massive amounts of 3d particles with alchemy source included I am attempting to do some tests. Here is some of the code private const SIZE int Math.pow(10, 5) private var testVectorNum Vector. lt Number gt private function testShader() void shader.data.ab.value 1.0, 8.0 shader.data.src.input testVectorNum shader.data.src.width SIZE 400 shader.data.src.height 100 shaderJob new ShaderJob(shader, testVectorNum, SIZE 4, 1) var time int getTimer(), i int 0 shaderJob.start(true) trace(\"TEST1 \", getTimer() time) The problem is that I keep getting a error saying Fault exception, information Error Error 1000 The system is out of memory. Update I managed to partially workaround the problem by converting the vector into bitmapData (Using this technique I still get a speed boost of 3x using Pixel Bender) private function testShader() void shader.data.ab.value 1.0, 8.0 var time int getTimer(), i int 0 testBitmapData.setVector(testBitmapData.rect, testVectorInt) shader.data.src.input testBitmapData shaderJob new ShaderJob(shader, testBitmapData) shaderJob.start(true) testVectorInt testBitmapData.getVector(testBitmapData.rect) trace(\"TEST1 \", getTimer() time)"} {"_id": 41, "text": "What are the advantages and challenges of using Haxe over ActionScript 3? I read this, and I also see that using FlashDevelop you can make an Adobe Air project with Haxe and compile to exe. I begun to wonder from a game making perspective Are there any additional advantages in performance when using Haxe instead of AS3 for games development (for the web)?"} {"_id": 41, "text": "AS3 StageWidth for BOX2D? I know BOX2D uses meters, and AS3 uses pixels. I'm trying to create objects which are limited to the stageWidth. If I do this variable for (var i int 0 i lt (stage.stageWidth) i ) ... The animation will freeze, and this output appears TypeError Error 1009 Cannot access a property or method of a null object reference. at Box2D.Collision b2BroadPhase CreateProxy() at Box2D.Collision.Shapes b2Shape CreateProxy() at Box2D.Dynamics b2Body CreateShape() at com.actionsnippet.qbox.objects CircleObject build() at com.actionsnippet.qbox QuickObject init() at com.actionsnippet.qbox QuickObject() at com.actionsnippet.qbox.objects CircleObject() at com.actionsnippet.qbox QuickBox2D create() at com.actionsnippet.qbox QuickBox2D addCircle() at BOX2D Test Tutorial fla MainTimeline frame1() Does anyone know how to fix this? Full Code SWF(width 350, height 600, frameRate 60) import com.actionsnippet.qbox. var sim QuickBox2D new QuickBox2D(this) sim.createStageWalls() make a heavy circle sim.addCircle( x 3, y 3, radius 0.4, density 1 ) create a few platforms make pins for (var i int 0 i lt (stage.stageWidth) i ) End sim.addCircle( x 1 i 1.5, y 18, radius 0.1, density 0 ) sim.addCircle( x 2 i 1.5, y 17, radius 0.1, density 0 ) sim.addCircle( x 1 i 1.5, y 16, radius 0.1, density 0 ) sim.addCircle( x 2 i 1.5, y 15, radius 0.1, density 0 ) Mid end sim.addCircle( x 0 i 2, y 14, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 13, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 12, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 11, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 10, radius 0.1, density 0 ) sim.start() sim.mouseDrag()"} {"_id": 41, "text": "AS3 random events using a timer I'm making a game for an assignment at university. The game I am making requires random household appliances around a house to \"turn on\" at random times. The player must run around the house turning this off. I am confident with the rest of the code for the game, but the random turning on is what I'm not sure on. I am thinking the solution would be to use an array with all my appliances pushed into into, then create a timer event. From this a random time would be picked from the timer, and then a random appliance would be picked from the array. The appliance on animation would then be displayed until the player clicked on it to turn it off. Only problem is i'm not sure how to start this. Also worth mentioning, I am only able to use flashdevelop and AS3 for this project, so no Adobe Flash. Thanks in advance, Job4aCowboy"} {"_id": 41, "text": "What's a good Flash game development tutorial, in FlashDevelop, for an absolute beginner? Ok, here's my situation I'm tutoring a 14yo homeschooled student with very little previous programming experience, and I'd like to teach her how to program. I think that Flash Actionscript 3 is a good resource for her to start out with, mostly because she seems to have an interest in game development. I've decided that FlashDevelop, used alone, is the best interface for her to use, especially as she becomes more proficient in Flash. The trouble is, while I am an extremely competent Web programmer in other languages, I have no experience with Actionscript at all, and I can't find a good tutorial for her to use. The tutorial doesn't need to have the algorithmical basics of programming, like the concept of loops, if statements, OOP, etc I can teach her those. What I need is a tutorial that teaches Actionscript SYNTAX and walks you through the steps of game development in FlashDevelop. Once I have that, I can do everything else. Can anyone help me?"} {"_id": 41, "text": "Using Event Driven Programming in games, when is it beneficial? I am doing a refresher on ActionScript 3. Other than using rudimentary tools like, Event.ENTER FRAME and using events to receive input from the user's mouse and keyboard, I find that I rarely use events and prefer to use public functions. I am starting to reconsider this approach. From what I have learned thus far, the event system works this way Each dispatcher can listen to itself during the target phase. Each display object on the stage, can listen to it's children before the target phase, during Capture or after the target phase, during bubbling. I would like to see an example of good use of the Event class for game programming. Have you used Event driven programming in a game and have a good example you could share? A lot of times I want to pass a message to a 'sibling' so I could have their methods listen to the stage or the parent object. Is that the best way to communicate between objects that are not parents of the dispatcher they want to listen to? I would like to know if events are better performance wise than public functions. Are there cases where using events can result in superior performance than avoiding events and sticking to function calls?"} {"_id": 41, "text": "What is the best toolchain for ActionScript3 social networks game development? I'm new to flash and web development too. But I have some background in c c Qt python. So, I want to know, what is the best toolchain for quickest dive into. My task is to write a game for facebook.com vkontakte.ru. I already have the design doc, great artist and game designer, so, the coding is the only stumbling block we met. There are no significant obstacles at server side, but, since we have not much time, I decided to ask some help on suitable toolchain definition. I think, that web services (maybe WCF) are perfect for the backend, so, some of them should transfer JSON ed data from to client, incapsulate game logic, and... here is the place I stuck. What next, what should I learn, what tools toolsets will provide learing productivity curve that meat least action principle. Maybe I'm on the wrong way and missing some basic and obvious (for web devs) things... I do not know, so, any advices will be highly appreciated. Yes, this is the copy of my question on SO, but it seems, that here is the really proper place to post it."} {"_id": 41, "text": "Target tracking with a small delay (actionscript 3.0) I'm having trouble thinking of a good method to track my character with an enemy attack. Of course, I don't want the attack to track my character's current position I want it to track where the character was about 1 second before (so you can move around and make the attack miss and loop around you sort of a thing). The general structure of my game uses a timer to update all of my events. I have a timer going off every 25 milliseconds that updates everything, including my player's position and the enemies position. Right now I just have the enemy attack directly targeting my character....which works fine except that it's impossible to escape p. Let me know if I didn't supply enough details. My approach was going to basically be get my character's position from about 1 second ago, then have the enemy target that position, the only problem is I can't think of a good way to get my character's position from previous times. Thanks for the help!"} {"_id": 41, "text": "How can I respond to mouse events in AS3? Background Trying to make a simple \"drop the ball\" game. The code is located inside the first frame of the timeline. Nothing more is on the stage. Issue Using QuickBox2D I made a simple If statement that drops and object acording the Mouse x position if (MouseEvent.CLICK) sim.addCircle( x mouseX, y 1, radius 0.25, density 5 ) I imported the MouseEvent library import flash.events.MouseEvent Nothing happens if I click, no output errors either. See it in action http gabrielmeono.com download Lucky Hit Alpha.swf http gabrielmeono.com download Lucky Hit Alpha.fla Full Code SWF(width 350, height 600, frameRate 60) import com.actionsnippet.qbox. import flash.events.MouseEvent var sim QuickBox2D new QuickBox2D(this) sim.createStageWalls() var ball sim.addCircle( x mouseX, y 1, radius 0.25, density 5 ) make a heavy circle sim.addCircle( x 3, y 1, radius 0.25, density 5 ) sim.addCircle( x 2, y 1, radius 0.25, density 5 ) sim.addCircle( x 4, y 1, radius 0.25, density 5 ) sim.addCircle( x 5, y 1, radius 0.25, density 5 ) sim.addCircle( x 6, y 1, radius 0.25, density 5 ) create a few platforms sim.addBox( x 3, y 2, width 4, height 0.2, density 0, angle 0.1 ) make 26 dominoes for (var i int 0 i lt 7 i ) End sim.addCircle( x 1 i 1.5, y 16, radius 0.1, density 0 ) sim.addCircle( x 2 i 1.5, y 15, radius 0.1, density 0 ) Mid end sim.addCircle( x 0 i 2, y 14, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 13, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 12, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 11, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 10, radius 0.1, density 0 ) Middle Start sim.addCircle( x 0 i 1.5, y 09, radius 0.1, density 0 ) sim.addCircle( x 1 i 1.5, y 08, radius 0.1, density 0 ) sim.addCircle( x 0 i 1.5, y 07, radius 0.1, density 0 ) sim.addCircle( x 1 i 1.5, y 06, radius 0.1, density 0 ) if (MouseEvent.CLICK) sim.addCircle( x mouseX, y 1, radius 0.25, density 5 ) sim.start() sim.mouseDrag()"} {"_id": 41, "text": "Dynamic entities using classes and objects I'm trying to create a program which involves the creation of several characters entities. At the moment I have a Base Entity class an Entities class and a Main class. I can handle one entity alright, however I am trying to create each one editable through a standard function call. Main Class http pastebin.com AjgEBSke Entity Class http pastebin.com 5y2wD3Qc BaseEntity Class http pastebin.com VfqRgeng I feel a little confused on how to dynamically call and edit each specific character without limiting myself to lots of 'if' statements. I have tried to restart this project several times... Basically I'm creating a private object in a class. That class will be used to talk to that private object, Save, load and edit etc. Then in a seperate Entities class I create an instance of that object, this is where I think im getting caught up. As far as I know, I need to handle everything I want to do in that entity in this entity class. I give the entity object an ID, and a default name which I want to be able edit later. I also want to eventually be able to call that entity from other classes to 'draw' it, have it return the values I need to draw it, Name, body type etc (other variables in the object). I have managed to interact with a specific instance of the object class by checking if the String is equal to an objects ID and then doing something, this however I feel is not dynamic and I'll just get into a bigger mess. Ideally I think I want to be able to enter the object's class' instance name as a string and have it handle everything. Sorry this has been rather long, if you know of any articles or information on how I'd learn to create dynamic entities to do what I need to do, that'd be great. Im probably looking more for an explanation of the concept of what I'm trying to do as i've only just really sketched up this code. So this code might be a little pointless at the momemnt. Ive attempted it a few times, trying to set things up better each time, however ultimately fail when I try to make things behave dynamically. If i'm going about this completely the wrong way then please tell me as I'm still learning and don't want to get into the habit of doing things badly."} {"_id": 41, "text": "how to save data in a visual novel with shared object I've been looking for ways to save data in a visual novel, I have seen that the best way to do is with shared object but the tutorials are usually saved scores and I want to save the history progression how can I do it? Which variable should be used? What should contain the variable? shared object works for android and ios? Thanks for reading"} {"_id": 41, "text": "Animate Interpolate and wait for completion. I'm implementing a blackjack game in flash and so far the logic is fine but there is no animation for the cards so they just appear and disappear which doesn't look very pleasing to the eye. I want to add some animations for when cards are dealt where they slide across to their position one by one. Is there a simple way to just tell a displayobject to interpolate from one position to another while waiting for it to complete? My current thought would be to just do something like this on enter frame if a card is animating move it further towards its destination continue else (if it is done animating) process as usual end end I believe this would produce the results I'd expect because the game should only continue after the card being dealt is where it should be. However, this feels like a weird approach and I'm probably over thinking it which is why I'd like to know if any of you have a better solution."} {"_id": 41, "text": "Best way to create neon glow line effect in AS3? What's the best way to create a neon glow line effect in Flash AS3? Say similar to what's going on in the game gravitron360 on the xbox 360? Would it be a good idea to create movieclips with plain lines drawn in them and then apply a glow filter to them? or perhaps just apply the glow filter to the entire movieclip layer the movieclips are on? or just draw them manually and create a glow effect by converting the lines to fills and then softening edges? (wouldn't blend as well but would be the fastest CPU wise?) Thanks for any help"} {"_id": 41, "text": "Read an object from compressed file generated from ActionScript 3 I have made a simple game Map Editor and I want to save a array that contain map tile info to a file, as below var arr Array .....2d tile info in it... var ba ByteArray new ByteArray() ba.writeObject(arr) ba.compress() var file File new File() file.save(ba) I had successfully saved a compressed object to a file. Now the problem is my server side need to read this file and decompress the array out from the file, then convert it to a Python list. Is that possible?"} {"_id": 41, "text": "AS3 Using singletons for sound managers Is it necessarily a bad thing to use a singleton for a sound manager? I am having a really tough time determining whether or not I should go ahead and use a singleton (which is easy it works) or if I am shooting myself in the foot by deviating away from good OOP principles (since a singleton is basically a glorified single instance global variable of sorts)."} {"_id": 41, "text": "How to add a movieclip to the stage then make it move down? I am making a game where i want to spawn zombies then make them move down the screen. I also want to have multiple on the screen at once. I have tried multiple ways now but none of them have worked. Here is my code if ((zombie 1) (zombie 3) (zombie 5) (zombie 7)) var Z new Z Z.x 403.25 Z.y 86.9 Z.rotation 90 addChild(Z) zombie 1 Functions function startzombie(event) trace(\"start zombies\") zombie 1 addEventListener(Event.ENTER FRAME,zombiemove) function zombiemove(event Event) Z.y 1 Z is the zombie"} {"_id": 41, "text": "How can I make an movieclip move in a circular path with GTween? How can I make an movieclip move in a circular path with GTween? it's straightforward to have something move with various easing effects in a line or a curve, but I would need a complete circular path."} {"_id": 41, "text": "AS3 Using singletons for sound managers Is it necessarily a bad thing to use a singleton for a sound manager? I am having a really tough time determining whether or not I should go ahead and use a singleton (which is easy it works) or if I am shooting myself in the foot by deviating away from good OOP principles (since a singleton is basically a glorified single instance global variable of sorts)."} {"_id": 41, "text": "Is it more efficient to store my tile grid as a dictionary or an array? I've just started making a video game in AS3, and I'm trying to keep the graphics, sound, and actual game state in three completely different spots and sets of classes. That being the case, the graphics module will have to repeatedly parse the state module. The game is divided into levels, and each level is divided up into square spaces (like a board game) thus the graphics module will have to repeatedly parse out a certain cross section of spaces of the current level. The player will always show up in the middle of the spaces' overall graphic (the \"Grid\"), and there will be 4 spaces in every direction from the player's positioin that will be displayed, along with any object each space may contain (such as the player, a monster, etc.). So right now I'm trying to decide how to store the spaces in each level (all of the level's spaces themselves, not the graphics). The first thing that came to mind was a 2D Array. Then I started to use a 2D Vector, then came back to using an Array, like at first and now I'm wondering whether to use an Array or a Dictionary. The problem Let's say a level looks like this xxxxxxxxxxxx xxxxxxxxxxxx xxxxPxxxxxxx x's are blank spaces, P is the space that the player. As the Grid parses this information, if it's a 2D Array, then it can use the length property of the main Array and the length property of each sub array to set up its for loops reasonably well. Furthermore if a space is outside the bounds of the 2D array, then rather than wasting memory trying to form more objects in the code or something, the Grid can just assume the space is blank var arr Array var space Space for (var i int level.playerX 4 i lt level.playerX i ) arr level.spaces i if (arr) for (var j int level.playerY 4 j lt level.playerY j ) space arr j if (space) find every object inside space and animate accordingly else assume the space is blank else assume the whole column of spaces is blank Within the player's radius, the Grid must animate any non existent spaces as blanks. Therefore the graphical output is as follows xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxPxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx But now if we have a level that looks more like this xxxxxxxxxxxxx xxxxxxxxx Pxxxx xxxxx then using an Array leaves two basic options Use null elements within the sub arrays to get the Grid to animate non existent spaces that come before the real ones in the sub array (the sub array's length can be used for non existent spaces that come after the real ones). Make that simple for looping inside the Grid a whole lot more complex to compensate for rows and columns of spaces starting at variable locations along each axis (and not simply ending at variable locations). I don't want to use option 2. I was just going to use option 1 with Arrays, but now the possibility of using Dictionaries instead has come to mind. At least with Dictionaries, I wouldn't have to just waste memory every time I wanted, let's say, for the first space in a row to begin at postion 5. Sorry, I know this was lengthy, but I hope I've illustrated the problem. Which is better an Array, or a Dictionary? If a Dictionary is better, should it use sub Dictionaries or sub Arrays to establish a 2 dimensional effect? Thanks!"} {"_id": 41, "text": "Show a range grid movement as3 How do I show range of grid movement in AS3? When player controls a character and chooses \"move\" options, the grid of movement will be displayed as 3 grid of X, 4 grid of Y (Both sides, and ). So, it will be like this In the image above, movement grid displayed in blue color. But, how do i display a range grid movement like that?"} {"_id": 41, "text": "Read an object from compressed file generated from ActionScript 3 I have made a simple game Map Editor and I want to save a array that contain map tile info to a file, as below var arr Array .....2d tile info in it... var ba ByteArray new ByteArray() ba.writeObject(arr) ba.compress() var file File new File() file.save(ba) I had successfully saved a compressed object to a file. Now the problem is my server side need to read this file and decompress the array out from the file, then convert it to a Python list. Is that possible?"} {"_id": 41, "text": "Incorrect angle calculation? I'm trying to create a simple topdown game, in which you control the player by WASD keys and use mouse to aim and shoot. So far, I have a player moving and firing, but I think there is something wrong with the shooting. Accuracy gets lower as the mouse cursor move away from the player. Please try the following SWF to see more clearly what I'm trying to say. http dl.dropbox.com u 24777511 gdstack.swf Here is a chunk of relevant code private function fireBullet(x Number, y Number, dFireAngle Number) void var b Bullet recycleBullet() var rFireAngle Number b.reset(x, y) b.angle dFireAngle rFireAngle (dFireAngle (Math.PI 180)) b.velocity.x Math.cos(rFireAngle) 385 b.velocity.y Math.sin(rFireAngle) 385 ... if (FlxG.mouse.pressed()) var p FlxPoint new FlxPoint(FlxG.mouse.screenX, FlxG.mouse.screenY) var angle Number FlxU.getAngle(new FlxPoint(player.x, player.y), p) 90 fireBullet(player.x, player.y, angle) ..."} {"_id": 41, "text": "How would you recommend I get started with ActionScript 3? I wanted to make Flash games so I bought the book \"Flash Games Development with AS3.\" I did the 'hello, world' program by trace and addChild (or something like that). But the problem was, instead of understanding what I was writing, I was just copying and pasting those lines of code. I felt it wouldn't work that way, and as the book had asked the learners to know at least some Java Javascript, C C , I didn't go any further. Now, I want to start again (and yes, I still don't know Java or C programming). What would you recommend for me? Thanks )"} {"_id": 41, "text": "Walk to nearest attackable range node My game has 3D environment which is partitioned in 2d cells(nodes). I have implemented A for path finding. Now I am just breaking my head to how to implement the algorithm to move the hero to the nearest attackable range node point when the enemy is out of attack able range. Which means, it should satisfy two conditions Target whithin attackable range No obstacles in between the target and attacker See below picture (pardon for my bad drawings) Brown boxes are obstacles Attacker hero is in the cell highlighted with Turquoise color dot, the circle is the radius size of the model. Target is the red dotted color cell, surrounded with red color circle to indicate the size of the model Green circle is the radius where hero has to move to some where inside that location to attack (its the radius of hero's attack range) Blue dots are the A path to reach from hero position to target position When the player issues attack command, hero should move to the nearest attack able node and start attacking. Finally I thought of below algorithm Calculate radius to scan This is the sum of attacker radius attacker weapon radius target radius Get nodes fall within the radius (from step 1) from targets position Find path from attacker to target using A Keep walking in the path (from step 3) check if current node is in the scanned nodes (from step 1) If true, Check that no obstacle are in between If true, attack, if false keep walking (repeat step 4) If we put together the algorithm and the figure1 The A gets the path of 9 node to reach the target After moving 5 steps, it enters the attackable range, since there is obstacle between the target, it take two more steps where it finds no obstacles and stats attacking. I am not sure if this is the optimized method to achieve this but I am not getting alternative solution. Very particular to the steps 2 5 which looks little weird and process intensive to me. I am using actionscript 3 and Flare3D (Stage3D API)"} {"_id": 41, "text": "Export information to a custom file type from Air So I have an engine (air application) that basically (for now) is loading some windows on the screen stage, and you can drag them around. And later on, I'll be able to add other objects onto the stage. How would I export any kind of information (like co ordinates or sizes of windows) out of my application to an external custom file. And then I would use that file to reload a previous project if I were to re load the engine. I'm working in AS3 Air and in FlashDevelop. Thanks for the help and time. If anymore information is needed please let me know. Cheers."} {"_id": 41, "text": "Efficient Sprite Batching Am considering porting over from XNA to the Stage3D API's (Molehill). So as a performance examination I've implemented sprite batching, but the performance is not all that great, while with XNA i can easily draw up to 500 000 quads but with my Molehill implementation i can draw around a measly 1000 quads and while a rather dramatic performance difference was expected on the CPU side this is due to being GPU bound. So currently the implementation is as follows. set render states let texture be null let batchSize be arbitrary for each sprite in queue if texture is not sprite texture or buffers are full upload vertex data to index buffer upload index data to vertex buffer bind texture draw triangles flush vertex data flush index data add sprite vertices to vertex data add sprite indices to index data end upload remaining vertex data to vertex buffer upload remaining index data to index buffer draw remaining triangles flush data The bottleneck is uploading the buffers, but as for a better implementation I'm hoping for a discussion here. Cheers. Revision One optimization that comes to mind is to persist the index buffer, since the indices are predictable and will always follow the same format. Am going to benchmark that now. Caching the index buffer had no noticeable performance gains, so in an effort to try to understand where the bottleneck is, I ported it over to C XNA, ever so slightly slower than Microsoft's implementation but still has a GPU capacity over 500 times more than the Molehill implementation. Is Molehill simply an extremely bad abstraction layer?"} {"_id": 41, "text": "Workflow with Flash Pro CS6 and FlashDevelop Using fla and swc to store assets I am using this tutorial http www.flashdevelop.org wikidocs index.php?title AS3 FlexAndFlashCS3Workflow In the past older versions of Flash Pro I was able to complete these steps right click on the symbol in the Library panel, select \"Linkage...\" dialog, check \"Export for ActionScript\" and fill in the symbol name (ie. MySymbol design or assets.MySymbol design), do not change the base class (ie. flash.display.MovieClip). Right now, I am stuck at that part. Any hints? What I wish to do is Use fla for the artist to store assets. Publish to swc Extract the assets in FlashDevelop by creating an instance of their class. ... How is this done in CS6? To clear things up, this is what I see when I right click a Flash symbol"} {"_id": 41, "text": "Is there any way to change the layering of objects in Actionscript 3 without altering the run order? I'm making a simple platformer in Adobe Animate, and I need the player to be layered in front of the stage because of a gimmick in the game. Unfortunately, whenever I change the layering order, it also seems to change the order that AS3 runs the instances. Is there any way to change the layering order without affecting the instance order, or vice versa? I'm only just starting with programming, so please bear in mind that I probably won't understand many of the technical terms. Thanks in advance!"} {"_id": 41, "text": "What is a good approach for making a relationship between the HUD and Environment? What is an elegant common way to build a relationship between the game scene environment world and the HUD that usually sits on top of it? I have thought about this for a while, and though there are ways to accomplish this that are easy to implement, they always seem to expose too much unrelated information between the two, or end up being too coupled. An example of this that I have used in the past would be to simply pass reference from the HUD to the Environment and vice versa (which is obviously not a good apporach for many reasons, especially when aiming for low coupling). What I want to end up with is a clean, uncoupled way to do things like From the HUD reference and manipulate objects within the environment, change the state of the Environment itself. From the environment update the HUD to reflect the current state of the environment. Maybe passing reference between the two is the way to go about this, but I feel like there's some pattern that I am missing for this type of task. Any insights into past experience and implementations concerning this type of problem would be very helpful."} {"_id": 41, "text": "How to set blur on mouse over and remove on mouse out in AS3? How can I do it? I want to active glow when the mouse is over a Sprite and remove it when the mouse is out. Is it possible? I have the following code var myGlow GlowFilter new GlowFilter() myGlow.color 0xFFFFFF myGlow.blurX glowMobilha.blurY 20 var miniatura MovieClip scene.d1 link miniatura.addEventListener(MouseEvent.CLICK, function(e Event) void MainSoundManager. sm.stopAllSounds() GameManager.loadSection(link, false) ) miniatura.addEventListener(MouseEvent.MOUSE OVER, function(e Event) void miniatura.filters myGlow miniatura.gotoAndStop(2) control.visible true controle.gotoAndPlay(2) ) miniatura.addEventListener(MouseEvent.MOUSE OUT, function(e Event) void miniatura.gotoAndStop(1) control.visible false control.gotoAndStop(1) ) miniatura.buttonMode true I set the blur at miniatura.addEventListener(MouseEvent.MOUSE OVER, function(e Event) void miniatura.filters myGlow miniatura.gotoAndStop(2) control.visible true controle.gotoAndPlay(2) ) How can I \"hide\" the blur at miniatura.addEventListener(MouseEvent.MOUSE OUT, function(e Event) void miniatura.gotoAndStop(1) control.visible false control.gotoAndStop(1) ) UPDATE I think I found the solution in the following code miniatura.addEventListener(MouseEvent.MOUSE OVER, function(e Event) void glowMobilha.alpha 1 miniatura.filters glowMobilha controle.visible true controle.gotoAndPlay(2) ) miniatura.addEventListener(MouseEvent.MOUSE OUT, function(e Event) void glowMobilha.alpha 0 miniatura.filters glowMobilha controle.visible false controle.gotoAndStop(1) ) is it the best solution?"} {"_id": 41, "text": "change the position of f3d objects randomly in action script I have a f3d object and have different boxes to place the parts of the f3d objects.When i click on the button change the position of the boxes randomly. How it possible?This is the code for random array. private function init(e Event null) void removeEventListener(Event.ADDED TO STAGE, init) entry point var startArray Array generateNumberArray(10) var randomArray Array randomArray(startArray) trace(\"startArray \" startArray) trace(\"randomArray \" randomArray) generate Array of numbers by length param length return Array of numbers public function generateNumberArray(length int) Array var numberArray Array for (var i int 0 i lt length i ) numberArray i i 1 trace(\"ersexrfegtdrgtdrygtfr\" numberArray i ) return numberArray generate randomly mixed array by input array param inputArray simple not mixed array return Array mixed array public function randomArray(inputArray Array) Array var randomArray Array var tempArray Array for (var i int 0 i lt inputArray.length i ) tempArray.push(inputArray i ) while (tempArray.length) var randomNumber int Math.round(Math.random() (tempArray.length 1)) get random number of left array randomArray.push( tempArray randomNumber ) tempArray.splice(randomNumber, 1) trace(\"randommmmmmmmmmmmmmmmmmmmmmmm\" randomArray) remove randomed element from temporary aarray tempArray null delete tempArray return randomArray public function loadCompleteEvent(e Event) void if (stage) init() else addEventListener(Event.ADDED TO STAGE, init) my boxes (want to change the position randomly of these boxes) Box2.setPosition(57.49752426147461, 2.987499237060547, 10) Box3.setPosition(57.49752426147461, 26.987499237060547, 10) Box4.setPosition( 48.50247573852539, 2.987499237060547, 10)"} {"_id": 41, "text": "How can I disable the forward back buttons in AS3? How can I disable the Flash player forward and back button in AS3? These buttons make it possible to cheat in my game by moving from level to level."} {"_id": 41, "text": "Placing items randomly in a dynamically generated terrain I'm currently working on a 'Tiny wings' like game. I've already asked about the angle of the items in curved lines and i solved (thank you for responses),i'm currently placing the items in random positions, but the terrain it's dynamically and i don't get this working. I've a vector with the points of the terrain, and i'm doing something similar to this (Iterating trough vector) if( SPManager amp amp i 15 0 amp amp i ! 0 ) if ( settings.specialPoints amp amp currentPoints lt settings.specialPoints ) SPManager.addPoint( hillsPosition i .x , hillsPosition i .y ) currentPoints But it isn't working as i expected. It isn't displaying the right number of items (Always shows less than i specified). How do i should place the items? Thanks )"} {"_id": 41, "text": "How can I output multiple sprite sheets from a single .fla? I have to produce out three sprite sheets of differing sizes. To do so, I have three different .fla source files. Obviously maintaining three files takes more time than maintaining one is there some way that I can use one .fla and produce three differently sized sprite sheets?"} {"_id": 42, "text": "How to spawn objects and control the content in each spawn I'm using unreal engine and would like to spawn multiple actors and control the text in each spawned actor. How can this be achieved in unreal engine?"} {"_id": 42, "text": "How to use X,Y, and Z instead of Pitch, Roll and Yaw I'm learning Unreal engine, and I'm rather disappointed because it uses pitch roll and yaw instead of the standard x, y, and z that I'm used to. Is there any way to convert this easily, or is there a preference, or do I have to get used to using y,z,x, instead of x,y,z."} {"_id": 42, "text": "Nonsense error in the overlap between 2 warriors and a tower I have a project where 1 warrior is generated every 5 seconds. This warrior as it is generated tries to follow a path that contains 4 target points. Between the target point 1 and the target point 2 there is a tower. Then the warrior is going to meet the target point 2, but as soon as he hits the tower, he fails to reach the target point 2 and goes to meet it until it is destroyed. The part of the code circled in pink was to be executed only after the destruction of the tower (when the life of the tower reaches 0), which does not happen, but the worst thing is that when it executes, it does not execute completely, the tower is not destroyed, but the warrior moves toward target point 2. Result in game Look that the impression occurs for the two warriors. Maybe the message log will help I decrease the delay time of the loop to 0.1 and as there is no time for the second warrior to overlap the tower along with the first warrior, everything works correctly. The problem occurs when more than one warrior reaches the tower simultaneously."} {"_id": 42, "text": "Correct use of AttachActorToActor ue4 I'm trying to stick some blocks together, but frankly I have no idea what I'm doing. I spawn 2 blocks during run time, and if they have an on hit event they're supposed to stick to each other. It struck me that I'm not even sure if that's what attach does, and maybe it has some completely different meaning. with the following blueprints, I'm getting all sorts of errors like quot already attached quot and quot can't attach actor to actor, already attached quot https imgur.com a 16Zz2eS Any help appreciated"} {"_id": 42, "text": "When and how often does Epic charge me royalties on my game? I want to know about that 5 royalties that Epic charges for the Unreal Engine if I sell games above 3000. What about if my game just made 300? Do I still need to pay 5 royalties to them? And how many times should I pay? For example, I made a game that was sold for above 3000 so I paid 5 royalties but do I still need to pay it again for the same game?"} {"_id": 42, "text": "Drawing roads on heightmaps I've been running into walls for the past week or so on my toy project in UE4. My goal is to draw procedural roads on a procedural landscape (eventually getting to intersections and buildings). The landscape is generated with libnoise and the roads are generated with a slightly modified version of the algorithm found here. But I'm having issues draping the roads on the landscape and I can't find any straightforward algorithmic way of doing it. You can see my problem below the geometry of the road intersects the geometry of the landscape. In short, given The landscape index buffer The landscape vertex buffer Every road segment's X,Y,Z coordinate How do I modify the underlying vertex index buffer so that the landscape \"wraps around\" the roads?"} {"_id": 42, "text": "Real time fluid simulation? I'd like to create a system in Unreal Engine 4 with glob like fluids which interact with the environment, like the gel in Portal 2. Here's a GIF of the gel from that (search that I used to bring up similar images) I was wondering how it might be possible to do something like this? An in depth guide would be nice as I have a mostly basic understanding of blueprints in UE4, although I know it's a lot to ask for. If you know how I can achieve this, please let me know. Thank you! ) P.S The quot fluid quot stains don't need to give effects such as speed like you saw in the GIF, but I would still like the liquids to stain wherever they hit. )"} {"_id": 42, "text": "Can I add extra widgets to a child widget in UMG UE4? I have a widget base class and I would like to reuse (logic and wigdets as well) it. I created an empty widget and set the parent class to the base class I would like to inherit from in the class settings. Works fine. But when I am trying to add any widget on top the pre existing ones just disappear, they get overridden by the children, I guess. I found this post for a feature request, but it is quite old. Just wondering if it is possible to add extra widgets without getting rid of the parent ones?"} {"_id": 42, "text": "How to change the mesh of the character in UE4? I made a Bellsprout mesh in Blender, exported it as an FBX file, and imported it into UE4. I can insert it in the stage without problem, but I would like to use this Bellsprout mesh to replace the mesh of the built in character. Even clicking and dragging will not replace the mesh I've looked into importing between blender UE4 https wiki.unrealengine.com Static Mesh from Blender And also about mesh editing https docs.unrealengine.com en us Engine Content Types StaticMeshes Editor I also looked at some questions in this forum Changing rendering in UE4 and Making only parts of a mesh destroy in UE4 To see if the question had not already been asked."} {"_id": 42, "text": "For Visual Studio Community 2017, 'Unreal Engine Installer' option is not available On Visual Studio Community Installer, I cannot find 'Unreal Engine Installer' under 'Desktop Developemtn with C ' 'Optional'. According to the tutorials I am learning, the 'Unreal Engine Installer' should be availbl.e I have Visual Studio installed on 'C ' and Unreal installed on 'H ' can this be the problem?"} {"_id": 42, "text": "How can I change the dimensions of collision volumes showed in UE4's physics asset tool? How can I change the dimensions of the capsule for one bone in the physics assets tool? The problem is that bones not connected by joints have overlapping collision volumes in the mannequin that comes with the starter content, which causes those body parts to apear dislocated or out of place when the simulation is running. For instance in this image the pelvis and the middle bone in the spine (Spine 2) are overlapping. So, when the simulation runs Pelvis and Spine 2 get pushed apart reducing the overlapping to a contact point."} {"_id": 42, "text": "How to use X,Y, and Z instead of Pitch, Roll and Yaw I'm learning Unreal engine, and I'm rather disappointed because it uses pitch roll and yaw instead of the standard x, y, and z that I'm used to. Is there any way to convert this easily, or is there a preference, or do I have to get used to using y,z,x, instead of x,y,z."} {"_id": 42, "text": "Radial circle placement of meshes How to place 10 static meshes in circular pattern so they are equaly aligned from the center ?"} {"_id": 42, "text": "Blueprint script executed on tick but not on construction Below, on event tick, I am initializing a map of images once, which works fine (remember we are in a graph for a widget blueprint here). Z Cursor Images is the map of the images. The keys in the map are an enum, and I am adding first an image for the default cursor, and then an image for when the player is targeting an object that she can pick up. Now, when I do the same in the construction script (Event Construct), it does not throw an error but later I cannot access the textures from the map. IsValid returns false for them... So why is the map filled on tick but not on Event Construct? And how do I solve this?"} {"_id": 42, "text": "GetUserWidgetObject returns null I have a widget component inside of my character ABCharacter.h ... UPROPERTY(VisibleAnywhere, Category UI) class UWidgetComponent HPBarWidget ... ABCharacter.cpp ... AABCharacter AABCharacter() Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick true HPBarWidget CreateDefaultSubobject lt UWidgetComponent gt (TEXT(\"HPBARWIDGET\")) HPBarWidget gt SetupAttachment(GetMesh()) I checked HPBarWidget is null and it wasn't if (HPBarWidget nullptr) UE LOG(ArenaBattle, Error, TEXT(\"NULL\")) HOWEVER, When I try to get the widget object, it said it's null. if (HPBarWidget gt GetUserWidgetObject() nullptr) UE LOG(ArenaBattle, Error, TEXT(\"NULL\")) it printed NULL What causes this returns null? I can clearly see I have a WidgetComponent that exists in my character's tree, and HPBarWidget wasn't null too. I struggled this already hours and couldn't find any related issues. What did I wrong? Using 4.24.3."} {"_id": 42, "text": "Unreal Engine 4 AI MoveTo always fails I try to move a character with AI MoveTo, but it always fails. I tried to do this with standart ThirdPersonController and a custom one. The blueprint is simple When the event happens, it starts printing \"failed\". I checked many times if I have a NavMesh on the level or any other problems with it, but I don't think there are any problems with that. Any ideas?"} {"_id": 42, "text": "Make a decal a physical object? Is there a way in the UE4 to make a decal such as a blood decal and give it a physical object? I want to do it so that I can add a sound affect when the player walks on the physical object, a box trigger wont work as when the player stands on it the sound will keep playing and repeating even if the player isn't moving."} {"_id": 42, "text": "Tank turret animations I don't know if this question is more of Blender 3D or gamedev Unreal question, but I decided to ask here first. What I want to do is make a character, simple robot. The bottom part rides around on wheels, controlled by keyboard, while the top part is a turret that turns towards player cursor (which works as a crosshair). I made the model in blender, using only two bones, one for the bottom part and one for the turret. I created 4 poses for aiming each direction. Then, in Unreal, I created 2D aim offset (as I only need one dimension). And after some coding, it works... almost. When I aim forward, and then to the right, it transitions, nice. Then towards the back, also works. But if I then move to the left, instead of rotating extra 90 degrees, the turrent rotates back forward and then to the left. How can I fix it? Is there some settings in Unreal that I could use, or should I create the model in blender differently? Is the whole rig bones solution not gonna work? TLDR I want the turret on my robot to rotate infinitely to whatever I aim at."} {"_id": 42, "text": "How to create smoke that spreads outward in all directions? I saw many tutorials about smoke grenade but they just use volumetric smoke. I want to make something like the smoke grenade in PUBG, where the smoke spreads in all directions how to do that? The Unreal Engine 4 smoke grenade throws out smoke in a particular direction, like this But I want something more like PUBG's that spreads smoke evenly in all directions"} {"_id": 42, "text": "Switch from left click to right click to make character walk in the Top Down Example, in UE4? When creating a new project in the Unreal Engine 4, you can choose to create a project already with some added features and things (Top Down Example) This project has a character (which I changed its appearance) and it moves around the map when I click the left mouse button I looked at the blueprints of the project, but I did not identify where the command is that makes the character walk, so I'd like it to walk when I right click. Alls blueprints of project M Cursor Decal TopDownCharacter TopDownController TopDownGameMode The circled blocks of reds are the ones I suspected could be where I should make the modification, but no information on them gave me the certainty that that was where I was supposed to change. I still do not create projects in C programming mode, because I do not have Visual Studio 2017. Some links from websites where I spent before coming here and that can help you to help me https docs.unrealengine.com en us Engine Blueprints https www.youtube.com watch?v EFXMW UEDco The video is 2015, so although it's good, I did not take it so well, because I know that with all this time that has already happened, a lot is different. Sorry for any translation errors, I'm not English speaker."} {"_id": 42, "text": "ue4editor.exe GPU selection Even though I set ue4editor.exe to use integrated graphics on my laptop, it somehow ends up using the discrete nvidia gpu is there a way to set the preferred gpu with the unreal suite?"} {"_id": 42, "text": "How do you spawn a component from a class in UE4? Background I'm working on a shooter game at the moment and I'm trying to spawn an Actor Component for the weapon currently in use, in order to have less Actors to keep track of. The problem with this is that I can't easily switch out components on the fly, without making a separate function for each weapon. Question Is there currently any way to spawn a component with blueprints from a class like you would do with an Actor?"} {"_id": 42, "text": "Make my Character face the same way as my Camera as I rotate the camera Before posting, I've already tried parenting the camera to the Character mesh head and setting controller yaw, that didn't work, in fact it invalidated my blueprint to set my Mouse X and Y for the pitch and yaw that allowed me to move my camera in the first place. So I need a different method to make my character follow the way my camera is facing whenever I rotate, otherwise when I turn around I just face my Character."} {"_id": 42, "text": "When and how often does Epic charge me royalties on my game? I want to know about that 5 royalties that Epic charges for the Unreal Engine if I sell games above 3000. What about if my game just made 300? Do I still need to pay 5 royalties to them? And how many times should I pay? For example, I made a game that was sold for above 3000 so I paid 5 royalties but do I still need to pay it again for the same game?"} {"_id": 42, "text": "Lightmap not working? So I've been exporting and re exporting my mesh from Blender and importing it into UE4 over and over again. For some reason, even after I've generated the light map in Blender, renamed both UV maps, re applied the UV maps, baked the textures, then changed the Light Map resolution in UE4 to 512, the Light Map Coordinate to 1, and built the lighting, my mesh is still black and I can't figure out why since I've tried literally everything I could find in my research. In the image below, the left mesh is what it's supposed to look like, and the right mesh is what it looks like after building the lighting. Please help me with this, thank you."} {"_id": 42, "text": "UE4 Want my landscape to be unlit BUT catch shadows from objects Here is my problem, I have a landscape that was created through photogrametry. I already has strong shadows on it's diffuse texture so I don't want it to be affected by my virtual sun. What I do want though is for objects added in my scene to receive shadows from the landscape, and for the objects to cast shadows onto the landscape. To do that I matched my virtual sun as close as I could with the shadows on the diffuse texture of the landscape. How do I keep my landscape unlit yet able to receive and cast shadows from and to other objects?"} {"_id": 42, "text": "How do you spawn a component from a class in UE4? Background I'm working on a shooter game at the moment and I'm trying to spawn an Actor Component for the weapon currently in use, in order to have less Actors to keep track of. The problem with this is that I can't easily switch out components on the fly, without making a separate function for each weapon. Question Is there currently any way to spawn a component with blueprints from a class like you would do with an Actor?"} {"_id": 42, "text": "Multiple errors on brand new C project I've just started a brand new project and created a created a new C Character class. However Visual Studio 2017 shows 140 errors. The project still builds fine, however the syntax highlighting and errors are very intrusive. Here are some examples of the errors on the BaseCharacter.cpp class I just created class \"UObject\" has no member \"BeginPlay\" class \"UObject\" has no member \"Tick\" class \"UObject\" has no member \"SetUpPlayerInputComponent\" on multiple '.h' files this declaration has no storage class or type specifier for all ' .generated.h' files cannot open source file \" ClassName .generated.h\" Is this a problem with my intellisence or the project itself? I haven't changed any of the code that was generated by Unreal."} {"_id": 42, "text": "UE4 Image Asset From String I have a custom widget with an image component. I want to change the image dynamically based on a string from a data table. How do I do this?"} {"_id": 42, "text": "How can I add these bones to my meta human? Or is there a way I can make virtual bones count when retargetting? Paid for animations thinking they would be fine and they mostly are but... the hands are using these IK bones that I do not have. Is there a way I can add the bones to my meta skeleton within unreal? I tried creating virtual bones but they dont seem to come up in the retarget manager ( Also, I can only seem to add one virtual bone to the root whereas both the foot and hand IK root bones are parented to the root bone here. Any help would be massively appreciated!"} {"_id": 42, "text": "Switch from left click to right click to make character walk in the Top Down Example, in UE4? When creating a new project in the Unreal Engine 4, you can choose to create a project already with some added features and things (Top Down Example) This project has a character (which I changed its appearance) and it moves around the map when I click the left mouse button I looked at the blueprints of the project, but I did not identify where the command is that makes the character walk, so I'd like it to walk when I right click. Alls blueprints of project M Cursor Decal TopDownCharacter TopDownController TopDownGameMode The circled blocks of reds are the ones I suspected could be where I should make the modification, but no information on them gave me the certainty that that was where I was supposed to change. I still do not create projects in C programming mode, because I do not have Visual Studio 2017. Some links from websites where I spent before coming here and that can help you to help me https docs.unrealengine.com en us Engine Blueprints https www.youtube.com watch?v EFXMW UEDco The video is 2015, so although it's good, I did not take it so well, because I know that with all this time that has already happened, a lot is different. Sorry for any translation errors, I'm not English speaker."} {"_id": 42, "text": "Unreal engine project not responding to key binding changes I'm getting started with learning Unreal development, and I've created a new project based off the FPS C template. I've changed the key mappings inside the DefaultInput.ini, rebuilt the Visual Studio solution, and rebuilt the project in the Unreal editor, but none of my changes are taking effect. What step am I missing?"} {"_id": 42, "text": "Problem with progress bar visibility I have a code with several elements. One of these elements I would like you to initiate hidden. So I did, set for the progress bar to start hidden. It started to go wrong when and I was calling its visibility (bind) the same stopped starting hidden. I did a test with this problematic progress bar and another one created on time The progress bar that has the visibility setting function appears even if I set it to start hidden As I said, I believe that this strange behavior is due solely and exclusively to the fact that there is such a function Even though I have created a boolean variable that imposes a condition, the bar insists on appearing The variable quoted initiates by default as false I thought the blame could be on the return knot, but as you can see in the fourth image, even putting \"hidden\", the progress bar appears anyway."} {"_id": 42, "text": "UE Sequencer Foot slide with character movement What is the best way to implement the character movement on the sequencer so there is no foot slide? I would go with Root Motion but the animations I have are on place. Thank you"} {"_id": 42, "text": "Elements of a widget blueprint do not appear if I click on simulate I made a widget that contains 2 minimaps and 2 texts related to a character's variables. When I click the play button (Selected Viewport) everything happens fine Focus where I circled in pink. It turns out that when I click the Simulate button, these two texts do not appear, but the minimaps do I did a test by first clicking the play button (Selected Viewport) and then I ejected the character (which for me is the same thing as simulating, except without closing and opening the game) and the texts appeared, so my problem is only when I'm done start simulating. I would like to know how to make these 2 texts appear even if I click on simulate instead of play."} {"_id": 42, "text": "How can I change the dimensions of collision volumes showed in UE4's physics asset tool? How can I change the dimensions of the capsule for one bone in the physics assets tool? The problem is that bones not connected by joints have overlapping collision volumes in the mannequin that comes with the starter content, which causes those body parts to apear dislocated or out of place when the simulation is running. For instance in this image the pelvis and the middle bone in the spine (Spine 2) are overlapping. So, when the simulation runs Pelvis and Spine 2 get pushed apart reducing the overlapping to a contact point."} {"_id": 42, "text": "Unwanted blendspace bone displacement in UE4 My characters hands quot fall off quot in the blendspace between the animations. Looking for a way to fix it, if anyone has any ideas."} {"_id": 42, "text": "Unpack the pak file Unreal Engine So I have the encryption key. This is stressed so much to have it. Well, I have it. Where do I use it? Unrealpak does not seems to offer an option to supply the encryption key, if your pak is encypted the unpackaging simply fails."} {"_id": 42, "text": "Drawing roads on heightmaps I've been running into walls for the past week or so on my toy project in UE4. My goal is to draw procedural roads on a procedural landscape (eventually getting to intersections and buildings). The landscape is generated with libnoise and the roads are generated with a slightly modified version of the algorithm found here. But I'm having issues draping the roads on the landscape and I can't find any straightforward algorithmic way of doing it. You can see my problem below the geometry of the road intersects the geometry of the landscape. In short, given The landscape index buffer The landscape vertex buffer Every road segment's X,Y,Z coordinate How do I modify the underlying vertex index buffer so that the landscape \"wraps around\" the roads?"} {"_id": 42, "text": "How to get UE4 to correctly put my bundle identifier for iOS projects? Each time I create a new project UE4 adds a generic bundle identifier to the iOS platform settings, that I always have to change to com.myname. PROJECT NAME in order to be able to run the newly created project. So, I wonder how can I make UE4 to correctly auto detect this field from the picked provisioning profile. I was thinking something like putting BUNDLE IDENTIFIER (including the square brackets) but the editor crashes when I put that in the bundle identifier field."} {"_id": 42, "text": "Unreal 4 How to access and iterate through the polygons of a mesh? I'm newbie with Unreal Engine 4. I need to create a function which calculates the volume of a mesh, based on the following example https n e r v o u s.com blog ?p 4415 To achieve that I created an actor blueprint containing a cone. I then created a function to calculate the volume of a tetrahedron composed by a polygon plus the center point of the scene, like that Now I want to iterate through each of the polygons composing the cone actor, one by one, and use the above function to calculate the total volume of the cone. I found a possible beginning for a such iteration However I'm unable to find a way to create a loop which iterate through the Triangles array and extract the 3 vertices of each triangles composing the mesh. I would be grateful if someone explained to me how to implement a such loop. Or, if so, how to access correctly to the actor mesh vertex buffer object, and to iterate through each of the polygons composing it."} {"_id": 42, "text": "Nonsense error in the overlap between 2 warriors and a tower I have a project where 1 warrior is generated every 5 seconds. This warrior as it is generated tries to follow a path that contains 4 target points. Between the target point 1 and the target point 2 there is a tower. Then the warrior is going to meet the target point 2, but as soon as he hits the tower, he fails to reach the target point 2 and goes to meet it until it is destroyed. The part of the code circled in pink was to be executed only after the destruction of the tower (when the life of the tower reaches 0), which does not happen, but the worst thing is that when it executes, it does not execute completely, the tower is not destroyed, but the warrior moves toward target point 2. Result in game Look that the impression occurs for the two warriors. Maybe the message log will help I decrease the delay time of the loop to 0.1 and as there is no time for the second warrior to overlap the tower along with the first warrior, everything works correctly. The problem occurs when more than one warrior reaches the tower simultaneously."} {"_id": 42, "text": "What does the update button in the Unreal Engine launcher actually update the engine to? Unreal Engine 4 seems to have a very handy way of managing different versions of the engine mainly you get to keep several copies and choose which one to launch. That said, not having used the new launcher recently I see that I am quite behind in engine versions but where previously I had to download the new version (as can be seen by my several copies of the engine) there is now an update button on the engines. My internet is really slow so I'm curious if anyone could tell me what the update button actually does? For example, in the circled one, will it update to some 4.2.x minor version or will it update to the 4.7.2 version that I can freshly install? If I can save some bandwidth by upgrading to 4.7.2 over downloading a fresh copy that would be ideal."} {"_id": 42, "text": "Unreal Engine 4 DefaultInput.ini mappings not showing in editor The mappings from DefaultInput.ini are not showing up in the editor. I had originally added them in the editor project settings, but it lost the mappings except for 2 of them Jump and Reset VR. They still show up in the DefaultInput.ini file. How do I get the editor to recover them (or read them from the .ini file?"} {"_id": 42, "text": "Unreal Engine Ubuntu Failed to import video, unknown file extension I've been reading tutorials and guides on getting video file playback in Unreal. I have media player materials created and textures. I'm having issues importing video files to Content Movies directory. When I use the import manager the files don't show. Drag and drop says its an unknown file extension for MP4, MWV, and other formats I tried like AVI even though I know AVI is not supported. So I wonder if maybe I'm missing a plugin for Unreal 4.8 4.9 in Linux?"} {"_id": 42, "text": "Map with media texture not packaging I have a simple map with a Big sphere and a pawn inside it. I use media texture and media player to play 360 video on it. But when I try to package it for windows 64 it fails while it tries to cook the map. Yes all the videos are copied to Content Movies first and then imported to UEProject as asset later. This is very crucial to our project. One of our developer have already started to build the solution in Unity just in case if packaging issue does not resolve with media player in unreal. Please help!"} {"_id": 42, "text": "How to support importing .uasset files in game for content creators(UE4)? I would like to support importing clothes(as SkeletalMeshes) and props(as StaticMeshes) as uasset files into game for content creators, which obviously have not been packaged with the game. Basically I am looking for a clean modding pipeline. EDIT TLDR Is it possible to load .uasset files with StaticLoadObject() into game and use assets from it after the game has been packaged? Or does it only work with packaged files? If not what function do you recommend for that purpose? not TLDR Bringing in stuff does work well in the editor, using Rama's LoadObjectFromAssetPath, just by right clicking my asset in Content Browser copy reference and copy pasting the result to the path variable of the LoadObjectFromAssetPath blueprint node. Well, I am not sure if it is going to work at runtime... So I used my favourite search engine and put in some keywords and bumped into this. Then I wrote some code(Blueprint Function Library) void UFileDialogOpener LoadFile(FString from) auto result StaticLoadObject(UStaticMesh StaticClass(), NULL, from) GEngine gt AddOnScreenDebugMessage( 1, 150.0f, FColor Red, quot from quot from) if(result)GEngine gt AddOnScreenDebugMessage( 1, 150.0f, FColor Green, quot name quot result gt GetName()) else GEngine gt AddOnScreenDebugMessage( 1, 150.0f, FColor Green, quot no result quot ) auto meSkelMesh Cast lt UStaticMesh gt (result) if(meSkelMesh)GEngine gt AddOnScreenDebugMessage( 1, 150.0f, FColor Red, meSkelMesh gt GetName()) else GEngine gt AddOnScreenDebugMessage( 1, 150.0f, FColor Red, quot no mesh quot ) As per the debug messages StaticLoadObject does not find anything. I tried feeding it the both of the results of righclicking my asset in Content Browser and choosing either copy reference and copy path. Neither of them yielded any result. Not sure where I am messing up. Anyways, just wondering if anyone can recommend a better way of doing this(code, plugins etc)?"} {"_id": 42, "text": "Create a instance of a C class within a blueprint I'd like to create an instance of a C class in a blueprint. That's my current approach, but the instance is None. Why?"} {"_id": 42, "text": "Unreal Engine 4 DefaultInput.ini mappings not showing in editor The mappings from DefaultInput.ini are not showing up in the editor. I had originally added them in the editor project settings, but it lost the mappings except for 2 of them Jump and Reset VR. They still show up in the DefaultInput.ini file. How do I get the editor to recover them (or read them from the .ini file?"} {"_id": 42, "text": "How to create smoke that spreads outward in all directions? I saw many tutorials about smoke grenade but they just use volumetric smoke. I want to make something like the smoke grenade in PUBG, where the smoke spreads in all directions how to do that? The Unreal Engine 4 smoke grenade throws out smoke in a particular direction, like this But I want something more like PUBG's that spreads smoke evenly in all directions"} {"_id": 43, "text": "Display a variable in the UI I have been searching and searching for an answer to this question but nobody seems to be helping me. I have wasted the past two hours trying to figure out how to do this, so please help me out here. I am making a FPS game in Unreal Engine 4, and I want to display ammo. I can do that fine, but changing the text of the UI displaying the ammo is turning into a nightmare. I need to access the text label variable Inside of the blueprint that handles the actual gun firing From there I should be able to adjust the text to match what my ammo is. Unfortunately, no matter what I try, I cannot change the variable in my blueprint. I can't even make the variable public to begin with! What do I need to do to accomplish this?"} {"_id": 43, "text": "Creating a GUI Countdown Timer Unity5 This was originally posted as a follow up comment to https stackoverflow.com questions 30714357 guitext in unity 5 need an alternative , but I'm asking it here as a dedicated question as per the community's recommendation. What I'm trying to do display GUI Text on screen as a countdown timer that counts down in real time What I've done so far watched YouTube tutorial \"Unity Scripting Tutorial 7 A Countdown Timer\" by VR Enthusiast.1 GameObject UI Text renamed TimerText Wrote the Timer script in C using UnityEngine using UnityEngine.UI using System.Collections public class Timer MonoBehaviour public float seconds 59 public float minutes 0 void Update() if (seconds lt 0) seconds 59 if (minutes gt 1) minutes else minutes 0 seconds 0 GameObject.GetComponent lt GUIText gt ().text minutes.ToString(\"f0\") \" 0\" seconds.ToString(\"f0\") else seconds Time.deltaTime if(Mathf.Round(seconds) lt 9) GameObject.GetComponent lt GUIText gt ().text minutes.ToString(\"f0\") \" 0\" seconds.ToString(\"f0\") else GameObject.GetComponent lt GUIText gt ().text minutes.ToString(\"f0\") \" \" seconds.ToString(\"f0\") placed the TimerText object in the GUI Text object reference Then I got this error \"MissingComponentException There is no 'GUIText' attached to the \"TimerText\" game object, but a script is trying to access it. You probably need to add a GUIText to the game object \"TimerText\". Or your script needs to check if the component is attached before using it. Timer.Update () (at Assets Timer.cs 40)\" I essentially placed The object GUI Text object itself (TimerText) as its own scripting reference in Unity's Inspector. Not sure where to go from here. Any advice on what I can do next? Any help would be appreciated."} {"_id": 43, "text": "CenterContainer makes my button too small I get the perfect width for my buttons, but CenterContainer overrides that value of theirs to make the button as wide as the biggest text length of the buttons when I put the buttons inside of the container godot 3.1"} {"_id": 43, "text": "How to make a scrollbar? I am making my own UI for my game, no libraries used, basic UI with simple controls and I am almost done. Now, let's say I need to display lots of information, controls or items which obviously won't fit in the screen space. I must use a scroll bar to achieve this task. But how does one make a scroll bar? I just don't understand how to do it. The concept for vertical and horizontal scrollbars is the same. Virtually there is a huge plain with data, but we can only display cut of it all in a such by such screen space. We use scrollbars to move that viewable rectangle across our giant plain. The scrollbar itself is a displayed line texture sprite on the side of the screen which has a button inside that we can interact with by moving it across the scrollbar. The button is dynamic, its size is relative to total item count and possible item count that can be shown in given space. Our button shrinks when there are more items added, expands when items are getting removed and the whole scrollbar disappears when all the items can be successfully displayed at once. I can't seem to find online tutorials on this matter. Perhaps it's so basic for everyone except me? Still can't wrap my head around it..."} {"_id": 43, "text": "Application toolkits like QT versus traditional game multimedia libraries like SFML I currently intend to use SFML for my next game project. I'll need a substantial GUI though (RPG strategy type) so I'll either have to implement my own or try to find an appropriate third party library, which seem to boil down to CEGUI, libRocket, and GWEN. At the same time, I do not anticipate doing that many advanced graphical effects. My game will be 2D and primarily sprite based with some sprite animations. I've recently discovered that QT applications can have their appearance styled so that they don't have to look like plain OS apps. Given that, I am beginning to consider QT a valid alternative to SFML. I wouldn't have to implement the GUI functionality I'd need, and I may not be taking advantage of SFML's lower level access anyway. The only drawbacks I can think of immediately are the learning curve for QT and figuring out how to fit game logic inside such a framework after getting used to the input update render loop of traditional game libraries. When would an application toolkit like QT be more appropriate for a game than a traditional game or multimedia library like SFML?"} {"_id": 43, "text": "Can't change anchor position and TextureRect size I'm making UI, and want to set anchor to middle of the image, but changing anchor from Layout Anchors Only or setting Anchor value directly doesn't work. The value was updated, but anchor point not moved at all. Is it bug or is there are something that I missed? Here's the node tree CanvasLayer Control TextureRect lt Anchor is not moving at all Using Godot 3.1.1. Also I can't find how to resize texture rect. I can set the min size, but change size doesn't work, the value immediately set back to original size. How to change the texture rect size?"} {"_id": 43, "text": "Logic only GUI library I'm not sure whether this place is the correct for asking this. If it's the wrong place I'm sorry, please tell me if so! I'm making a small game for fun which would uses an own engine with OpenGL and Vulkan as underlying renderer implementation. The engine itself is targeted for Mono .Net. Currently I'm not yet there but I'll come to the point where I'm pushed to implement some kind of GUI (I'm thinking ahead because of good design). I already searched the Internet for render independent GUI systems but I wasn't lucky yet. As result I thought about how I could implement the GUI on my own and came to the conclusion a independent implementation is needed which takes care only for layout, positioning of GUI objects with responding to inputs. another implementation is needed which only takes the results of calculations for rendering (the renderer) Before I start inventing the whole wheel new I simply want to know Is it a correct approach to doing it this way? Is there a different common approach doing what I described?"} {"_id": 43, "text": "How to make a scrollbar? I am making my own UI for my game, no libraries used, basic UI with simple controls and I am almost done. Now, let's say I need to display lots of information, controls or items which obviously won't fit in the screen space. I must use a scroll bar to achieve this task. But how does one make a scroll bar? I just don't understand how to do it. The concept for vertical and horizontal scrollbars is the same. Virtually there is a huge plain with data, but we can only display cut of it all in a such by such screen space. We use scrollbars to move that viewable rectangle across our giant plain. The scrollbar itself is a displayed line texture sprite on the side of the screen which has a button inside that we can interact with by moving it across the scrollbar. The button is dynamic, its size is relative to total item count and possible item count that can be shown in given space. Our button shrinks when there are more items added, expands when items are getting removed and the whole scrollbar disappears when all the items can be successfully displayed at once. I can't seem to find online tutorials on this matter. Perhaps it's so basic for everyone except me? Still can't wrap my head around it..."} {"_id": 43, "text": "How can I model a \"weapon overheating\" mechanic? I want to create a weapon overheating system very similar to the plasma rifle in Halo. You can watch a video of the plasma rifle firing. What I want to do is to create a flexible logic that can be used for multiple weapons for different in game feelings. Here is my proposed system Create a bar that is split from 0 100. Each bullet has a heat value as an integer. Every bullet adds this value to the bar. The bar has a cooldown set as some value per second. If the bar goes over 100 with any bullet fire the bullet still shoots but then the weapon is deactivated for a period defined as it's \"cooldown.\" Now this system is very simple but visually it will be very linear, with a simple growth and decay. I wanted to try to create a more exponential system that would mean the bar would jump quickly to the middle then remain and hover near the top hot bit of the bar for a long period to create a sense of anticipation just before it overheats. What would be a good formula to achieve that result?"} {"_id": 43, "text": "How do I render my own DirectX Stuff to a full screen WPF's DirectX surface? Basically Danny Varod seems to know as he posted it as an answer to this question Display a Message Box over a Full Screen DirectX application I think, theoretically this might work, but I have no idea how to actually do it. Since I'm also not allowed to post a comment under his comment nor am I allwoed to ask on meta about how to contact another user, I ask this as a normal question here How do I render my own DirectX Stuff to a full screen WPF's DirectX surface? For starters, I have no idea how to get the DirectX surface from a WPF window. If I had it, what do I have to take care of that the WPF rendering doesn't screw up my own rending or vice versa?"} {"_id": 43, "text": "Nifty popup fails to register I'm new to Nifty GUI, so I'm following a tutorial here for making popups. For now, I'm just trying to get a very basic \"test\" popup to show, but I get multiple errors and none of them make much sense. To show a popup, I believe it is necessary to first have a Nifty Screen already showing, which I do. So here is the ScreenController for the working Nifty Screen public class WorkingScreen extends AbstractAppState implements ScreenController Main is my jme SimpleApplication private Main app private Nifty nifty private Screen screen public WorkingScreen() public void equip(String slotstr) int slot Integer.valueOf(slotstr) System.out.println(\"Equipping item in slot \" slot) Here's where it STOPS working. app.getPlayer().registerPopupScreen(nifty) System.out.println(\"Registered new popup\") Element ele nifty.createPopup(app.getPlayer().POPUP) System.out.println(\"popup is \" ele) nifty.showPopup(nifty.getCurrentScreen(), ele.getId(), null) Override public void initialize(AppStateManager stateManager, Application app) super.initialize(stateManager, app) this.app (Main)app Override public void update(float tpf) jME update loop! public void bind(Nifty nifty, Screen screen) this.nifty nifty this.screen screen When I call equip(0) the system prints Equipping item in slot 0, then a lot of errors and none of the subsequent println()'s. Clearly it botches somewhere in Player.registerPopupScreen(Nifty nifty). Here's the method public final String POPUP \"Test Popup\" public void registerPopupScreen(Nifty nifty) System.out.println(\"Attempting new popup\") PopupBuilder b new PopupBuilder(POPUP) childLayoutCenter() backgroundColor(\" 000a\") panel(new PanelBuilder() id(\"List\") childLayoutCenter() height(percentage(75)) width(percentage(50)) control(new ButtonBuilder(\"TestButton\") label(\"TestButton\") width(\"120px\") height(\"40px\") align(Align.Center) ) ) System.out.println(\"PopupBuilder success.\") b.registerPopup(nifty) System.out.println(\"Registerpopup success.\") Because that first println() doesn't show, it looks like this method isn't even called at all! Edit After removing all calls on the Player object, the popup works. It seems I'm not \"allowed\" to access the player from the ScreenController. Unfortunate, since I need information on the player for the popup. Is there a workaround?"} {"_id": 43, "text": "CenterContainer makes my button too small I get the perfect width for my buttons, but CenterContainer overrides that value of theirs to make the button as wide as the biggest text length of the buttons when I put the buttons inside of the container godot 3.1"} {"_id": 43, "text": "What method is best to display respawn times? I'm currently working on multiplayer game and am trying to work out how to display respawn times. I had a few ideas in mind, taking inspiration from other games I've played before. Text Based Progress Bar Visual Timer Is there another way to display respawning for players that improves visual feedback? Meaning, is clear and effective at conveying exactly how long a player has to wait to respawn?"} {"_id": 43, "text": "Logic only GUI library I'm not sure whether this place is the correct for asking this. If it's the wrong place I'm sorry, please tell me if so! I'm making a small game for fun which would uses an own engine with OpenGL and Vulkan as underlying renderer implementation. The engine itself is targeted for Mono .Net. Currently I'm not yet there but I'll come to the point where I'm pushed to implement some kind of GUI (I'm thinking ahead because of good design). I already searched the Internet for render independent GUI systems but I wasn't lucky yet. As result I thought about how I could implement the GUI on my own and came to the conclusion a independent implementation is needed which takes care only for layout, positioning of GUI objects with responding to inputs. another implementation is needed which only takes the results of calculations for rendering (the renderer) Before I start inventing the whole wheel new I simply want to know Is it a correct approach to doing it this way? Is there a different common approach doing what I described?"} {"_id": 43, "text": "Display a variable in the UI I have been searching and searching for an answer to this question but nobody seems to be helping me. I have wasted the past two hours trying to figure out how to do this, so please help me out here. I am making a FPS game in Unreal Engine 4, and I want to display ammo. I can do that fine, but changing the text of the UI displaying the ammo is turning into a nightmare. I need to access the text label variable Inside of the blueprint that handles the actual gun firing From there I should be able to adjust the text to match what my ammo is. Unfortunately, no matter what I try, I cannot change the variable in my blueprint. I can't even make the variable public to begin with! What do I need to do to accomplish this?"} {"_id": 43, "text": "How do I attach UI data to logic data? I'm attempting to write an inventory system(C , doesn't need to be huge), that later on should be able to be drawn in a GUI. In the file structure, I think it would be best to put both information about the item itself and references to graphics, etc. in one file. But how does that translate into code? How should I tell the renderer, for example which sprite to draw for which item and where to do that. Should I only have the CInventory and the CItem class, containing both logic and sprite information, or should I create separate logic and GUI inventory(in this case meaning both CInventory and CItem) classes which are then linked by a common item id for example? Answers are always appreciated )"} {"_id": 43, "text": "way to implement a menu pratical i do my first game and already read alot about design strategie, programming style, design .. and so on theoretically it works perfect but in practice i dont know if i do thinks \"right\" i have three classes my main which starts the view in this i do all my stuff currently it holds an state variable, it has an onDraw method .. and so on the third class is the game thread while my game is running, in here are decisions depending on my current state what should be done Override public void run() Canvas canvas null mStartTime System.currentTimeMillis() while (mRun) canvas mHolder.lockCanvas() if (canvas ! null) State Updating State means to manage state transitions, such as a game over, character select or next level. switch( mPanel.getModeState() ) case Surface.MODE LOGO SPLASH break case Surface.MODE MENU the menu break case Surface.MODE LOADING loading animation break case Surface.MODE GAME PLAYING game stuff GAME START RUNNING END Input AI Physics animation mPanel.animate(mElapsed) break draw everyThing mPanel.doDraw(mElapsed, canvas) sound Sound and Video. mElapsed System.currentTimeMillis() mStartTime mHolder.unlockCanvasAndPost(canvas) mStartTime System.currentTimeMillis() my problem is .. the function onDraw draws everything .. including the menu ? this sounds for me like bad code because everytime doDraw is executet, i have to check in this function which state i am currently in .. this cost time, dosent it ? public void doDraw(long elapsed, Canvas canvas) canvas.drawColor(Color.BLACK) currently just gameLayout canvas.drawBitmap(background, 0, 0, mPaint) gameLayout.draw(canvas) would it not be better do implement an other thread which draws the menu ? but if so, how can i overlay the menu afer pause the game ? thanks for help erwin"} {"_id": 43, "text": "Why does Forge not find my texture for my custom background? I am creating a minecraft mod that improves the main menu for my minecraft server. At first I wanted to create the background, but somehow when I try to start minecraft it closes and I get a nullpointerexception because minecraft didn't find my background. public class ThundrialMenu extends GuiScreen Override public void initGui() Override public void drawScreen(int mouseX, int mouseY, float partialTicks) Random rnd new Random() int background rnd.nextInt(3) 1 String backgroundLocation \" assets thundrial gui Background\" background \".png\" this.drawBackground(mc.renderEngine.getTexture(new ResourceLocation(backgroundLocation)).getGlTextureId()) super.drawScreen(mouseX, mouseY, partialTicks) Override public void updateScreen() super.updateScreen() This is the folder where the pictures are located Why does Minecraft not find those pictures?"} {"_id": 43, "text": "Best approach for Event driven UI Had an idea for a modification to a game, however the core functionality heavily involves UI, and the API for the mod is event based. The player will have there own custom data object, so I know one option could be onClickEvent if Player doing X task player.doX if Player doing Y task player.doY on ScrollEvent if Player doing X task player.setXValue I have a feeling this is not the best approach, so my question is what is the best approach to an event driven UI?"} {"_id": 43, "text": "Error in DRAW GUI event on android. (GameMaker) Image of the game on a mobile phone As you can see the maze (draw event) has been resized correctly. But the yellow post it (draw GUI event) has not been scaled or displayed in the correct location (center of the screen). Same thing with GUI layout (draw GUI event). Because this is a small stage room (size) I do not use the artifice of views, I thought that could be because of that the problem, but I enabled the views and did not get any different result. Picture of the game on a computer (like it should be on the phone) OBS One information that can help you to help me solve the problem, is that to draw the post it I use the following code draw GUI event draw sprite(spr Post,0,640,360) . 640 is the half screen width of the game and also the room, 360 is half the height of the game screen and also the room. It seems that somehow the room on the cell phone is different size than 1280x720. I do not put the following code draw GUI event draw sprite(spr Post,0,room width 2,room height 2), because there are much larger phases that need views, so the post it needs to be in the center of the screen of the player, and with this code it ends up being in the center of the phase. I tested the game on Bluestacks and it did not happen the same as on the phone."} {"_id": 43, "text": "Interfaces 101 Making it Pretty I've made a few games which I've actually released into the wild. There's one particular issue I run into over and over, and that's the issue of the interface theme of the game. How can you make non arbitrary, consistent decisions about the look and feel and interface of your game? For example, in version one of my Silverlight chemistry based game, I made a (bad?) decision to go witha natural, landscape style look and feel, which resulted in this UI Then in a later iteration, I got smarter and went with a more \"machiney,\" grungy look and feel, which resulted in this (final UI) I will definitely say that my taste in UI improved through iteration. But it was a result of a lot of initially arbitrary decisions followed by a lot of tweaking. Is there a better way to figure out how to theme your game? To give a parallel in writing, when you're writing a fantasy sci fi novel, there are a lot of elements you need to describe. While you can arbitrarily invent objects creatures places etc., you get a much more consistent world when you sit down for a few minutes and design the area, region, planet, or universe. Everything then fits together nicely, and you can ask yourself \"how would this work in this universe? Edit It seems like I didn't explain this well. Let me simplify the question in the extreme when I need to lay out a title screen (with background, fonts, skinned buttons) how do I decide how they should look? Green or blue? Grunge or not? Rounded or flat? Serif or sans serif? Take that question and explode it into your game as a whole. How do you figure out how things should look? What process do you use to make them consistent and non arbitrary? Look at the screenshots again. I could have stuck to grass sky rocks, but metal seemed more fitting to the idea of chemical reactions and atoms."} {"_id": 43, "text": "How to create guides to off screen objects? I've played Metroid Blast on Wii U, and would like to build one of its features in a three.js game. The feature is if an opponent is out of view, a guide is displayed showing the direction of the opponent. An example of it is here (Image source) Notice the small circles with arrows in the left side. How could I have a similar feature in my game?"} {"_id": 43, "text": "Is it possible to skin Qt 4.5 such that it has a 'game like' interface? Is it possible to skin Qt 4.5 such that it looks less like an application framework but more of a game? I guess this probably means replacing the canvas, the title bar and the artwork of the various widgets. Will such an approach be platform independent too?"} {"_id": 43, "text": "How to display Render Target live to HUD widget in UE4 I'm making a security camera system in Unreal Engine 4. It allows the player to 'activate' the monitor, which should display the Render Target texture or the material made from it on the HUD. However, that just doesn't work. There's just no image when I try to play it. Nothing appears on the screen. I'm using blueprints btw, not C . And yes, I did check and make sure that it's not the part that displays the HUD that's going wrong, it's the displaying of the render target to the UI widget. To display it, i've tried using the image component in the UI widget. Can anyone help?"} {"_id": 43, "text": "Runtime Storage vs Static Storage Runtime Storage (hardcoded) vs Static Storage (file storage) (original question) I extended my engines GUI from procedural style to object orientated style, but I still have to create menues, buttons etc. So I got the choice to create each menue via a class or have a static main class which loads menues from a XML file. My problem is that I actually like to have static and external storage in XML because it keeps the code and the project clean. But if a GUI Object is created e.g. a button I want to have delegates callbacks events on it, but I think that isn't possible with loading and creating GUI Objects by XML files that only contain ints and strings. The question is when do you hardcode parts of your game and when do you store them locally. Runtime Storage You safe time while you do not have to write a parser or something similar. You lose a lot of flexibility in late development Static Storage You gain a lot of flexibility in the late development You spent a lot of time into a system to read and write, and also handle the storage"} {"_id": 43, "text": "Why does Forge not find my texture for my custom background? I am creating a minecraft mod that improves the main menu for my minecraft server. At first I wanted to create the background, but somehow when I try to start minecraft it closes and I get a nullpointerexception because minecraft didn't find my background. public class ThundrialMenu extends GuiScreen Override public void initGui() Override public void drawScreen(int mouseX, int mouseY, float partialTicks) Random rnd new Random() int background rnd.nextInt(3) 1 String backgroundLocation \" assets thundrial gui Background\" background \".png\" this.drawBackground(mc.renderEngine.getTexture(new ResourceLocation(backgroundLocation)).getGlTextureId()) super.drawScreen(mouseX, mouseY, partialTicks) Override public void updateScreen() super.updateScreen() This is the folder where the pictures are located Why does Minecraft not find those pictures?"} {"_id": 43, "text": "How do I create a message box that fires a callback on button press? I need to create a message box with an \"OK\" button. When the user touches the button, it should execute a callback. I'm new to this and couldn't find any articles in the docs."} {"_id": 43, "text": "Does a successful attempt count as an attempt? I'm writing a video game and I'd like to know if I should include the \"successful\" attempt in the count of \"total attempts\". For instance, in a clay shooting game, if the player needs four shots before they hit the target bullet one miss bullet two miss bullet three miss bullet four hit Does it equate to three attempts, or four attempts? What text do I need to write at the end of the round? You needed three attempts to hit the target! or You needed four attempts to hit the target!"} {"_id": 43, "text": "In tools development, what languages and technologies are currently in use? I am an aspiring tools developer currently in university. Normally I use both C and C to and from but as my time at university is coming to an end, what language and technologies are worth focusing on? With tools I'm not only thinking simple data file editors, but level editors and such as well. I have tried searching in numerous places but generally I only find questions regarding what language or tools to use for game development. As I want to create the tools rather than use them, the answers don't necessarily apply. Seeing as C still seems to be the language of choice in the gaming industry, is it also still the primary language for tools? If so, what UI and core libraries are most prominent? wxWidgets and stl boost? Plain Win32? Or if C is being phased out in favor of \"easier\" languages like C is WinForms the right pick, or is the industry moving towards WPF? Maybe scaleform internally as well? In short, is there anything I absolutely need to know to not be just an expensive chair heater?"} {"_id": 43, "text": "Slick2D and Nifty GUI I am currently trying to combine both slick2d and nifty to work together. I've had some amount of success I can now actually run my test and it won't crash. As far as I can tell, it will also receive input properly. First, I'm having doubts I'm doing it right. I extend NiftyStateBasedGame in my outer game and then I extend two NiftyOverlayGameState to create the two states. However, I am getting an error that doesn't crash my application saying WARNING An event service by the name NiftyEventBusalready exists. Perhaps multiple threads tried to create a service about the same time? org.bushe.swing.event.EventServiceExistsException An event service by the name NiftyEventBusalready exists. Perhaps multiple threads tried to create a service about the same time? at org.bushe.swing.event.EventServiceLocator.setEventService(EventServiceLocator.java 123) I could ignore it, since the application is running well enough (I think?) but I'm concerened that once I figure out how to actually implement some parts of the GUI they might not work. Which leads me to my next question. I was trying to create a simple button on screen and I could not for the life of me figure out how to go about it. I have my nifty instance... But what do I do with it? Any pointers in the right direction would be greatly appriciated! My three classes The outer class, TheGame (This is the StateBasedGame) public class TheGame extends NiftyStateBasedGame Menu menu Nifty nifty GameOver go public TheGame(String name) super(name) menu new Menu() go new GameOver() Override public void initStatesList(GameContainer arg0) throws SlickException this.addState(menu) this.addState(go) public static void main(String args) throws Exception AppGameContainer game new AppGameContainer(new TheGame(\"OMG, Super test!\")) game.setDisplayMode(800, 600, false) game.setAlwaysRender(true) game.start() And the two dummy classes the are the states public class Menu extends NiftyOverlayGameState Override protected void initGameAndGUI(GameContainer gc, StateBasedGame sbg) throws SlickException initNifty(gc, sbg) Override protected void renderGame(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException g.drawString(\"Does it work?\", 100, 100) Override protected void updateGame(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException Input input gc.getInput() if (input.isMouseButtonDown(Input.MOUSE LEFT BUTTON)) sbg.enterState(1) public int getID() return 0 public class GameOver extends NiftyOverlayGameState protected void initGameAndGUI(GameContainer gc, StateBasedGame sbg) throws SlickException initNifty(gc, sbg) Override protected void renderGame(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException g.drawString(\"WORKS, OOOH YEA!\", 100, 100) Override protected void updateGame(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException Input input gc.getInput() if (input.isMouseButtonDown(Input.MOUSE RIGHT BUTTON)) sbg.enterState(0) public int getID() return 1 Again, if compiled, this gets me the two screens I want with the warning exception I mentioned above. What am I doing wrong? And how would I start actually adding GUI elements to this?"} {"_id": 43, "text": "Keeping track of focused widget in GUI tree I'm designing a GUI framework based on trees of widgets. Widgets are general control and container structures that are everything from panels to buttons to file dialogs. Widgets have an array of child widgets a button contains a label and maybe an icon. Widgets are fed input events where the widget first does its own logic with the event then passes it on to its children. The application feeds input events to a single root widget, which can be anything from a single button in the middle of the screen to a full control window. I need a way to handle which widget(s) receives keyboard events. I've decided that one of the widgets in a given widget tree would be the focused widget. Widgets would have a gainFocus method and a loseFocus method, which would be used in response to mouse click events or manually by the application. It's unlikely I'll implement tabbing. When one widget gains focus, any existing focused widget would naturally lose focus. I still want each ancestor of the focused widget to see a given keyboard event in turn before it's given to the focused widget itself. So if I have a panel with a text box in it, the panel would see the event before the text box does. Therefore I really need to keep track of the chain of widgets from the root widget to the focused widget. I also need to maintain data integrity when I change focus so that all widgets in a tree can correctly tell whether or not they're the focused widget or an ancestor of the focused widget. I've so far come up with giving widgets a hasFocus boolean and a focusedChildIndex integer. hasFocus would be set to true when the widget has focus. focusedChildIndex would be set to the index of the focused child in its child array, which could be the focused widget itself or the next widget in the chain leading to the focused widget, or 1 to indicate that there's no focused child. Setting these variables when one widget in the tree gets its gainFocus or loseFocus method invoked is something I'm stumped on though. Edit So we're clear, this is what I think my widget class will be like class Widget private Widget parent private Array lt Widget gt children Methods for getters, adding widgets to widget trees, etc. ... public void mouseClick(int x, int y) doMouseClickEvent(x, y) for c in children c.mouseClick(int x, int y) As you can see in mouseClick the widget sees the event before its children does. I want keyboard inputs to work the same way, except this time I want to only have a single chain from the root to the focused widget to see the event. Plus I need to make sure that when one widget gains focus the currently focused widget in the tree loses focus."} {"_id": 43, "text": "Immediate GUI yae or nay? I've been working on application development with a lot of \"retained\" GUI systems (below more about what I mean by that) like MFC, QT, Forms, SWING and several web GUI frameworks some years ago. I always found the concepts of most GUI systems overly complicated and clumsy. The amount of callback events, listeners, data copies, something to string to something conversions (and so on) were always a source of mistakes and headaches compared to other parts in the application. (Even with \"proper\" use of Data Bindings Models). Now I am writing computer games ). I worked with one GUI so far Miyagi (not well known, but basically the same Idea as all the other systems.) It was horrible. For real time rendering environments like Games, I get the feeling that \"retained\" GUI systems are even more obsolete. User interfaces usually don't need to be auto layouted or have resizable windows on the fly. Instead, they need to interact very efficiently with always changing data (like 3d positions of models in the world) A couple of years ago, I stumbled upon \"IMGUI\" which is basically like an Immediate Graphics mode, but for user interfaces. I didn't give too much attention, since I was still in application development and the IMGUI scene itself seemed to be not really broad nor successfull. Still the approach they take seem to be so utterly sexy and elegant, that it made me want to write something for the next project using this way of UI (I failed to convince anyone at work (...) let me summarize what I mean by \"retained\" and \"immediate\" Retained GUI In a separate initialization phase, you create \"GUI controls\" like Labels, Buttons, TextBoxes etc. and use some descriptive (or programmatical) way of placing them on screen all before anything is rendered. Controls hold most of their own state in memory like X,Y location, size, borders, child controls, label text, images and so on. You can add callbacks and listeners to get informed of events and to update data in the GUI control. Immediate GUI The GUI library consists of one shot \"RenderButton\", \"RenderLabel\", \"RenderTextBox\"... functions (edit don't get confused by the Render prefix. These functions also do the logic behind the controls like polling user input, inserting characters, handle character repeat speed when user holds down a key and so on...) that you can call to \"immediately\" render a control (doesn't have to be immediately written to the GPU. Usually its remembered for the current frame and sorted into appropiate batches later). The library does not hold any \"state\" for these. If you want to hide a button... just don't call the RenderButton function. All RenderXXX functions that have user interaction like a buttons or checkbox have return values that indicate whether e.g. the user clicked into the button. So your \"RenderGUI\" function looks like a big if else function where you call or not call your RenderXXX functions depending on your game state and all the data update logic (when a button is pressed) is intermangled into the flow. All data storage is \"outside\" the gui and passed on demand to the Render functions. (Of course, you would split up the big functions into several ones or use some class abstractions for grouping parts of the gui. We don't write code like in 1980 anymore, do we? )) Now I found that Unity3D actually uses the very same basic approach to their built in GUI systems. There are probably a couple of GUI's with this approach out there as well? Still.. when looking around, there seem to be a strong bias towards retained GUI systems? At least I haven't found this approach except in Unity3D and the original IMGUI community seems to be rather .... .. quiet. So anyone worked with both ideas and have some strong opinion? Edit I am most interested in opinions that stem from real world experience. I think there is a lot of heated discussions in the IMGUI forum about any \"theoretical weakness\" of the immediate GUI approach, but I always find it more enlightening to know about real world weaknesses."} {"_id": 43, "text": "zoom to cursor calculation I want to be able to zoom in and out of the map using the scroll wheel. I want to zoom towards the cursor like google maps does but I'm completely lost on how to calculate the movements. so far, all I have is the resizing but I now need to change the map position. What I have map x and y map width and height cursor x and y. Any help would be most welcome."} {"_id": 43, "text": "Tech Tree layouts for games? I'm trying to do a tech tree GUI for my game, but i have limited width and the tree has alot of branches, the problem is if I make them small to fit the width, the tech tree is too small to read. For example the AOE one is very large (in width) I could allow scroll bar but as its web based, scrolls are quite ugly. So i was wondering how to deal with branches which slowly cause the tech tree to get wider as you go down the tech tree and how you would fit such a design in a limited space. Are there different known designs for tech trees that any one knows of so i can look at their types. I don't know the names given to the types of tech tree layouts. But am hoping to find one that is not overly complex for the user aswell."} {"_id": 43, "text": "HTML5 Game (Canvas) UI Techniques? I'm in the process of building a JavaScript HTML5 game (using Canvas) for mobile (Android iPhone WebOS) with PhoneGap. I'm currently trying to design out how the UI and playing board should be built and how they should interact but I'm not sure what the best solution is. Here's what I can think of Build the UI right into the canvas using things like drawImage and fillText Build parts of the UI outside of the canvas using regular DOM objects and then float a div over the canvas when UI elements need to overlap the playing board canvas. Are there any other possible techniques I can use for building the game UI that I haven't thought of? Also, which of these would be considered the \"standard\" way (I know HTML5 games are not very popular so there probably isn't a \"standard\" way yet)? And finally, which way would YOU recommend use? Many thanks in advance!"} {"_id": 43, "text": "Application toolkits like QT versus traditional game multimedia libraries like SFML I currently intend to use SFML for my next game project. I'll need a substantial GUI though (RPG strategy type) so I'll either have to implement my own or try to find an appropriate third party library, which seem to boil down to CEGUI, libRocket, and GWEN. At the same time, I do not anticipate doing that many advanced graphical effects. My game will be 2D and primarily sprite based with some sprite animations. I've recently discovered that QT applications can have their appearance styled so that they don't have to look like plain OS apps. Given that, I am beginning to consider QT a valid alternative to SFML. I wouldn't have to implement the GUI functionality I'd need, and I may not be taking advantage of SFML's lower level access anyway. The only drawbacks I can think of immediately are the learning curve for QT and figuring out how to fit game logic inside such a framework after getting used to the input update render loop of traditional game libraries. When would an application toolkit like QT be more appropriate for a game than a traditional game or multimedia library like SFML?"} {"_id": 43, "text": "Tech Tree layouts for games? I'm trying to do a tech tree GUI for my game, but i have limited width and the tree has alot of branches, the problem is if I make them small to fit the width, the tech tree is too small to read. For example the AOE one is very large (in width) I could allow scroll bar but as its web based, scrolls are quite ugly. So i was wondering how to deal with branches which slowly cause the tech tree to get wider as you go down the tech tree and how you would fit such a design in a limited space. Are there different known designs for tech trees that any one knows of so i can look at their types. I don't know the names given to the types of tech tree layouts. But am hoping to find one that is not overly complex for the user aswell."} {"_id": 43, "text": "Need help with making a journal system My game uses a system similar to Metroid Prime's logbook, in that it logs things the player encounters and discovers on their journey, categorizing it, etc. I want to write out all of the possible entries they can find, with the categories and all, but I need a system similar to what'll be in the final product to toy with, and use as an example for when it gets implemented into the game itself. A click through menu sort of thing. Writing out all of these long descriptions would be too much of a hassle in a regular text document (and would make it FAR too long), and doing it through HTML or something sounds far too messy. Basically, I want something, like an app, that I can edit, and that'll let me click through the categories till I get to the entry I want, which should display on the side. Here's a really terrible example of what I'm looking for. I'm probably stupid for asking this, and there's likely an extremely obvious solution to this, but I have a thousand other things related to the game to think about, and Googling didn't result in anything."} {"_id": 43, "text": "How to get text width in pixels in direct2d I am making the simple editor on direct2d and i want to make adaptive buttons size. When i create a button i pass text to it and a button gets width based on text width in pixels. I have tried to use IDWriteTextLayout and the method GetMetrics but i get the weird result where height more than width. D2D1 SIZE F Direct2D get text size(const char text) IDWriteTextLayout text layout NULL DWRITE TEXT METRICS text metrics wchar t wtext char string wchar(text) HR(write factor gt CreateTextLayout(wtext, wcslen(wtext), text format, 0.0f, 0.0f, amp text layout)) text layout gt GetMetrics( amp text metrics) DELETE ARRAY(wtext) RELEASE COM(text layout) D2D1 SIZE F size size.width text metrics.widthIncludingTrailingWhitespace size.height text metrics.height return size"} {"_id": 43, "text": "How do Nethack frontends work? I have been trying to learn about GUI frontends for Nethack, but I have been unable to determine how do they get the game information (map, inventory, player info, enemy locations, etc) from Nethack? As in, is there some API that allows these frontends to query these information? If so, how are they used? I have looked up everywhere but unable to find any documentation that describes how to do so."} {"_id": 43, "text": "Error in DRAW GUI event on android. Image of the game on a mobile phone As you can see the maze (draw event) has been resized correctly. But the yellow post it (draw GUI event) has not been scaled or displayed in the correct location (center of the screen). Same thing with GUI layout (draw GUI event). Because this is a small stage room (size) I do not use the artifice of views, I thought that could be because of that the problem, but I enabled the views and did not get any different result. Picture of the game on a computer (like it should be on the phone) OBS One information that can help you to help me solve the problem, is that to draw the post it I use the following code draw GUI event draw sprite(spr Post,0,640,360) . 640 is the half screen width of the game and also the room, 360 is half the height of the game screen and also the room. It seems that somehow the room on the cell phone is different size than 1280x720. I do not put the following code draw GUI event draw sprite(spr Post,0,room width 2,room height 2), because there are much larger phases that need views, so the post it needs to be in the center of the screen of the player, and with this code it ends up being in the center of the phase. I tested the game on Bluestacks and it did not happen the same as on the phone."} {"_id": 43, "text": "Differences between storyboarding for game design vs. web design I'm looking to UX and storyboard out a web adventure game. The goal being to have an area to show what the UI UX would look like (mockups), and ability to add dialog blurbs to describe the screen. I was thinking InVision, but that seems strictly for web development mockups. I could also simply draw them in Photoshop or on paper, but was looking more for something game design specific. Are there significant differences between storyboarding for game design as opposed to web design? If so, how do UX or storyboarding tools cater to those differences?"} {"_id": 43, "text": "What interchange format should I use for e.g. subtitles and UI texts? Are there any standard formats that can be used as the source material for game texts (i.e. subtitles, UI texts, etc.)? I can think of the following constraints at least some style effects (e.g. bold, italics) at least some format string support (e.g. you found d gold, you found count gold) be translator friendly either easy to grasp, or standard enough that translation companies may already have experience with it I know about the following but none of them appear to support format strings. Are there any industry standards for that or does every game or engine roll their own format? UE4 uses a custom rich text format (example Hello lt RichText.Emphasis gt everyone lt gt !) Unity uses its own HTML like format (example Hello lt b gt everyone lt b gt !) the srt format uses HTML like syntax, too (example Hello lt b gt everyone lt b gt !) BBCode is another popular format (example Hello b everyone b !)"} {"_id": 43, "text": "Keeping track of focused widget in GUI tree I'm designing a GUI framework based on trees of widgets. Widgets are general control and container structures that are everything from panels to buttons to file dialogs. Widgets have an array of child widgets a button contains a label and maybe an icon. Widgets are fed input events where the widget first does its own logic with the event then passes it on to its children. The application feeds input events to a single root widget, which can be anything from a single button in the middle of the screen to a full control window. I need a way to handle which widget(s) receives keyboard events. I've decided that one of the widgets in a given widget tree would be the focused widget. Widgets would have a gainFocus method and a loseFocus method, which would be used in response to mouse click events or manually by the application. It's unlikely I'll implement tabbing. When one widget gains focus, any existing focused widget would naturally lose focus. I still want each ancestor of the focused widget to see a given keyboard event in turn before it's given to the focused widget itself. So if I have a panel with a text box in it, the panel would see the event before the text box does. Therefore I really need to keep track of the chain of widgets from the root widget to the focused widget. I also need to maintain data integrity when I change focus so that all widgets in a tree can correctly tell whether or not they're the focused widget or an ancestor of the focused widget. I've so far come up with giving widgets a hasFocus boolean and a focusedChildIndex integer. hasFocus would be set to true when the widget has focus. focusedChildIndex would be set to the index of the focused child in its child array, which could be the focused widget itself or the next widget in the chain leading to the focused widget, or 1 to indicate that there's no focused child. Setting these variables when one widget in the tree gets its gainFocus or loseFocus method invoked is something I'm stumped on though. Edit So we're clear, this is what I think my widget class will be like class Widget private Widget parent private Array lt Widget gt children Methods for getters, adding widgets to widget trees, etc. ... public void mouseClick(int x, int y) doMouseClickEvent(x, y) for c in children c.mouseClick(int x, int y) As you can see in mouseClick the widget sees the event before its children does. I want keyboard inputs to work the same way, except this time I want to only have a single chain from the root to the focused widget to see the event. Plus I need to make sure that when one widget gains focus the currently focused widget in the tree loses focus."} {"_id": 43, "text": "HTML5 Game (Canvas) UI Techniques? I'm in the process of building a JavaScript HTML5 game (using Canvas) for mobile (Android iPhone WebOS) with PhoneGap. I'm currently trying to design out how the UI and playing board should be built and how they should interact but I'm not sure what the best solution is. Here's what I can think of Build the UI right into the canvas using things like drawImage and fillText Build parts of the UI outside of the canvas using regular DOM objects and then float a div over the canvas when UI elements need to overlap the playing board canvas. Are there any other possible techniques I can use for building the game UI that I haven't thought of? Also, which of these would be considered the \"standard\" way (I know HTML5 games are not very popular so there probably isn't a \"standard\" way yet)? And finally, which way would YOU recommend use? Many thanks in advance!"} {"_id": 43, "text": "How do I create a message box that fires a callback on button press? I need to create a message box with an \"OK\" button. When the user touches the button, it should execute a callback. I'm new to this and couldn't find any articles in the docs."} {"_id": 43, "text": "Display a variable in the UI I have been searching and searching for an answer to this question but nobody seems to be helping me. I have wasted the past two hours trying to figure out how to do this, so please help me out here. I am making a FPS game in Unreal Engine 4, and I want to display ammo. I can do that fine, but changing the text of the UI displaying the ammo is turning into a nightmare. I need to access the text label variable Inside of the blueprint that handles the actual gun firing From there I should be able to adjust the text to match what my ammo is. Unfortunately, no matter what I try, I cannot change the variable in my blueprint. I can't even make the variable public to begin with! What do I need to do to accomplish this?"} {"_id": 43, "text": "Slick2D and Nifty GUI I am currently trying to combine both slick2d and nifty to work together. I've had some amount of success I can now actually run my test and it won't crash. As far as I can tell, it will also receive input properly. First, I'm having doubts I'm doing it right. I extend NiftyStateBasedGame in my outer game and then I extend two NiftyOverlayGameState to create the two states. However, I am getting an error that doesn't crash my application saying WARNING An event service by the name NiftyEventBusalready exists. Perhaps multiple threads tried to create a service about the same time? org.bushe.swing.event.EventServiceExistsException An event service by the name NiftyEventBusalready exists. Perhaps multiple threads tried to create a service about the same time? at org.bushe.swing.event.EventServiceLocator.setEventService(EventServiceLocator.java 123) I could ignore it, since the application is running well enough (I think?) but I'm concerened that once I figure out how to actually implement some parts of the GUI they might not work. Which leads me to my next question. I was trying to create a simple button on screen and I could not for the life of me figure out how to go about it. I have my nifty instance... But what do I do with it? Any pointers in the right direction would be greatly appriciated! My three classes The outer class, TheGame (This is the StateBasedGame) public class TheGame extends NiftyStateBasedGame Menu menu Nifty nifty GameOver go public TheGame(String name) super(name) menu new Menu() go new GameOver() Override public void initStatesList(GameContainer arg0) throws SlickException this.addState(menu) this.addState(go) public static void main(String args) throws Exception AppGameContainer game new AppGameContainer(new TheGame(\"OMG, Super test!\")) game.setDisplayMode(800, 600, false) game.setAlwaysRender(true) game.start() And the two dummy classes the are the states public class Menu extends NiftyOverlayGameState Override protected void initGameAndGUI(GameContainer gc, StateBasedGame sbg) throws SlickException initNifty(gc, sbg) Override protected void renderGame(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException g.drawString(\"Does it work?\", 100, 100) Override protected void updateGame(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException Input input gc.getInput() if (input.isMouseButtonDown(Input.MOUSE LEFT BUTTON)) sbg.enterState(1) public int getID() return 0 public class GameOver extends NiftyOverlayGameState protected void initGameAndGUI(GameContainer gc, StateBasedGame sbg) throws SlickException initNifty(gc, sbg) Override protected void renderGame(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException g.drawString(\"WORKS, OOOH YEA!\", 100, 100) Override protected void updateGame(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException Input input gc.getInput() if (input.isMouseButtonDown(Input.MOUSE RIGHT BUTTON)) sbg.enterState(0) public int getID() return 1 Again, if compiled, this gets me the two screens I want with the warning exception I mentioned above. What am I doing wrong? And how would I start actually adding GUI elements to this?"} {"_id": 43, "text": "Technical term for the border that appears around the screen, usually in response to low health? This had a strange term but I can't remember what it's called and it's difficult to search for."} {"_id": 43, "text": "How can I implement dynamic button size? I'm on the process of planing a sort of a 2D 2.5D, pixel art multilingual game, while I learn about game development. I have a pretty solid background at programming, but when it comes to game design, I don't know too much. My particular question is about how is the proper better way of creating and implementing a game text button, but I suppose it can be applied to other GUI elements. What I have found so far, while \"googleing\" looking for this specific question, is how to deal with engines or frameworks which have their own way of doing it, but I would like to do it by my own. So to make things clearer, let me expose my vision of potential approaches. Fixed text in a fixed size texture This is an easy way of implementing a text button, as all I have to do is loading and positioning a texture. However, it could be painful to change my .psd files all the time, as I'm working with a multilingual game. Variable text and fixed size texture I could use a texture as a button model and overlap it with all kinds of text of different languages, reading the texts from .xml files. The problem is that a word in a language can exceed its equivalent of another language. A workaround for this could be switching between different font sizes, i.e., a text in a language would be smaller or larger than in another, but this would look ugly. Variable text and splitted texture This approach would divide a button texture into 3 different parts left, middle and right. Then, I would read a text from a .xml file, measure its length in pixels and increase (\"multiply\") the \"middle\" part of the texture so that the text could fit on it. This looks fine when working with a pixel art game GUI, but sounds not fine when working with vectorized images. Dynamically generated GUI I could use OpenGL to render rectangles and use them as buttons, but this would produce quite basic shapes. At most, I would have shaded rectangles with a basic border and some text rendered on it it would look like a HTML CSS GUI, which is a way far from a game GUI. These approaches are just my guesses, as I've never worked in the game industry I assume that someone experienced can correct me if I deduced something wrong. Another thing is that I think these approaches can work diffently depending of the texture type (e.g. pixel art and vectorized textures), so you'll be welcome for answering why an approach is better for a texture type or another. There's also a possibility of me being a bad thinker and all of this being a \"bullshit\", and if it is the case, I hope you share your technique with me. Moreover, as I said before, this question is specific for a text button, but I think with some adjustments it could cover more GUI elements which have related properties (such as window, text input and the like), so if you include it as part of your answer, it'll be helpful."} {"_id": 44, "text": "Godot tween animation playing order I'm making a three in line game with godot, but i'm having an issue. First time when swapping cells, the animation of swapping and the elimination of cells (in the case of making 3 or more cell aligned in a line) played both at the same time. So i refactored a bit the code, now i have queue for each cell that manages the animation to be played one by one. Now my problem is this, the cells that the player swaps, they do fine, the play the swap animation then the elimination animation. the problem are the other cells in the line, those get removed as the first cells are playing the swap animation first and then elimination animation. Step 1 Step 2 cells in line remove animation nothing swaped cells swap animation remove animation in case i didn't explained well i left a more graphic description of the flow of the animation steps. this is how i want the animation to be played Step 1 Step 2 cells in line nothing remove animation swaped cells swap animation remove animation I'm not sure how to solve the problem, each cell manages their animations in the queue."} {"_id": 44, "text": "Is it possible to have a script built in into a custom resource? Here's a rudimentary custom resource extends Resource export(Resource) var scr I can drag a pre made .gd script into this exported property in Inspector, and it works as intended. I can click on the exported property field and embed a resource (like \"New ShaderMaterial\"), and it would also work as intended, and I would be able to edit that sub resource normally. However, if I click on the exported property and select \"New GDScript\", there doesn't seem to be a way to open the new gdscript for editing. Is it possible to embed a gdscript sub resource the same way you can embed a different sub resource?"} {"_id": 44, "text": "Add a sound to all the buttons in a project Is there an option on the texture button or something like that where you can specify a sound to be played on button press. I have created a global sound manager but for the button presses, I have to manually code it everywhere the script has a button pressed signal. Or some kind of logic that when a button is pressed anywhere in the project, sound manager plays a particular sound."} {"_id": 44, "text": "Godot doesn't loop the sound Basically it's the sound of a fuse for a bomb, until the timer sends the signal the sound should stop playing and play the explosion sound, but right now only plays once and the stop. What i did wrong what i did missed? the code i use for the bomb scene extends StaticBody2D func ready() AnimatedSprite.animation quot bomb quot CollisionShape2D.disabled true BombTimer.start() FuseSound.play() func on BombTimer timeout() AnimatedSprite.animation quot explosion quot CollisionShape2D.disabled false RemoveTimer.start() ExplosionSound.play() func on RemoveTimer timeout() queue free() func on Bomb body entered(body) print( quot bomb collided with quot body.get name())"} {"_id": 44, "text": "How to seperate gui input from world input? I have a GUI interface and a player that hase code to detect when the mouse is pressed. When i mess with my GUI buttons the code for the player also fires off an undesired behavior. The code in the player is meant for mining or using his current item not meant for buttons. Some people have suggested using unhandled input and mouse filters, but i havent gotten either of those to work. Im just wondering what the common thing to do in the situation?"} {"_id": 44, "text": "Linux Mint Godot window when ran very small I am running my game on Linux Mint 20 Cinnamon. When I run my game I get a very small window that is about 1 pixel tall. This happens across all projects. I have tried uninstalling Godot and reinstalling it from the package manager. I have also tried the official launcher from their website. Updating through update manager does not help as well. I get the same issue using Godot 3.2.2 and 3.2.3"} {"_id": 44, "text": "\"ui is not declared in current scope\" error I just started development for a game I have to design for school. When using gd in the script to make the character move right I get an error extends KinematicBody2D var motion Vector2() func physics process(delta) if input.is action pressed(ui.right) motion.x 100 move and slide(motion) This is the line that is giving me problems if input.is action pressed(ui.right) and it keeps saying that ui is not declared in the current scope"} {"_id": 44, "text": "How to know if an overriden method calls its super method or not? Consider this situation, where a Player class inherits from a more general Actor class Actor.gd class name Actor extends KinematicBody2D func ready() print( quot I am an actor quot ) foo() func foo() print( quot I was thinking I was an actor quot ) Player.gd class name Player extends Actor func ready() print( quot I am a player quot ) func foo() print( quot I was thinking I was a player quot ) When one instantiate a player in a scene, we have this output I am an actor I was thinking I was a player I am a player How to know when a method will call its super class?"} {"_id": 44, "text": "Godot and getting files via HTTP So, I am wanting to use Godot to get a (binary) file using HTTP and then either save it or, even better, turn it into a Resource in memory that I can use. It'll be WAV files that I'm getting in return (trying to implement MaryTTS, which is running as a server on localhost). I had a look at the docs for HTTPRequest, but can't seem to get a working solution. I do HTTPRequest.request(\"http ...\") when a keypress is made, and I have the on HTTPRequest request completed() function, but this never seems to be called. I tried with the function in the same Node as the request (as per the docs' example), and I also tried putting it as part of a script for the HTTPRequest Node. If I hit the triggering key fast enough, it gives an error (\"HTTPRequest is processing a request\"), but if I do it slower, it doesn't give that error, so it appears it is finishing. It just doesn't do anything when it finishes. HTTPRequest gives a return value of 0, which I assume means no error? (Or should this give me HTTP status codes?) Any idea what I'm doing wrong? Can HTTPRequest handle binary files? How do I get this working? (Any suggestions on a better way to implement MaryTTS are also welcome)."} {"_id": 44, "text": "Change object's location at instantiated moment I'm trying to instantiate object(scene) and set it's spawn position at the spawn time. Here's the code I wrote func spawn asteroid() var spawn position Vector3 get spawn position() var asteroid instance asteroid scene.instance() asteroid instance.transform.origin spawn position spawned asteroids.append(asteroid instance) add child(asteroid instance) asteroid scene is PackedScene, so get instance first, and then update it's position, and finally use add child to append current scene's tree. It seems fine to me, however when I run the game, the object was spawned at (0,0,0) and then move spawn position. I changed it's position before it appended to scene, but why it still (0,0,0) and right after move to the specified position? In Unity, change object's location right after instancing works. In Godot Engine, is this approach invalid?"} {"_id": 44, "text": "Why does the kinematic body move in opposite direction after I interpolate its movement, and how do I fix it? I have added some basic movement and some manual interpolation to a cube that is a kinematic body in Godot. extends KinematicBody var speed int 10 var slowdown buffer 0.2 var movement Vector3(0,0,0) func ready() pass func interpolate() if movement.x gt 0 movement.x slowdown buffer elif movement.x lt 0 movement.x slowdown buffer else movement.x 0.0 func physics process(delta) if Input.is action pressed( quot left quot ) movement.x speed elif Input.is action pressed( quot right quot ) movement.x speed else interpolate() move and slide(movement) The problem is that when I move the cube using A and D, after the cube stops after the interpolation, it starts moving in the opposite direction with a non increasing speed. How can I fix this?"} {"_id": 44, "text": "What should I enter in Debug user and Release User in android export section in Godot? I just want to export to android. I have tried by adding my name, I got install error."} {"_id": 44, "text": "Godot 3.X Implementing a smooth movement for pitch, yaw roll I'm implementing pitch, yaw and roll on airplane object, but when rotating the object (either pitch, roll or yaw), it starts rotating slowly but then the rotating movement goes awfully fast very quickly. it's quite jarring. i'm not sure how to make more smooth. The issues I think the problem lies in the acceleration when the object rotates, i want to be an uniform speed Other problem from this code, it's that if want to change the rotating direction it's slow to change, takes a while to rotate to the opposite direction The player input code extends Node const MAX CAM ANGLE 30 var pitch dir 0 var yaw dir 0 var roll dir 0 var thrust 0.5 var input '' func ready() DebugStats.add property( Plane, quot transform origin quot , quot round quot ) DebugStats.add property( Plane, quot force quot , quot round quot ) DebugStats.add property( Plane, quot torque quot , quot round quot ) DebugStats.add property(self, quot pitch dir quot , quot round quot ) DebugStats.add property(self, quot input quot , quot quot ) func physics process(delta) process inputs(delta) process movement(delta) func process inputs(delta) if Input.is action pressed( quot p1 fire quot ) Plane.fire weapon() input 'fire' if Input.is action pressed( quot ui up quot ) thrust delta input 'accel' if Input.is action pressed( quot ui down quot ) thrust delta input 'slow' if Input.is action pressed( quot p1 pitch up quot ) pitch dir delta input 'up' if Input.is action pressed( quot p1 pitch down quot ) pitch dir delta input 'down' if Input.is action pressed( quot p1 roll left quot ) roll dir delta input 'yaw left' if Input.is action pressed( quot p1 roll right quot ) roll dir delta input 'yaw right' if Input.is action pressed( quot p1 yaw left quot ) yaw dir delta input 'yaw left' if Input.is action pressed( quot p1 yaw right quot ) yaw dir delta input 'yaw right' if Input.is action pressed( quot ui quit quot ) get tree().quit() TODO Adjust values to make movement more smooth func process movement(delta) thrust clamp(thrust, 0.2, 1) pitch dir clamp(pitch dir, .6, .6) yaw dir clamp(yaw dir, .6, .6) roll dir clamp(roll dir, .6, .6) Plane.calc force(thrust, pitch dir, roll dir, yaw dir) The plane movement script extends RigidBody const v3 Vector3(0, 0, 0) const scalar z Vector3(0, 0, 1) var force v3 var torque v3 var drag v3 var lift v3 var thrust v3 const MAX THRUST TURN 150 const MAX THRUST 1 temporal value just to debug the rotating problem const MAX CAM ANGLE 30 const DRAG CONST 1 temporal value just to debug the rotating problem Calculates flying speed and direction func calc force(thrust, pitch dir, roll dir, yaw dir) var speed MAX THRUST (thrust) var drag coef DRAG CONST MAX THRUST MAX THRUST thrust transform.basis.z ( speed) drag transform.basis.z drag coef lift transform.basis.y drag coef force thrust drag lift var pitch global transform.basis.x pitch dir MAX THRUST TURN var yaw global transform.basis.z yaw dir MAX THRUST TURN var roll global transform.basis.z roll dir MAX THRUST TURN torque pitch yaw roll Applies all force at once in the airplane object func integrate forces(state) add central force(force) add torque(torque) How i can make the rotating movement more smoother? Note this is an arcade game, not really interested in a complex solution for the physics. Note 2 if you want to test it, you can check out here https github.com balmeidaa godot sky aces"} {"_id": 44, "text": "How do I remove the window border in Godot? I want to show my Godot engine game in a borderless window, but not fullscreen. I want to just have the game view visible on screen with no title bar or window chrome."} {"_id": 44, "text": "Is there a way to run a tool script without attaching it to a node in the scene tree? What I want to do is run a tool script on the editor. The usual way would be to attach it to a scene tree node, but then I'd have to guard it with ifs all over to prevent editor code to be run at runtime and viceversa. I could instantiate the script and run it directly without it being attached to a node, but the script that instantiates that script would have to be tool too, so not getting rid of the problem. I guess I could create a node in the scene tree with a tool script attached, that removes itself from the scene tree once the game is running. Is there a more elegant way of doing it? Like some kind of project setting to run a tool script on project load?"} {"_id": 44, "text": "How can I change the default New Project directory in Godot Engine? When I go to create a new project in Godot Engine (version 3.2) my Project Path is always the original default directory, no matter what path I last used. There doesn't appear to be any configuration inside the Project List window. How can I change the default project path for new projects?"} {"_id": 44, "text": "How signals work when Node2D is queue freed? Consider this setup KinematicBody2D (Player) Sprite (icon.png) VisibilityNotifier2D With Player.gd class name Player extends KinematicBody2D signal unvisible onready var visibility notifier VisibilityNotifier2D VisibilityNotifier2D func ready() gt void visibility notifier.connect( quot screen exited quot , self, quot on screen exited quot ) func on screen exited() gt void emit signal( quot unvisible quot ) Now I have a template Level.gd Node2D (Level) Player extends Node2D onready var player Player Player export var debug no enemy false export var debug no player true func ready() gt void player.connect( quot unvisible quot , self, quot reset level quot ) if debug no player player.queue free() func reset level() gt void print( quot reset quot ) get tree().reload current scene() The print statement proves that this setup make a kind of infinite loop of reset because the signal screen exited is still emited when the player is queue free. Is it expected? I am even more surprised with this modified version which produces the same thing func ready() gt void if debug no player player.queue free() player.connect( quot unvisible quot , self, quot reset level quot )"} {"_id": 44, "text": "How can I remove Godot's splash screen? I started using Godot lately (mostly because the editor supports Linux). There is one thing that bothers me the Godot splash screen. I know that I can (somehow) remove it and I saw something about C but I'm not sure. Is there any way to remove it? Or maybe it is only in the editor and once you export the game it'll disappear?"} {"_id": 44, "text": "Godot and getting files via HTTP So, I am wanting to use Godot to get a (binary) file using HTTP and then either save it or, even better, turn it into a Resource in memory that I can use. It'll be WAV files that I'm getting in return (trying to implement MaryTTS, which is running as a server on localhost). I had a look at the docs for HTTPRequest, but can't seem to get a working solution. I do HTTPRequest.request(\"http ...\") when a keypress is made, and I have the on HTTPRequest request completed() function, but this never seems to be called. I tried with the function in the same Node as the request (as per the docs' example), and I also tried putting it as part of a script for the HTTPRequest Node. If I hit the triggering key fast enough, it gives an error (\"HTTPRequest is processing a request\"), but if I do it slower, it doesn't give that error, so it appears it is finishing. It just doesn't do anything when it finishes. HTTPRequest gives a return value of 0, which I assume means no error? (Or should this give me HTTP status codes?) Any idea what I'm doing wrong? Can HTTPRequest handle binary files? How do I get this working? (Any suggestions on a better way to implement MaryTTS are also welcome)."} {"_id": 44, "text": "GET and POST requests in gdscript How do I perform get and post requests from Gdscript in Godot? I am trying to get a map API and use it in the game."} {"_id": 44, "text": "Godot Collision for character teleportation I'm currently working on a little game to discover Godot game engine. It's a Top Down game and I want my character to be able to teleport through walls. I thought to dupplicate my character's collision box and to set its position to the teleportation's position but I didn't find a way to check if there is a collision to this new position. Any advise?"} {"_id": 44, "text": "Can't find sibling node, keeps giving \"null instance\" I'm trying to set it up so that there are three buttons but only one can be toggled at a time. So when one button gets toggled it makes sure that the other two are not toggled. The code is trying to set the toggled status however since it can't find the node I'm at a loss. var vec Vector2(0,1000) var ori Vector2(0,0) func ready() pass func on Ally1 Button toggled(button pressed) if button pressed set position(ori) Player Button.set pressed(false) else set position(vec) This is what the tree looks like. The Player Ally1 ui is trying to access Player Button but as stated it can't seem to find it and just returns null. Any help is greatly appreciated, thank you in advance."} {"_id": 44, "text": "How to have a tilted FNT font on Godot? Since FNT is a bitmap font I was thinking perhaps making the padding negative to the right and left side of the characters and rasterizing each glyph already skewed by an angle could make the font appear to be tilted. Does any one know whether FNT sports negative padding or whether Godot support some form of skewing that could accomplish that? Please take a look at the image to see what I'm describing"} {"_id": 44, "text": "Error(45,74) Identifier 'collision' is not declared in the current scope func physics process(delta) direction Vector3(0, 0, 0) if Input.is action pressed(\"ui left\") direction.x 1 if Input.is action pressed(\"ui right\") direction.x 1 if Input.is action pressed(\"ui up\") direction.z 1 if Input.is action pressed(\"ui down\") direction.z 1 direction direction.normalized() direction direction speed delta if velocity.y gt 0 gravaty 20 else gravaty 30 velocity.y gravaty delta velocity.x direction.x velocity.z direction.z velocity move and slide(velocity, Vector3(0, 1, 0)) if is on floor() and Input.is key pressed(KEY SPACE) velocity.y 10 var hitCount get slide count() if hitCount gt 0 var collision get slide collision(0) if collision.collider is RigidBody collision.collider.apply impulse(collison.position, collision.normal)"} {"_id": 44, "text": "Using add force and add torque to turn a RigidBody2D Godot Scene tree Scene (Node2D) RigidBody2D (Parent of Sprite and CollisionShape2D initially points to X direction 90 degrees) Camera2D When I use apply force() with ui up key, the Vehicle moves correctly and remains in motion. However when I use apply torque impulse() (such as ui right) it turns but, then the Vehicle is moving slipping sideways instead of towards the new direction. If I stop the motion by reversing the thrust, then start again it moves correctly in that new direction. Seems I have to do some vector math math on the value of torque but I am not sure what. extends RigidBody2D var thrust Vector2(0, 100) var torque 1024 var cot Vector2(0,0) var speed int var direction int func ready() set physics process(true) set process input(true) can sleep false speed 0 direction 0 func integrate forces(state Physics2DDirectBodyState) if Input.is action just pressed( quot ui down quot ) speed 1 add force(cot, thrust.rotated(rotation)) if Input.is action just pressed( quot ui up quot ) speed 1 add force(cot, thrust.rotated(rotation)) if Input.is action just pressed( quot ui right quot ) direction 1 apply torque impulse(torque) if Input.is action just pressed( quot ui left quot ) direction 1 apply torque impulse( torque)"} {"_id": 44, "text": "How to inspect child nodes in IDE debugger? Consider an enemy with this node hierarchy KinematicBody2D (Enemey) Sprite CollisionShape Area2D (StompDetector) CollisionShape2D With signal from StompDetector to Enemy func on StompDetector body entered(body Node) gt void if body.global position.y lt StompDetector.global position.y die() gt gt BREAKPOINT lt lt That does not work as exepcted. How to inspect StompDetector from the debugger at BREAKPOINT?"} {"_id": 44, "text": "How to create bullet hole decals in Godot engine? How can you create decals such as bullet holes in Godot? Godot doesn't seem to have any native method of creating decals. I am trying to create decals so that bullet holes will be displayed properly on curved and angled surfaces and corners. I have tried a few plugins, but none of them worked, they all either had a texture stretching issue or they didn't work at all. For example, when I tried using the Screen Space Decals plugin (https godotengine.org asset library asset 241), it did draw decals when a texture wasn't provided (a simple black rectangle by default), but when I assigned the bullet hole texture to the decal property the bullet holes became invisible. What would be an ideal method of creating decals in Godot?"} {"_id": 44, "text": "How to get a consistent behavior for a rigid body hooked platform? Consider this platform made of RigidBody2D and PinJoint2D objects PinJoint2D setup is Softness 0 Bias 0.9 When I set the mass of the platform with high value, the structure starts to shake like this Why is this happening and how to fix that?"} {"_id": 44, "text": "How do I add an object to the node tree at a specific position I'm making a skiing game, and a part of that is programmatically adding snow to the scene in a specific place. It will all be the child of a single node. I was looking through the Flappy Bird code but when it instances a scene, it only uses the function add child(). There doesn't seem to be a way to set its position. Here is the project on github."} {"_id": 44, "text": "How to change FPS when using a sprite sheet and AnimationPlayer? With AnimatedSprite it is easy to change FPS. Is there a convenient way to do that with AnimationPlayer?"} {"_id": 44, "text": "How to make two keys pressed to make an action? Hey i am beginner gamedev. I couldn't find answer to this or I am bad articulating my problem. But really would like an answer to this. How can i make function to press two keys like A and D at the same time to make a jump animation if A and D are already taken separately to A walk left and D to walk right? Without them overlapping. func input(event) if event.is action pressed( quot left quot ) amp amp event.is action pressed( quot right quot ) DancerSprite.play( quot bluedouble quot ) if event.is action pressed( quot left quot ) DancerSprite.play( quot blueleft quot ) return elif event.is action pressed( quot right quot ) DancerSprite.play( quot blueright quot ) return"} {"_id": 44, "text": "How do i get effect when gems come together in godot? I'm create gems puzzle game, In my game there is requirement that 2x2 matrix gem will group and then it will convert in power gem. check below image. I'm new in game development, so anyone can point me out ? any suggestion or link will be helpfull. Thank you"} {"_id": 44, "text": "What is the efficient way to sync TextureProgress with a Timer not in the UI? I want to use a TextureProgress which reflects the state of a Timer. I have tried to emit signals FROM the Node2D. process() which owns the Timer with emit signal( quot time left changed quot , timer.time left) TO the UI but it seems to make huge impact on performance."} {"_id": 44, "text": "How to handle multiple clipping rectangles in a CanvasItem? Let's say I have a CanvasItem that needs to draw the background first, occupying the entire item rect, and then draw all its content within a smaller rect leaving a margin. How should this be done in the NOTIFICATION DRAW within notofication? This is what I've tried void MyCustomItem notification(int p what) case NOTIFICATION DRAW Enable clipping VisualServer get singleton() gt canvas item set clip(get canvas item(), true) draw background() Clip to margins VisualServer get singleton() gt canvas item set custom rect(get canvas item(), true, Rect2( Point2( MARGIN LEFT, MARGIN TOP ), Size2( width MARGIN LEFT MARGIN RIGHT, height MARGIN TOP MARGIN BOTTOM ) )) draw stuff() The problem with this is that it will clip everything to the margins including the background."} {"_id": 44, "text": "Godot play video after file load I used WebM video in my game but it's lagging. The audio is few secs delayed then video. Is there any way to load the video first then play so that the lagging doesn't occurs"} {"_id": 44, "text": "Godot Collision for character teleportation I'm currently working on a little game to discover Godot game engine. It's a Top Down game and I want my character to be able to teleport through walls. I thought to dupplicate my character's collision box and to set its position to the teleportation's position but I didn't find a way to check if there is a collision to this new position. Any advise?"} {"_id": 44, "text": "In Godot browser game, is it possible to let the player download a file? I have a Godot game exported to the browser. I want to let the player export some data and let it save the data as a file on their PC, as if they were downloading a file from the Web. Is it possible for me to do that?"} {"_id": 44, "text": "How do I access a variable from my code in Godot's editor? In Godot, I have a node with a variable that I often need to tweak for balancing purposes. It would be a lot easier to manage if I could modify it inside the editor instead of the code. How would I go about doing this?"} {"_id": 44, "text": "Despite the connect() method returning 0 (enum), the function specified in the connection is not called The subject script extends ColorRect onready var subject get parent().get node('Page1') func ready() var error subject.connect('set timer', self, 'ad') func ad() print('signal connected')"} {"_id": 44, "text": "How to have a tilted FNT font on Godot? Since FNT is a bitmap font I was thinking perhaps making the padding negative to the right and left side of the characters and rasterizing each glyph already skewed by an angle could make the font appear to be tilted. Does any one know whether FNT sports negative padding or whether Godot support some form of skewing that could accomplish that? Please take a look at the image to see what I'm describing"} {"_id": 44, "text": "How to get current Microphone Frequency in Godot Let us say I want to create a singing game similar to SingStar, and for this purpose I want to get the audio pitch the microphone is getting, in real time, or as close as possible. I know I can get audio input in Godot. Even record the microphone to a file, there is an official demo project that does that (mic record). I also know there are libraries that can analyze the audio. How can I get the microphone pitch in real time? Yes, I'm answering my own question. This question is inspired on a similar one on StackOverflow, which asked for a library to do this, which lead to the question getting closed, and the asker deleted it instead of editing the question Before I noticed. As it turns out, you don't need libraries to do this. This is a means to answer the question I believe that person should have asked."} {"_id": 44, "text": "How should bullet reflections be implemented? Im working on a tank game where bullets are relected off of walls. The formula for a relfection is r d 2d n n 2n where d is the incoming vector and n is the normal of a wall. My bullets stick to the walls and then quot bounce quot off at the corners an undesirable effect. Im honestly questioning my formula implementation at this point. func collision() for i in get slide count() var collision get slide collision(i) if collision.collider.is in group(globals.wall group) var normal collision.normal velocity velocity ((2 velocity.dot(normal)) normal.length squared()) normal rotation velocity.angle() PI if i use the is on wall function and simply negate the velocity this does produce a bouncing effect but not a correct one. I still need the normal. I orignally used rigid bodies as seen in the image. But i have switched to kinematic bodies."} {"_id": 44, "text": "Is it better to connect signals in source code or with the IDE feature? In Godot IDE, what are the advantages and the caveats of using the visual IDE to connect signals to listerners instead of doing this var state bool onready var countdown Timer Countdown func ready() gt void state true countdown.connect( quot end quot , self, quot toggle quot ) func toggle() gt void state not state"} {"_id": 44, "text": "How to draw text with characters rendered in reverse order in a Godot game? I need to have some text showing up in my Godot game in a way that each character overlaps the character directly to its right, like so Using a BMFont (.fnt) in a Label node with the values of xadvance specified in the font smaller than the characters width I get this What approach can I use to still be able to use my .fnt font and also store the text with the characters in their natural order, as it would be stored for using with a normal Label or Button control? Which would help for language localization purposes."} {"_id": 44, "text": "How do I decrease the scale of an instanced node or scene? I'm trying to decrease size of instanced RigidBody2D scene, through code. With scale(), I'm trying to decrease the size of the image sprite that's attached to the RigidBody2D. The problem is, it's not working. No matter how much I try to scale down, the size of the blood drop circle remains the same. const blood druple scn preload(\"res Scenes blood.tscn\") func spawnBlood() var newBlood Blood druple scn.instance() rotationAdd rotationAdd 30 if(switchBloodSize 0) set scale(Vector2(2,1)) This part is my problem print(\"blood size \", newBlood.get scale()) add child(newBlood) switchBloodSize 1 elif(switchBloodSize 1) newBlood.scale(Vector2(0.5,0.5)) This part is my problem print(\"Blood size \", newBlood.get scale()) add child(newBlood) switchBloodSize 0 newBlood.set pos(Vector2(100,100)) rotate(rotationAdd) As you can see, I have two different if conditions, each with a different scale() and size. Sadly, both remain the same size. The strange part is that it does display the scale values as been altered, yet the newBlood instance is not visually changing. Why is this?"} {"_id": 44, "text": "How to make a 3D mesh invisible in Godot? Just like the title says i'm trying to make the mesh disappear after a set value reaches zero. Current code is trying to simply turn the entity invisible so that later i can implement a resurrect function. if Sname get node(\"Entity\").get name() print(\"punched number 1\") selected.health selected.health 10 if selected.health lt 0 selected.health 0 get node(\"Control Button\").disabled true Entity.visable false Is it even possible to toggle that value or is there an easier way to do this? I dont want to use free queue() as that would interfere with other entitys. Thanks for the help in advance, im new to Godot so sorry if this ends up being a no brainer."} {"_id": 44, "text": "What is the efficient way to sync TextureProgress with a Timer not in the UI? I want to use a TextureProgress which reflects the state of a Timer. I have tried to emit signals FROM the Node2D. process() which owns the Timer with emit signal( quot time left changed quot , timer.time left) TO the UI but it seems to make huge impact on performance."} {"_id": 44, "text": "How to get current Microphone Frequency in Godot Let us say I want to create a singing game similar to SingStar, and for this purpose I want to get the audio pitch the microphone is getting, in real time, or as close as possible. I know I can get audio input in Godot. Even record the microphone to a file, there is an official demo project that does that (mic record). I also know there are libraries that can analyze the audio. How can I get the microphone pitch in real time? Yes, I'm answering my own question. This question is inspired on a similar one on StackOverflow, which asked for a library to do this, which lead to the question getting closed, and the asker deleted it instead of editing the question Before I noticed. As it turns out, you don't need libraries to do this. This is a means to answer the question I believe that person should have asked."} {"_id": 44, "text": "How do I attach the Visual Studio Code debugger to Godot At 3.0 Godot now supports C and encourages the use of Visual Studio Code to edit this code. It is not clear how to attach VS Code so that we an apply breakpoints and debug a project at runtime. I am running A recent build of Godot from master (b49ca94 with mono for 64 bit windows) Visual Studio Code 1.21.0 with these extenstions C 1.14 Mono Debug 0.15.8 Mono 5.10.0"} {"_id": 44, "text": "Difference between process(delta) and physics process(delta)? The documentation is pointing one main difference, this is the concept of being synced or not with the physics engine, so the delta parameter has more chance to be constant in physics process(delta) than in process(delta). But I am pretty sure that no one counts on that. And that everybody checks the value of delta in physics process(delta). So what are the different use cases of those two functions?"} {"_id": 45, "text": "How can I cull non visible isometric tiles? I have a problem which I am struggling to solve. I have a large map of around 100x100 tiles which form an isometric map. The user is able to move the map around by dragging the mouse. I am trying to optimize my game only to draw the visible tiles. So far my code is like this. It appears to be ok in the x direction, but as soon as one tile goes completely above the top of the screen, the entire column disappears. I am not sure how to detect that all of the tiles in a particular column are outside the visible region. double maxTilesX widthOfScreen halfTileWidth 4 double maxTilesY heightOfScreen halfTileHeight 4 int rowStart Math.max(0,( xOffset halfTileWidth)) int colStart Math.max(0,( yOffset halfTileHeight)) rowEnd (int) Math.min(mapSize, rowStart maxTilesX) colEnd (int) Math.min(mapSize, colStart maxTilesY) EDIT I think I have solved my problem, but perhaps not in a very efficient way. I have taken the center of the screen coordinates, determined which tile this corresponds to by converting the coordinates into cartesian format. I then update the entire box around the screen."} {"_id": 45, "text": "How can I implement (almost) infinitely large maps in Unreal Engine 4? I'm making a game where a helicopter travels around. I'd like that the environment around be as realistic as possible. For instance, since the helicopter can travel at speeds up to 200 km h, I want the player to see very far away, in a realistic fashion. I'm talking about a map where let's say there is a \"real\" mountain 50km away and you could \"walk\" there, as well as the mountain looking like a mountain in game from the any distance (no matter the quality). How could I manage my map in UE4 that would allow me to implement such a \"real\" world?"} {"_id": 45, "text": "Best way to let the player know there are multiple solutions to a problem?(and force them to play again) I am going to work on a map for my game that is in first person mode. This is the story(planned). He is on a sinking ship and he wants to escape before the ship sinks. He has a few ways of doing so, either with the on board seaplane or an emergency raft. Both methods will lead the player to different maps in the game. So here is the question How can I notify the player that there is another way of \"winning\" the map if he chooses one. I do not want to just pop out and say \"hey you could have used the boat\" or even include a progress map of some sorts, but I still want the player to visit the map again in the future to figure out the paths. Any suggestions would be awesome. The lighting would be dimmer as the scene is set at night. There will be blood, grease and other dirty stuff on the player's screen. The ship itself is most probably going to wobble around. edit Sorry that I didn't clarify, but I want to know methods to lure players to play the map again. Methods of letting the player know that there are different methods works, but I think that should not be the only method. I'll change the title."} {"_id": 45, "text": "How can I build a graphical map for my MUD engine? I am working on a text based game totally from scratch and one thing I am not sure how to do is the map system. In my mud engine totally writen in Javascript (that will be executed in a Node.js environment), I use that kind of data to design an area and the links between rooms. 003 004 001 002 007 005 006 var map \"001\" \"Id\" \"001\", \"Name\" \"Room 001\", \"Directions\" \"N\" \"\", \"S\" \"\", \"E\" \"002\", \"W\" \"\" , \"002\" \"Id\" \"002\", \"Name\" \"Room 002\", \"Directions\" \"N\" \"003\", \"S\" \"005\", \"E\" \"\", \"W\" \"001\" , \"003\" \"Id\" \"003\", \"Name\" \"Room 003\", \"Directions\" \"N\" \"\", \"S\" \"002\", \"E\" \"004\", \"W\" \"\" , \"004\" \"Id\" \"004\", \"Name\" \"Room 004\", \"Directions\" \"N\" \"\", \"S\" \"007\", \"E\" \"\", \"W\" \"003\" , \"005\" \"Id\" \"005\", \"Name\" \"Room 005\", \"Directions\" \"N\" \"002\", \"S\" \"\", \"E\" \"006\", \"W\" \"\" , \"006\" \"Id\" \"006\", \"Name\" \"Room 006\", \"Directions\" \"N\" \"007\", \"S\" \"\", \"E\" \"\", \"W\" \"005\" , \"007\" \"Id\" \"007\", \"Name\" \"Room 007\", \"Directions\" \"N\" \"004\", \"S\" \"006\", \"E\" \"\", \"W\" \"\" On the MUD game I am actually playing, the mud command display something like this I would like to know in pseudo code the way to do this in the most efficient way. Please note that it has a maximum character length for each lines and that the map is centered around You ( ). Thank you for your help!"} {"_id": 45, "text": "What is a good format for a 3d topview map? I am building a 3d topview game like GTA2. In this game the ground is mostly one level (except for tunnels and highways). Most of the ground is also city so the ground is usually covered by either roads or buildings. The buildings are simple 3d models which the player can walk around on. Most of the gameplay is 2d. How should I model the map? I have considered the following options Bitmaps, I think this gives problems when I want to add data smaller than a tile. Also the problem of bridges and tunnels seems hard to solve with this. Polygons, define all roads, terrain types, buildings with polygons and save that along with physics and texture information. What approach would you take or have you ever implemented this or know of an implementation?"} {"_id": 45, "text": "How do RPG store and retrieve maps? I'm making a very basic online RPG (2d, and instead of sprites I use characters, like a roguelike) and I still haven't figured out how to store and retrieve maps. Until now I used a text file that are stored on the server. Should I store the map in the database and retrieve it as the player moves around? For example, if the player is in the position x, y , load all the tiles within a 15 tile radius. Or maybe dividing the map in \"sections\" and then, depending on the player's location load a given section? Which is the best option? Also, if I was to save the map in the database, which is the best data type to store it as a bi dimensional array? BLOB maybe?"} {"_id": 45, "text": "Vertical vs horizontal hex grids, pros and cons With hex grids, you can choose to arrange the tiles with the pointy sides up, so that you can move along the west east axis, or you can arrange them with an edge up, so that you can move along the north south axis. Horizontal or pointy side up hex grid Vertical or flat side up hex grid According to this page, the vertical alignment is \"by far the most popular\" in pen and paper RPGs, but it doesn't explain why. This blog post also mentions both varieties, but again gives no reason to use one or the other. And if you look at some PC games using hexes, it seems both have their adherents Horizontal Heroes of Might and Magic series (except V), Civilization V... Vertical Panzer General and many similar wargames, Battle for Wesnoth... But what are the main reasons for choosing a vertical or a horizontal layout of hex grids? I'm looking for objective advantages and disadvantages in terms of data structures, graphics, gameplay, etc, not personal preferences. Or is it really inconsequential which orientation you choose?"} {"_id": 45, "text": "How do I show the current view from the viewport on my map? I'm doing HTML5 Canvas development and currently have a large viewport (on the left) and a map (on the right). Like this I need to show on the map what is currently being viewed in the left. And I'm at a lost on how to calculate this. This is how I want it to be I am manipulating the main viewport via a transformation matrix. like 1, 0, 0, 1, 0, 0 This is decently common functionality in different games and apps. So I assume there are resources on how to do it. But I haven't been able to find any."} {"_id": 45, "text": "How to make a map (game world) based on a real world place or city? As a disclaimer before my real question, I have little experience in game development, only basic Unity knowledge. I noticed a lot of games are based on real world places and cities, for example GTA 5 on Los Angeles and Watch Dogs. What is the process of making such a virtual version of a real world place or city? Or at least, what is a good starting point? I imagine you could get some sort of map data or satellite images and import this in a tool, from which you can start modelling the buildings etc. But if this is the case I don't know how to do that."} {"_id": 45, "text": "Generating a map in runtime for a simple top scrolling racing game I'm creating a simple top scrolling racing game. The concept is quite simple the player controls the car, which goes on a dynamically generated field with square blocks. Once the car hits a car, the game ends. My first implementation was simply to put a few random blocks in each row being generated on the top of the screen, but this does lead to maps where going through is impossible. What is the best algorithm for generating such type maps? My platform of choice is XNA and C , if that's important. EDIT Here's an illustration (pic) In this case, there's no possible way for the player to pass."} {"_id": 45, "text": "Good basemap generator I am currently making a board game and cannot seem to find any vector world map creators where I can select a region of the world to capture and have it download that section. I just want a base map so no city names and preferably no borders. The map doesn't have to be vector if it is of good enough quality."} {"_id": 45, "text": "Generating a map in runtime for a simple top scrolling racing game I'm creating a simple top scrolling racing game. The concept is quite simple the player controls the car, which goes on a dynamically generated field with square blocks. Once the car hits a car, the game ends. My first implementation was simply to put a few random blocks in each row being generated on the top of the screen, but this does lead to maps where going through is impossible. What is the best algorithm for generating such type maps? My platform of choice is XNA and C , if that's important. EDIT Here's an illustration (pic) In this case, there's no possible way for the player to pass."} {"_id": 45, "text": "Good map file structure? I need a map file structure for my game but does anyone know a good way to map it out? I was thinking something like this name MyMap add floor stone solid 20, 640 add playerspawn 20, 620"} {"_id": 45, "text": "Spherical map representation My latest game will take place on a small planetoid. I am looking for good data structure for representing cells on the surface of a sphere. Triangles, squares, pentagons, hexagons? Which one minimises stretch the most and creates the best tiling? Spherical mapping is the easiest but the stretch at the poles is unacceptable. Cubemapping is also fairly easy but there would still be considerable stretch near the cube corners. Subdividing an icosahedron seems the best in terms of stretch but there is the problem of indexing many triangular arrays and finding neighbouring cells at the boundaries would be difficult. I guess I could use a single linear array of points representing N gons, each with an array of N neighbour indices, but that seems like a huge waste of space. The game has RTS elements so I will be storing things like influence maps and performing A pathfinding and convolution, so the representation has to be efficient."} {"_id": 45, "text": "How can randomly paired players fairly select a map? I'm developing a website for a board game that revolving around user created boards. Matches are currently created by selecting two people who have been waiting in a queue the longest and creating a match for them. We will later implement matchmaking with specific users. What is an appropriate way to select a map when a match is created with two random people? Should one player be allowed to pick the map? Should a random map be selected? Maybe the players should rank a collection of popular boards by preference, then select the one with the highest average rating?"} {"_id": 45, "text": "Entity position In map or in script? I'd like to know how others have handled the issue of storing the entity's position. (Or maybe it's not an issue and I just make it too complicated.) I'm undecided on whether to store the position of each entity in the world map file or in the entity's script file. From what I figured, both approaches have their own good and bad points If you store the entity's position in the map Good Easier to edit the map you can see where the entity will be. Maybe this isn't a problem for integrated map editors, but I'm using an external, general purpose map editor (GLEED2D). Bad Inside the game it's easier to handle data if the position is inside the entity object, not the map object. So when you load the game, you have to gather data from a lot of places to build your entity object. On the other hand, if you store the position inside the entity script, the advantages and disadvantages are exactly the opposite of the above."} {"_id": 45, "text": "Alternative ways to construct maps I've searched around and it seems like most people are using tile based map systems. I suppose, this question is more theoretical than practical (I am not very concerned about memory or performance speed), but I want to know what other ways can a map be created in a game? A map being a graphic representation of terrain that can be navigated, has entrances and exits, and boundaries (no go zones). Besides using text files to store and arrays to load tile data, one idea I had, was to store a map entirely as a graphic file and use queries on the pixel colour to determine boundaries (i.e. you can only move in a certain direction if the way is bright enough in that direction). What other creative map systems are out there?"} {"_id": 45, "text": "How can I implement (almost) infinitely large maps in Unreal Engine 4? I'm making a game where a helicopter travels around. I'd like that the environment around be as realistic as possible. For instance, since the helicopter can travel at speeds up to 200 km h, I want the player to see very far away, in a realistic fashion. I'm talking about a map where let's say there is a \"real\" mountain 50km away and you could \"walk\" there, as well as the mountain looking like a mountain in game from the any distance (no matter the quality). How could I manage my map in UE4 that would allow me to implement such a \"real\" world?"} {"_id": 45, "text": "1D Terrain Generation in Java Not able to implement Perlin Noise for 1D Random Terrain Generation. I've tried everywhere and I cannot find anything useful, sure I sort of understand Perlin Noise but everytime I try it nothing works. I'm using LibGDX in Java if that helps, thanks. Here is the code for P.N. static float Noise(int x) x (x lt lt 13) x return (float) (1.0 ((x (x x 15731 789221) 1376312589) amp Integer.MAX VALUE) 1073741824f) public static float PerlinNoise1D(float x, float persistence, int octaves) float total 0 float p persistence int n octaves 1 for (int i 0 i lt n i ) float frequency (float) Math.pow(2, i) double amplitude Math.pow(p, i) total InterpolatedNoise(x frequency) amplitude return (int) total private static float InterpolatedNoise(float x) int integer X (int) x float fractional X x integer X float v1 SmoothNoise1D(integer X) float v2 SmoothNoise1D(integer X 1) return CosineInterpolate(v1, v2, fractional X) public static float CosineInterpolate(float a, float b, float x) float ft (float) (x Math.PI) float f (float) ((1 Math.cos(ft)) 0.5) return a (1 f) b f public static float SmoothNoise1D(int x) return Noise(x) 2 Noise(x 1) 4 Noise(x 1) 4 and here is the code for the for loop used to render the tiles (assuming my tiles are 32px x 32px) for (int i 0 i lt Gdx.graphics.getWidth() i ) float y PerlinNoise1D(i, 5f, 3) for (int j (int) (y) j lt Gdx.graphics.getHeight() j ) hudBatch.begin() hudBatch.draw(hp, i, j) hudBatch.end() j 31 i 31 P.S I'm sort of trying to create a terraria like game."} {"_id": 45, "text": "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. But for now, I'm stuck with something I can't figure how it is done How are building interior handled ? Here's a screenshot to illustrate what I say When 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. Sometimes 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 Teleport 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. Section 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. How can I create this kind of transition? I've specified that I am on Unreal, but I'm more searching the theorical way rather than Unreal specifics."} {"_id": 45, "text": "How to write a custom map canvas and project coordinates on it? I am writing a game with Objective C ( xcode ) and I need to use the users location service to mark their position on a map but since I need to create my own map component, I am not able to use the Map framework. Doing this I think I need to project latitude and longitude which I receive from location framework on my custom planar canvas, this is a small part of my game but the other parts are pretty easy or could be done if I could manage to implement this part, however I dont know where to start. did anybody does it before? is it easy to create a map canvas? Any kind of hint and help or sympathy are welcome. Thanks"} {"_id": 45, "text": "Vertical vs horizontal hex grids, pros and cons With hex grids, you can choose to arrange the tiles with the pointy sides up, so that you can move along the west east axis, or you can arrange them with an edge up, so that you can move along the north south axis. Horizontal or pointy side up hex grid Vertical or flat side up hex grid According to this page, the vertical alignment is \"by far the most popular\" in pen and paper RPGs, but it doesn't explain why. This blog post also mentions both varieties, but again gives no reason to use one or the other. And if you look at some PC games using hexes, it seems both have their adherents Horizontal Heroes of Might and Magic series (except V), Civilization V... Vertical Panzer General and many similar wargames, Battle for Wesnoth... But what are the main reasons for choosing a vertical or a horizontal layout of hex grids? I'm looking for objective advantages and disadvantages in terms of data structures, graphics, gameplay, etc, not personal preferences. Or is it really inconsequential which orientation you choose?"} {"_id": 45, "text": "How to generate tile based natural looking map? I have a tile based map which I generate using interpolation of pixels on a reference bitmap into appropriate tiles depending on the color of the pixel. I'm trying to make the output look natural in which blocks of similar tiles look like they are forming a single entity as in the following image While my version only puts static sprites onto aligned cells, the second image takes forest tiles and smashes them together like a whole single forest. The same is done for the water area. Could someone explain or point me somewhere where I can learn how to make the result of the first image look like the second? Thank you Also, how are the seamless road connections done in the above image?"} {"_id": 45, "text": "How to use the SDL viewport properly? I'm very confused about the SDL2 viewport, I did some googling to find out how to implement it but people keep mentioning things like \"world coordinates\" which I don't have in my game. Question Do I even need world coordinates for the SDL2 viewport to work? If yes, how do I implement it? I've currently got a problem where if my viewport goes too much to the right or down, the entire window will become green, kinda like if it stopped rendering all my sprites. Here's a GIF to show you what I mean As you can see, whenever I go too much to the right or down the entire screen goes green. I thought this maybe was beause of me not using world coordinates, but I have no idea I'm just guessing stuff at this point... My current codes for moving the viewport, drawing it, and such looks like this Creating the viewport camera Camera Camera(Uint16 x, Uint16 y, Uint16 w, Uint16 h) Sets up the viewport positions and sizes viewport.x x viewport.y y viewport.w w viewport.h h Sets the viewport so that SDL uses it SDL RenderSetViewport(Window GetRenderer(), amp viewport) Drawing the viewport (gets called every frame) void Camera DrawCameraViewport() SDL RenderSetViewport(Window GetRenderer(), amp viewport) I set the cameras position during runtime like this void Camera SetCameraPosition(int x, int y) viewport.x x viewport.y y And here's how I set the cameras position using the above function Note Sorry, the line became giantic... camera gt SetCameraPosition( SpriteManager GetPlayerSprite() gt GetPosition().x Window GetWindowMiddlePoint().x SpriteManager GetPlayerSprite() gt GetMiddlePoint().x , SpriteManager GetPlayerSprite() gt GetPosition().y Window GetWindowMiddlePoint().y SpriteManager GetPlayerSprite() gt GetMiddlePoint().y) Question Am I implementing the viewport correctly?"} {"_id": 45, "text": "Is there any way to convert .unr file? I'd like to examine a Harry Potter game for study purposes. All of resources are fine except map file. The maps are in a .unr file format. I know it is unreal map file. Is there any way to convert .unr file to .fbx, .obj, or pskx formats? I want to open map file to 3ds max or blender."} {"_id": 45, "text": "How to use the SDL viewport properly? I'm very confused about the SDL2 viewport, I did some googling to find out how to implement it but people keep mentioning things like \"world coordinates\" which I don't have in my game. Question Do I even need world coordinates for the SDL2 viewport to work? If yes, how do I implement it? I've currently got a problem where if my viewport goes too much to the right or down, the entire window will become green, kinda like if it stopped rendering all my sprites. Here's a GIF to show you what I mean As you can see, whenever I go too much to the right or down the entire screen goes green. I thought this maybe was beause of me not using world coordinates, but I have no idea I'm just guessing stuff at this point... My current codes for moving the viewport, drawing it, and such looks like this Creating the viewport camera Camera Camera(Uint16 x, Uint16 y, Uint16 w, Uint16 h) Sets up the viewport positions and sizes viewport.x x viewport.y y viewport.w w viewport.h h Sets the viewport so that SDL uses it SDL RenderSetViewport(Window GetRenderer(), amp viewport) Drawing the viewport (gets called every frame) void Camera DrawCameraViewport() SDL RenderSetViewport(Window GetRenderer(), amp viewport) I set the cameras position during runtime like this void Camera SetCameraPosition(int x, int y) viewport.x x viewport.y y And here's how I set the cameras position using the above function Note Sorry, the line became giantic... camera gt SetCameraPosition( SpriteManager GetPlayerSprite() gt GetPosition().x Window GetWindowMiddlePoint().x SpriteManager GetPlayerSprite() gt GetMiddlePoint().x , SpriteManager GetPlayerSprite() gt GetPosition().y Window GetWindowMiddlePoint().y SpriteManager GetPlayerSprite() gt GetMiddlePoint().y) Question Am I implementing the viewport correctly?"} {"_id": 45, "text": "Good basemap generator I am currently making a board game and cannot seem to find any vector world map creators where I can select a region of the world to capture and have it download that section. I just want a base map so no city names and preferably no borders. The map doesn't have to be vector if it is of good enough quality."} {"_id": 45, "text": "Difference between orthogonal map and isometric map I am laughing at myself ignorant on this. Google didn't produce an obvious answer. Could someone explain what orthogonal map and isometric map are, and how they are different?"} {"_id": 45, "text": "Finding the scale of pixels in map with given dimensions For the game I am making, I have textures for planets. Each texture has a size of 2048 x 1024 pixels. I also know the size, thus the diameter, of each planet. Not every planet is the same size, you know. What is the size in kilometers of one pixel? I know it has to do with the circumference but I'm not sure this translates into a scale. For example, let's say a planet is 18,872 km in size, so it's a circumference of about 59258,08 km (diameter PI). Can anyone provide pointers in the right direction?"} {"_id": 45, "text": "Can custom maps in Starcraft 2 automatically enable certain unit upgrades? If I create a custom map with the Starcraft 2 map editor, how can I specify that some unit upgrades are already researched? For example, if I want all the units to already have the weapons upgrade 1 at the beginning of the game, can I specify this in the editor? I've looked through the menus but didn't find anything that looked like it would relate to unit upgrades."} {"_id": 45, "text": "3d game terrain creation approach I want to create a terrain world map for my 3d game. I want a huge map. For example, ill make it in Blender or generate from a heightmap. Then I plan to divide it in chunks so I can load unload and show hide them when needed in the game. If I want to remake the map, then I will have to divide it in chunks again, and again spend time on placing world objects on the terrain. I'm not sure that is the best way. What approach is optimal here?"} {"_id": 45, "text": "Level Map file creation and processing with OpenGL How do levels maps work in the game development world? Counter strike, which is a popular FPS that uses OpenGL as it's graphics library, has it's levels maps created as .bsp files. How do you create files like this, and use OpenGL to load them? Thanks!"} {"_id": 45, "text": "Best way to let the player know there are multiple solutions to a problem?(and force them to play again) I am going to work on a map for my game that is in first person mode. This is the story(planned). He is on a sinking ship and he wants to escape before the ship sinks. He has a few ways of doing so, either with the on board seaplane or an emergency raft. Both methods will lead the player to different maps in the game. So here is the question How can I notify the player that there is another way of \"winning\" the map if he chooses one. I do not want to just pop out and say \"hey you could have used the boat\" or even include a progress map of some sorts, but I still want the player to visit the map again in the future to figure out the paths. Any suggestions would be awesome. The lighting would be dimmer as the scene is set at night. There will be blood, grease and other dirty stuff on the player's screen. The ship itself is most probably going to wobble around. edit Sorry that I didn't clarify, but I want to know methods to lure players to play the map again. Methods of letting the player know that there are different methods works, but I think that should not be the only method. I'll change the title."} {"_id": 45, "text": "Is there any way to convert .unr file? I'd like to examine a Harry Potter game for study purposes. All of resources are fine except map file. The maps are in a .unr file format. I know it is unreal map file. Is there any way to convert .unr file to .fbx, .obj, or pskx formats? I want to open map file to 3ds max or blender."} {"_id": 45, "text": "How can I create a Killing Floor map? I'm trying to create a Killing Floor map and i have the latest Unreal Engine but i dont know how to export my map to Killing Floor. Where can i find the correct version of Unreal Editor ? How can i export my map with current version ?"} {"_id": 45, "text": "Is there any way to convert .unr file? I'd like to examine a Harry Potter game for study purposes. All of resources are fine except map file. The maps are in a .unr file format. I know it is unreal map file. Is there any way to convert .unr file to .fbx, .obj, or pskx formats? I want to open map file to 3ds max or blender."} {"_id": 45, "text": "Heightmap generation I want to implement something like this to create a heightmap 'Place a group of coordinates evenly across a map, and give them height values within a certain range. Repeatedly create coordinates between all of those coordinates, setting their height by deriving a value that was a mean value of all the surrounding coordinates.' However, I'm not sure how I would go about it I'm not sure how I could code the part where I place the coordinates in between the existing coordinates. Can anyone give any help advice?"} {"_id": 45, "text": "Best way to solve tile drawing in 2D side scroller? What i still can't figure out is which would be the more sane way easier and faster way to draw the map on the screen.. I mean i will use many tiles for my maps in my side scroller.. But problem is should i make the maps in whole images like one .png file for each map (Example) or should i draw the tiles by code like a for loop in c .. Which way is most recomended or where can i read about which way is the best."} {"_id": 45, "text": "storing map data as file in 3d roguelike games I'm currently designing 3d roguelike game. I need to come up with a map storing system but I'm quite new to game programming so I don't really know how to design. The map will be relatively small, it's not open world. I think it would be just like 3d version of The Binding of Isaac with first person perspective. I want to store map data as a file(e.g txt) but I don't know how to order them and what is necessary to store. Answers with some examples would be very appreciated."} {"_id": 45, "text": "Fair spawning of players on a 2D grid As new players enter a game, they are given a location on a large grid. The first player is given the location in the center. Now, how should the second player be placed? Then, the third and so on? New players should be placed reasonably near some other players, but not so close as to cause bunching. My current thinking is to trace a clockwise spiral around the first player, gradually moving further and further out from that initial point. But I keep thinking this must have been done before and that a general solution must exist. This is for a strategy resource game (similar to CoC or Throne Wars etc). How do I do this?"} {"_id": 45, "text": "Good map file structure? I need a map file structure for my game but does anyone know a good way to map it out? I was thinking something like this name MyMap add floor stone solid 20, 640 add playerspawn 20, 620"} {"_id": 45, "text": "storing map data as file in 3d roguelike games I'm currently designing 3d roguelike game. I need to come up with a map storing system but I'm quite new to game programming so I don't really know how to design. The map will be relatively small, it's not open world. I think it would be just like 3d version of The Binding of Isaac with first person perspective. I want to store map data as a file(e.g txt) but I don't know how to order them and what is necessary to store. Answers with some examples would be very appreciated."} {"_id": 45, "text": "Heightmap generation I want to implement something like this to create a heightmap 'Place a group of coordinates evenly across a map, and give them height values within a certain range. Repeatedly create coordinates between all of those coordinates, setting their height by deriving a value that was a mean value of all the surrounding coordinates.' However, I'm not sure how I would go about it I'm not sure how I could code the part where I place the coordinates in between the existing coordinates. Can anyone give any help advice?"} {"_id": 45, "text": "What are the most common ways of closing an open world? In many open world games, there are several ways to limit them. From original ones such as Desynchronisation(Assasins' Creed) to invisible walls. What are the most common ways to close open worlds?"} {"_id": 45, "text": "Using a permutation table for simplex noise without storing it Generating Simplex noise requires a permutation table for randomisation (e.g. see this question or this example). In some applications, we need to persist the state of the permutation table. This can be done by creating the table, e.g. using def permutation table(seed) table size 2 10 arbitrary for this question l range(1, table size 1) random.seed(seed) ensures the same shuffle for a given seed random.shuffle(l) return l l see shared link why l l is a detail and storing it. Can we avoid storing the full table by generating the required elements every time they are required? Specifically, currently I store the table and call it using table i (table is a list). Can I avoid storing it by having a function that computes the element i, e.g. get table element(seed, i). I'm aware that cryptography already solved this problem using block cyphers, however, I found it too complex to go deep and implement a block cypher. Does anyone knows a simple implementation of a block cypher to this problem?"} {"_id": 45, "text": "How to generate tile based natural looking map? I have a tile based map which I generate using interpolation of pixels on a reference bitmap into appropriate tiles depending on the color of the pixel. I'm trying to make the output look natural in which blocks of similar tiles look like they are forming a single entity as in the following image While my version only puts static sprites onto aligned cells, the second image takes forest tiles and smashes them together like a whole single forest. The same is done for the water area. Could someone explain or point me somewhere where I can learn how to make the result of the first image look like the second? Thank you Also, how are the seamless road connections done in the above image?"} {"_id": 45, "text": "storing map data as file in 3d roguelike games I'm currently designing 3d roguelike game. I need to come up with a map storing system but I'm quite new to game programming so I don't really know how to design. The map will be relatively small, it's not open world. I think it would be just like 3d version of The Binding of Isaac with first person perspective. I want to store map data as a file(e.g txt) but I don't know how to order them and what is necessary to store. Answers with some examples would be very appreciated."} {"_id": 45, "text": "What is a good format for a 3d topview map? I am building a 3d topview game like GTA2. In this game the ground is mostly one level (except for tunnels and highways). Most of the ground is also city so the ground is usually covered by either roads or buildings. The buildings are simple 3d models which the player can walk around on. Most of the gameplay is 2d. How should I model the map? I have considered the following options Bitmaps, I think this gives problems when I want to add data smaller than a tile. Also the problem of bridges and tunnels seems hard to solve with this. Polygons, define all roads, terrain types, buildings with polygons and save that along with physics and texture information. What approach would you take or have you ever implemented this or know of an implementation?"} {"_id": 45, "text": "Is there any way to convert .unr file? I'd like to examine a Harry Potter game for study purposes. All of resources are fine except map file. The maps are in a .unr file format. I know it is unreal map file. Is there any way to convert .unr file to .fbx, .obj, or pskx formats? I want to open map file to 3ds max or blender."} {"_id": 45, "text": "Level Map file creation and processing with OpenGL How do levels maps work in the game development world? Counter strike, which is a popular FPS that uses OpenGL as it's graphics library, has it's levels maps created as .bsp files. How do you create files like this, and use OpenGL to load them? Thanks!"} {"_id": 46, "text": "How to split login and game logic when writing servers? I'm building a poker like game server, I was going to have all logins and game logic to be handled on one server, but from my research on the web, I learn that this would not scale, and it would make sense to split the work into a login and game servers. But what I don't get is after I handled authentication in the login server, and have the client make a new connection to the game server, how would I know which client is which? Would I not have to re login again and thus defeat the purpose of having a server for login? Is there some way to pass a connection across processes and machines that I don't know about? Excuse my little knowledge of networking."} {"_id": 46, "text": "How should I configure firewall for online game server? I'm complete newbie on game server work. As I know, online (massively multiplay) game server should keep some TCP or UDP connection from the user. As I ( newbie) guess, maybe huge count of socket port should be opened. So how should I configure firewall for game server? Or should I use some other special method to security? Any advise will be appreciated."} {"_id": 46, "text": "how to check if a gameserver can handle clients before game release? we are developing an iOS based game with multiplayer support. so far everything seems real good but now we want to make sure if server could handle 10000 clients or not. any idea how can I make sure server will survive that much traffic?"} {"_id": 46, "text": "How do I write a game server with single threaded networking? I want to write a game server with one thread for clients message handling and use something like epoll to accept network messages. All I O and database access will be processed in a thread pool and they are asynchronous and non blocking. Given such a scheme, how should I handle other events messages (physics, game logic, etc)? Can I implement methods to handle these messages as a blocking interface in the main thread? What simple, popular servers exist (using Cocos d Unity as client) that I could look at for an example of this?"} {"_id": 46, "text": "How to prevent attackers from compromising multiplayer game servers? Consider a relatively small multiplayer game server, written by an individual or a small company. Some malicious user wants to boost their character stats by a factor of 100. What paths of attack might they have and what are the most important safeguards to prevent these attacks?"} {"_id": 46, "text": "Where should I place input output console for server? I'm developing a simple 2d online game and now I'm designing my server. The server will be run on linux vps and I need a way to communicate with it (for example to close it, and as it will be run on vps, simply closing terminal won't work). So I think there are 2 options 1) Write 2 apllications server which doesn't say anything and doesn't accept console input and the second application is console which sends commands to server (like exit, get online players etc). 2) Have 2 threads on the server appplication one is the real server, the second thread will be used for cin and cout. However I'm not sure if this will work on vps... Or maybe there is better aproach? What is the usual way of doing this?"} {"_id": 46, "text": "How do I resolve asynchronous client actions against an authoritative server state? I have a multiplayer card game which I am in the process of developing. The game is relatively simple players have a certain number of cards which they can activate, sell, or use in various other ways. The game isn't turn based. Instead, it is asynchronous so that players (A, B, C, and D) all make their choices at the same time. Certain actions will affect the game state. For example, removing a card from the game or adding a card to the game. Players should always be in sync with each other so that, for instance, Player A cannot use a card that Player B has just removed, as it is no longer present. Obviously there are situations in which Player A may remove a card at nearly the same time that Player B tries to interact with the same card. How would the server handle this sort of situation? My original thought is that each client could hash their game state and send it with their command to the server, for example Player A MYHASH Command Pick Up Card Z Player B MYHASH Command Remove Card Z The server would then action the first command and regenerate the hash. Upon trying to execute the second command it would notice the hash sent by Player B differs from the current hash, so the server would reject the request. In the above example Player A would notice nothing and the game would continue normally, but Player B would have to be informed that their action failed."} {"_id": 46, "text": "How to make hard to hack leaderboards Okay, someone tasked me to make a leaderboard for their game. However, the one I have right now is really insecure. All it does is check if someone is in the top 100, and if they are, post the score to the server, where the server will completely trust the client to give a real score. My question is How would I make it harder, or better, impossible, to send a fake high score, because right now they can just post a value to an easy to find endpoint. Clarifications The game is running in an interpreted environment, therefore obfuscation is not practical, and the game has a lot of input (an hour's worth at least), so sending that to the server is also impractical."} {"_id": 46, "text": "how to check if a gameserver can handle clients before game release? we are developing an iOS based game with multiplayer support. so far everything seems real good but now we want to make sure if server could handle 10000 clients or not. any idea how can I make sure server will survive that much traffic?"} {"_id": 46, "text": "Choosing a server for a PVP game So I am starting a game with a friend as a small project, and we are considering what game servers would we need. Firstly, the game is a multiplayer(player vs player) game, for example, like an online chess game. However it is real time, so the latency cannot be too high. The players basically take turns, but in a real time fashion. The platform is going to be Android (and perhaps extend to iOS in the future) The server would need to synchronize the players' moves to each other devices. I don't really need anything large scale and I am thinking of using PHP since the volume of data isn't really that big, this is like a web based game with a requirement of a slightly lower latency. What would be the advantages and disadvantage of using Apache PHP for a game like this? If that seems to be a bad choice, I would be grateful if you can share your experience with me. Thank you. (We are both programmers and we are familiar with Java C Obj C Apache PHP Tomcat JSP Javascript)"} {"_id": 46, "text": "Is it possible to rent a server for my own game? I'm an independent game developer and I don't yet have a lot of money to buy myself a very cool high speed and low latency internet connection along with a powerful server machine to place somewhere in the world to host my very own game's server application for my fans to play on. I know it's possible to rent a server for an existing popular game (for example, Team Fortress 2), but how about renting a server for my own game that I'm developing? Are there services specifically for that, or should I just rent some general purpose something and go from there? Such a server should be Easy to update With a low latency for a specific region (I'm planning on renting EU and US servers)"} {"_id": 46, "text": "Can you recommend a game server for a facebook board game? I am seeking a game server that will scale well. All commercial and or free software alternatives are welcome. Game will be a boardgame that is similar to poker. Some technical details are listed below. There will be a table which consists of 4 people, to send them message I need a channel manager. A table will be ready to play for at least 5 minutes. There should be a reliable channel manager. People will wait for some time(i.e.) and if they are not playing they will be kicked by server, so there will be a reliable timed task queue to execute some tasks. It should be quick enough to response and show the changes to all 4 people on that table simultaneously.To achive this server should have a powerfull I O library. I think to use inmemory to have quick response times, but it comes with scalability problems. And some variables should be thread safe so a variable should be thread safe between multiple nodes. Flash(AS3) and Unity (.Net 2.0 C mono) client API's should be available for socket connection. PS I am using Reddwarf server, it lacks of documentation and multiple node."} {"_id": 46, "text": "When to read write to database with a game server My question is fairly simple but maybe hard to answer. I'm currently building my own game server and I've done to login server now. So, on to the actual game server. I have a question for this server though. Say, a thousand players are moving around on this server, how do I manage this with the database (MySQL) that should hold the player positions and such? I understand I can't query the database every time something small changes or a single player moves because that would be a huge load for that server. How is this done in real game servers? When do they read or write to the database?"} {"_id": 46, "text": "How can one add a level to an already published ios android unity3D game on a daily basis? How can one add a level to an already published iOS Android Unity3D game on a daily weekly basis? I know this probably isn't feasible but it won't harm if I just made sure of it. Our game requires to allow access to just one level a day week. You may access levels that were released on previous days and play to your heart's content but all players will get access to a new level every day week. I know this may sound crazy but the concept requires it so just roll with me. Is there anyway to achieve this for iOS Android games built with Unity? Of course, we could package a whole game with 10 levels and allow access to each level after a set time, but the game will need to talk to a back end CMS all the time to allow login and verification of users, make sure they aren't cheating, etc, etc, over proper security and https (proper anti cheat solutions are a must and that's why maybe HTML5 route is better). We are now moving towards doing all this in HTML5 and completely bypass Unity, but was hoping to find a solution with Unity because 3D is better than 2D depending on the situation, and some levels could be 3D while others 2D. Patching updating everyday to upload new levels won't go down well with anyone, the app stores or the users."} {"_id": 46, "text": "Distributed C game server which use database My C turn based game server (which uses database) does not stand against current average amount of clients (players), so I want to expand it to multiple (more then one) amount of computers and databases where all clients still will remain within single game world (servers will must communicate with each other and use multiple databases). Is there some tutorials books common standards which explain how to do it in a best way?"} {"_id": 46, "text": "How can I stress test my sever for the game Rust? I am looking to stress test my server for the game Rust and monitor CPU, RAM and FPS. I could not find much around. I general I think I will need a good amount of compute power, bunch of cloud based VM which generate the load through UDP using some headless client. Monitoring CPU and RAM should be fairly easy, but how about the in game FPS? Also I could not find much about Rust clients that could simulate a player."} {"_id": 46, "text": "How should I implement lag compensation in my racing game? I've looked around and I see a lot of discussion about lag compensation for FPS's, but none for racing games. I know Mario Kart uses some sort of interpolation for other racers, but it doesn't provide very smooth results a lot of the times, when the simulated kart goes way off course and then teleports back on track with the next server update. I think games like Forza also use interpolation, but the cars in games like that move a lot more predictably, so it doesn't seem noticeable. If I'm going for a game with the same type of chaotic movement that of Mario Kart, will I just have to accept that there will be sudden visible teleporting when a player has a bad connection to the server?"} {"_id": 46, "text": "Do I need to create my own or use a commercial server for the features and matchmaking options I want my game to support? So I'm developing an indie turn based game for iOS and, in coding up a Game Center matchmaking class, I'm starting to question whether Game Center is even the best choice for what I want this game to do. I need to figure out whether I need to create my own server, invest in a preexisting client or server service, or if I even need to use a server at all. If I do need to use a ready made service other than Game Center, which server would accomodate my game's needs best? I have limited resources and funds. Here is the list of features I want my game to support, ideally Turn based gameplay (a la \"with Friends\" and \"with Buddies\" games) Smart matchmaking (matching users up with other players of comparable skill achievements) Random matchmaking Facebook matchmaking Specific username matchmaking Contact list matchmaking A way to select what \"type\" of match you want to challenge an opponent to. (In random, smart, and Facebook matchmaking, there will be different \"wagers\" the player can make. e.g. \"I wanna play a random opponent for 1000 points. Now, I wanna play my Facebook buddy for 1,000,000 points.\" There will be a predetermined range of amounts you can play for. It won't be customizable.) Buddies list capability (Game buddies, as opposed to contacts and Facebook) A higher concurrent game cap than Game Center offers (which I still can't really find a straight answer on) Scalability (it should support 2 or 20,000,000 players) Objective C compatibility Flexibility (for all the stuff I haven't thought of yet) Am I dreaming, here? Is there even a service that can handle all of these features? Do I need to invest months in learning a networking language to build my own? If so, how much would I need to spend on hardware? I've been looking around all morning and, so far, the only seemingly viable option is SmartFox. Under \"Everything and the kitchen sink\" section here, it says they support \"virtual world with Zones, Rooms and RoomGroups, create complex game challenges, send invitations, manage buddy lists, create custom permission profiles, oversee the security aspects and tons more.\" http www.smartfoxserver.com overview platform Is there an option that Im just overlooking? Thanks for any help anyone can provide. Sorry for the long poast. One last question Does anyone know which server Dice with Buddies uses? I was experimenting with how many concurrent games I could get going and my ADHD kicked in at about 80 games. 80 concurrent games would be great for my game, but again, I need the other features I mentioned too. Thanks again."} {"_id": 46, "text": "What's the best server architecture for real time games? I'm developing a Real Time game which should hold thousands of players in real time (FPS like. max 1s lag). What would be the best infrastructure for this? My idea was using 2 server clusters one for the Server End (all the computing side) and one for the Database end, where a load balancer is \"responsible\" for each of the clusters. One main server will receive the requests from the users and send back the IP address of the relevant server that the user can work this. The database cluster will use database replication for consistency between the databases. There should be a geographical load balancer as well so it will assign the regional load balancer to each user for best response. I'm using .NET MSSQL for the game. Thanks!"} {"_id": 46, "text": "How should I implement a timer in a strategy game? I'm developing a real strategy game for Android and want to implement timers. Those timers will represent the time remaining until some building is finished. Say that i have a building in construction that takes 45 minutes to be completed. How can I communicate this timer information between my client (Android app) my server and my database? Should I communicate to the server every second in which state my timer is? Should I even do this on the server (i.e., should the timer run on the client)? I'm inclined to assign this task to the server for security and integrity reasons, but i'm not sure on the way i can accomplish that."} {"_id": 46, "text": "how does server communication work in a flash game with a php backend I am trying to create a browser game using actionscript flash. Currently, I'm trying to understand how I would go about creating a back end which interfaced with my MySQL database. As far as I understand, If I create a php file on a webserver called test.php and then navigate to a webpage hosted on the server eg. www.example.com test, the php script will run and display the result in my browser. This would use http. Is this how communication between client and server usually works in a flash game? for example, if the game needed to query the db. Would actionscript have to essentially invoke the url of the php script that would execute the query? it could then parse the data and use it. If this is the case, then is JSON considered a good way to transfer data over http?"} {"_id": 46, "text": "Game server position tracking How would you go about determining a players position server side based off player input? The Setup Player sends packet to server containing the command and view angles. Server takes the direction and multiplies it by speed. Say a player is going up a hill. How would the server make the players position reflect that the player is going up a hill. The way i see doing is taking the ground height under the player and calculating if the height change in direction x is too high. However calculating that info for n players say 1000 would be very intense. So what is the proper way of determining a players position based on input with a client server setup with the server being authorative. There is 10 updates per second."} {"_id": 46, "text": "How to achieve game server redundancy? The game I'm developing has a simple game server which stores inventory and hero data for each user, as well as deciding the outcome of some random events. The server interacts with PostgreSQL and responds to HTTP queries. It runs on EC2 and Microsoft Azure, but these hosts sometimes become unreachable for a few minutes, and one week the EC2 server froze every day. What are the strategies to make sure a server is always available? Non solution Multiple servers with their own databases, and the client will try to connect to a different server after a timeout. Of course, their data will be absent if it's a different server. Solution 1 As above, except whenever player data changes, that change is stored, and each player's data is replicated to the other servers (bidirectionally). The disadvantage is that this solution is \"home grown\" and prone to mistakes. Solution 2 One primary server (let's leave sharding for later), and one or more backup servers, with the database being replicated. When the primary server becomes unreachable, a backup server is made into the primary server. Problems this needs additional technology for directing queries to the right server, and also to decide when a backup server needs to be promoted to primary. Can this \"manager\" also hang? It sure can if it's on AWS! That would bring the whole system down. Solution 3 We could pay for database hosting with some guarantee of reliability, and have multiple servers but just one database. We would assume the database is reliable (but still back it up). The user could connect to any reachable server, and the servers would not need to worry about having stale data, since there will be only one database. (Again, sharding is a separate problem, and we could just multiply the whole setup without fundamentally changing its architecture.) So how is reliability achieved when individual servers aren't reliable? I like solution 3 for its simplicity, if a 3rd party database can be relied upon."} {"_id": 46, "text": "How to design game server to mitigate DDOS attacks I'm in the design phase of a turn based game with low load on the server ( lt 1 message every 10 seconds per user, lt 50'000 users at a time). The game is multi platform. The protocol has not been decided yet. How can I mitigate DDoS attacks against such a server by design?"} {"_id": 46, "text": "Distributed C game server which use database My C turn based game server (which uses database) does not stand against current average amount of clients (players), so I want to expand it to multiple (more then one) amount of computers and databases where all clients still will remain within single game world (servers will must communicate with each other and use multiple databases). Is there some tutorials books common standards which explain how to do it in a best way?"} {"_id": 46, "text": "What are useful server metrics to gather for a table card game? When building a game server intended to accomodate large numbers of simultanous games (e.g. table card games), where the server manages lots of tables and each table has up to a small handful of users, what metrics are most useful to collect and why?"} {"_id": 46, "text": "what is the best way to code an online multiplayer game? so i want to create a simple game that runs over a network but I am having trouble deciding what needs to be done in terms of what the server needs to do and what the clients need to do. I understand I should use UDP sockets but I am unsure how to implement it within a game and have all the clients be in sync. Should the server side have like a master copy of the game where i basically runs the game and accepts moves, plays them in itself, and then sends the current state of the object to the other clients?"} {"_id": 46, "text": "Do I need a backend engineer for my studio right now? I am working on a mobile game that requires a well thought out backend, because it spans across the healthcare data science space and we need to be compliant in terms of security regulations in how we approach this. Think something like Fitbit. My team is nearly finished with the client side game aspect but I am wondering whether I need to take on a short term contract part time backend engineer to create our entire backend infrastructure OR someone who would work on this full time with our team. Here is what we would need to do Setup our entire backend infrastructure and plug this into Unity This would require knowing how to handle (transmit receive) data securely, and also perform computation with that data in the cloud Set up an API where other developers can query our data Set up our dev ops infrastructure (Docker, Jenkins) for the future The kicker here is that we are not yet live and are just in a testing phase. I don't want this to be 2 3 weeks of work, with no users for 3 more months while we're working on other aspects of the project, with the dude having nothing to do. Does this sound like a lot of work? Or could it easily take up a devs time for a month or two? Would a short contract be advisable here, or would it be better to hire someone FT and have them grow with us."} {"_id": 46, "text": "Do I need to create my own or use a commercial server for the features and matchmaking options I want my game to support? So I'm developing an indie turn based game for iOS and, in coding up a Game Center matchmaking class, I'm starting to question whether Game Center is even the best choice for what I want this game to do. I need to figure out whether I need to create my own server, invest in a preexisting client or server service, or if I even need to use a server at all. If I do need to use a ready made service other than Game Center, which server would accomodate my game's needs best? I have limited resources and funds. Here is the list of features I want my game to support, ideally Turn based gameplay (a la \"with Friends\" and \"with Buddies\" games) Smart matchmaking (matching users up with other players of comparable skill achievements) Random matchmaking Facebook matchmaking Specific username matchmaking Contact list matchmaking A way to select what \"type\" of match you want to challenge an opponent to. (In random, smart, and Facebook matchmaking, there will be different \"wagers\" the player can make. e.g. \"I wanna play a random opponent for 1000 points. Now, I wanna play my Facebook buddy for 1,000,000 points.\" There will be a predetermined range of amounts you can play for. It won't be customizable.) Buddies list capability (Game buddies, as opposed to contacts and Facebook) A higher concurrent game cap than Game Center offers (which I still can't really find a straight answer on) Scalability (it should support 2 or 20,000,000 players) Objective C compatibility Flexibility (for all the stuff I haven't thought of yet) Am I dreaming, here? Is there even a service that can handle all of these features? Do I need to invest months in learning a networking language to build my own? If so, how much would I need to spend on hardware? I've been looking around all morning and, so far, the only seemingly viable option is SmartFox. Under \"Everything and the kitchen sink\" section here, it says they support \"virtual world with Zones, Rooms and RoomGroups, create complex game challenges, send invitations, manage buddy lists, create custom permission profiles, oversee the security aspects and tons more.\" http www.smartfoxserver.com overview platform Is there an option that Im just overlooking? Thanks for any help anyone can provide. Sorry for the long poast. One last question Does anyone know which server Dice with Buddies uses? I was experimenting with how many concurrent games I could get going and my ADHD kicked in at about 80 games. 80 concurrent games would be great for my game, but again, I need the other features I mentioned too. Thanks again."} {"_id": 46, "text": "Where should I place input output console for server? I'm developing a simple 2d online game and now I'm designing my server. The server will be run on linux vps and I need a way to communicate with it (for example to close it, and as it will be run on vps, simply closing terminal won't work). So I think there are 2 options 1) Write 2 apllications server which doesn't say anything and doesn't accept console input and the second application is console which sends commands to server (like exit, get online players etc). 2) Have 2 threads on the server appplication one is the real server, the second thread will be used for cin and cout. However I'm not sure if this will work on vps... Or maybe there is better aproach? What is the usual way of doing this?"} {"_id": 46, "text": "How should I configure firewall for online game server? I'm complete newbie on game server work. As I know, online (massively multiplay) game server should keep some TCP or UDP connection from the user. As I ( newbie) guess, maybe huge count of socket port should be opened. So how should I configure firewall for game server? Or should I use some other special method to security? Any advise will be appreciated."} {"_id": 46, "text": "How should I store game data in a game server? I'm new to game server development. I'm facing this issue I want to develop a card game server, but I'm not sure about the solution to hold the game data while playing. Example In a poker game, when a player makes a move, the server will process the request and send it to all other players. But how will the game server know what the current state of the game is to do subsequent actions? Should I save all moves into database and server will look into it to know the current state?"} {"_id": 46, "text": "Keeping Players in Groups tl dr How can one enforce that groups of players stay together in units in Minecraft? I'm developing a plugin for a Minecraft server. It's based off feudalistic societies, like Ancient Europe or Japan. I understand that many ancient societies had advanced battle tactics (like this and this, for example). I think this is very interesting, and would add some more interest to a server. However, Minecraft isn't particularly well suited for this kind of play. Generally, in battles, all the players just run willy nilly and charge the enemy. There are no units of players, much less the units combining in a smart way to defeat the enemy. How can one enforce players staying together in one unit or group? Keeping each player in a certain position no matter what is not an option, since the players cannot PvP. Once players are grouped into units, I assume they will take up certain battle strategies and use them in a smart way."} {"_id": 46, "text": "Spreading server load for a multiplayer game My online game is more of a \"highly interactive website\", as it is played in browser using webpages and AJAX to communicate with the server, which uses PHP to generate output. The server is fairly standard, using PHP7, MariaDB, and Memcached (to avoid constantly reloading data from the DB, cache hit rate is about 95 ). All of this works. Fairly well, at that, and it can comfortably handle about 1,000 users actively hammering at the core gameplay element. The problem is that it's not scalable. The only scaling strategy we've had so far is \"throw stronger hardware at it\", which again works but it's not sustainable. I want to look into options for spreading the load over multiple servers, but it's daunting. Most of the game involves manipulating your own characters, and then visiting other player profiles to \"interact\" with their characters (which awards EXP and bonuses to both parties). There is also trading between players. Of course if this were just a regular website then I could probably just replicate everything and stick a load balancer in front of it, but I'm not sure that'll really work here. I think the most sensible option would be some system of assigning users to a specific server. When you log in a cookie is set to indicate which server you're on, which the load balancer can use to direct your actions to the server your data is on. When visiting another player's profile, the server will request that data from the other player's server. Things like trading will also be handled by having \"player one\" send a request to their server, which will communicate with \"player two\"'s server to move data around and complete the action. Is this realistic? Or am I overthinking it? Are there other options? Ideas?"} {"_id": 46, "text": "Synchronize turn based browser game I'm writing a browser game in php and Sql. I'm also using Javascript Ajax and Mysql. I'm stack on the battle system because I want to Synchronize the turns of the players in the battle. What I doing is to put two players on a battle. So from the first turn a countDown of 60sec will start. What I am thinking is to use a server function to check the countdown, not to the client side. This because I think that in that case a bad synchronization will came, instead if it is the server to count down. But.. how can I let the server do all this stuff?"} {"_id": 46, "text": "How do I write a game server with single threaded networking? I want to write a game server with one thread for clients message handling and use something like epoll to accept network messages. All I O and database access will be processed in a thread pool and they are asynchronous and non blocking. Given such a scheme, how should I handle other events messages (physics, game logic, etc)? Can I implement methods to handle these messages as a blocking interface in the main thread? What simple, popular servers exist (using Cocos d Unity as client) that I could look at for an example of this?"} {"_id": 46, "text": "Physics motor on servers, How a billiard server works? i'm trying to figure how a phisics game like billiard works in server side . I'm asking this cause i know how to achieve this in a client , but if i use a phisics motor i think it could be very heavy for a server when i want to have many people in the server. When i see this type of games, it use to be really fast , thinking that server is controlling the movements of course . Cause any other way maybe from client you could have been doing cheats. Then my questions are The server sends in this case, all ball movements? Are the server trusting in clients? In this case How to be sure a phisics motor doesn't have little error. (float decimals differences) And globaly How this type of server works?"} {"_id": 46, "text": "save player achievements in local device As an indie developer with zero dollar budget for servers and backend i wonder if there are ways to store the player achievements on his mobile device ?"} {"_id": 46, "text": "nodejs game server timer I'm new to game server develop. I'm developing a card game server. How could I make nodejs server wait for few seconds then push data to client after an event fired ? Example in poker game, one player have about 20 seconds to make a move, after 20 seconds server will auto fold and then push a message to another player. How could I make server wait for 20 seconds and then do next action ?"} {"_id": 46, "text": "Game server position tracking How would you go about determining a players position server side based off player input? The Setup Player sends packet to server containing the command and view angles. Server takes the direction and multiplies it by speed. Say a player is going up a hill. How would the server make the players position reflect that the player is going up a hill. The way i see doing is taking the ground height under the player and calculating if the height change in direction x is too high. However calculating that info for n players say 1000 would be very intense. So what is the proper way of determining a players position based on input with a client server setup with the server being authorative. There is 10 updates per second."} {"_id": 46, "text": "As an Independent Developer should I host my own official game servers My small team is approaching initial closed alpha for testing, however that has brought up the question of whether it is a good idea to host our official game instances from my home office or not. I've run a few dedicated servers before on my home PC (have 3 active as a service at the moment actually) so I'm not unfamiliar with the process. However I'm looking into building a server PC specifically to fulfill that singular purpose. I have google fiber 1000mbps so I don't think I'll have bandwidth issues. But I wonder if any of you have advice and insight into what I should expect, dangers to avoid, etc. Here's what I anticipate, am I missing anything? Masking home IP via dynamic DNS service (pointing to a website to login rather than an IP) Running multiple VMs on a single server to easily manage server resources Initially testing with a few selected users Eventually open up to more users once proven stable"} {"_id": 46, "text": "About online game servers and how to handle data So my question isn't about what technology to use or how to do this or that, but a more general question. I'm currently developing a action third person shooter. With elements of RPG weapon,armor upgrades and items. Players will be able to create new games or join old ones. So my question is how to create the game server that players will play in. I have two ideas on my mind. The player who made the game is the server. All data passes trough him and he send this data to the server updating the database of the players with their XP points kills deaths score and other. Or my host machine is the server, the player who made the game just will open new instance on my host and will be like client. And all players send their input data to the host, the host updates the game and send response back to client for any new changes like where is the enemy and other. And if i choose option 1 is there a chance the host to change the game content and manipulate the game results? (I think there is but i'm not sure) And if i choose option 2 isn't that raising the response time and potentially the game lag? or maybe there is another option?"} {"_id": 46, "text": "Existing master server software? Considering there are many games out there that use some sort of a server that contains a list of current games servers, is there an existing library I can use instead of writing my own master server? I only wish to store game server data (server name ip, num players, game specific data...). Thanks!"} {"_id": 46, "text": "Do I need a backend engineer for my studio right now? I am working on a mobile game that requires a well thought out backend, because it spans across the healthcare data science space and we need to be compliant in terms of security regulations in how we approach this. Think something like Fitbit. My team is nearly finished with the client side game aspect but I am wondering whether I need to take on a short term contract part time backend engineer to create our entire backend infrastructure OR someone who would work on this full time with our team. Here is what we would need to do Setup our entire backend infrastructure and plug this into Unity This would require knowing how to handle (transmit receive) data securely, and also perform computation with that data in the cloud Set up an API where other developers can query our data Set up our dev ops infrastructure (Docker, Jenkins) for the future The kicker here is that we are not yet live and are just in a testing phase. I don't want this to be 2 3 weeks of work, with no users for 3 more months while we're working on other aspects of the project, with the dude having nothing to do. Does this sound like a lot of work? Or could it easily take up a devs time for a month or two? Would a short contract be advisable here, or would it be better to hire someone FT and have them grow with us."} {"_id": 46, "text": "Distributed C game server which use database My C turn based game server (which uses database) does not stand against current average amount of clients (players), so I want to expand it to multiple (more then one) amount of computers and databases where all clients still will remain within single game world (servers will must communicate with each other and use multiple databases). Is there some tutorials books common standards which explain how to do it in a best way?"} {"_id": 46, "text": "Calculate resources real time. Sockets or not? I'm currenly developing a game in Javascript. It's a Single Page Application so every change should be pulled from the server without page refresh. I'm currently wondering how I should handle the 'resources in stock' (like wood, food and gold). I know there are more questions like this around here (regarding websockets and Ajax requests) but I'm currently looking for the best solution in my specific case. Scenario Resources are produced every second. So for example, every minute 100 resources are produced. This should be updated live. I know, in this case it's not necessary to really update them live. I mean, I can simply calculate how much resources are produced in the current time minus the last updated time. So no problem here, but there are a lot of different factors regarding the production of resources If a player is attacked, the enemy could have robbed some of his resources. So after an attack, the resources should be updated too. If a player is attacked, and one of his 'productionbuildings' are damaged, he, for example, doesn't produce 1000 resources a hour, but 800 resources instead. So after a building has been demolished, the application should know the new building level to calculate the right amount of new resources. Possibilities So, how should I update the resources for the user? These are the options I think could possibly work Ping a script on the server, which calculates and updates the resources, every 5 seconds. Set up a websocket stream and trigger it after each activity (after an attack, demolished building, ...) Are there any other options? What would be the best way?"} {"_id": 46, "text": "what is the best way to code an online multiplayer game? so i want to create a simple game that runs over a network but I am having trouble deciding what needs to be done in terms of what the server needs to do and what the clients need to do. I understand I should use UDP sockets but I am unsure how to implement it within a game and have all the clients be in sync. Should the server side have like a master copy of the game where i basically runs the game and accepts moves, plays them in itself, and then sends the current state of the object to the other clients?"} {"_id": 46, "text": "How do I resolve asynchronous client actions against an authoritative server state? I have a multiplayer card game which I am in the process of developing. The game is relatively simple players have a certain number of cards which they can activate, sell, or use in various other ways. The game isn't turn based. Instead, it is asynchronous so that players (A, B, C, and D) all make their choices at the same time. Certain actions will affect the game state. For example, removing a card from the game or adding a card to the game. Players should always be in sync with each other so that, for instance, Player A cannot use a card that Player B has just removed, as it is no longer present. Obviously there are situations in which Player A may remove a card at nearly the same time that Player B tries to interact with the same card. How would the server handle this sort of situation? My original thought is that each client could hash their game state and send it with their command to the server, for example Player A MYHASH Command Pick Up Card Z Player B MYHASH Command Remove Card Z The server would then action the first command and regenerate the hash. Upon trying to execute the second command it would notice the hash sent by Player B differs from the current hash, so the server would reject the request. In the above example Player A would notice nothing and the game would continue normally, but Player B would have to be informed that their action failed."} {"_id": 46, "text": "Choosing a server for a PVP game So I am starting a game with a friend as a small project, and we are considering what game servers would we need. Firstly, the game is a multiplayer(player vs player) game, for example, like an online chess game. However it is real time, so the latency cannot be too high. The players basically take turns, but in a real time fashion. The platform is going to be Android (and perhaps extend to iOS in the future) The server would need to synchronize the players' moves to each other devices. I don't really need anything large scale and I am thinking of using PHP since the volume of data isn't really that big, this is like a web based game with a requirement of a slightly lower latency. What would be the advantages and disadvantage of using Apache PHP for a game like this? If that seems to be a bad choice, I would be grateful if you can share your experience with me. Thank you. (We are both programmers and we are familiar with Java C Obj C Apache PHP Tomcat JSP Javascript)"} {"_id": 46, "text": "Is it possible to rent a server for my own game? I'm an independent game developer and I don't yet have a lot of money to buy myself a very cool high speed and low latency internet connection along with a powerful server machine to place somewhere in the world to host my very own game's server application for my fans to play on. I know it's possible to rent a server for an existing popular game (for example, Team Fortress 2), but how about renting a server for my own game that I'm developing? Are there services specifically for that, or should I just rent some general purpose something and go from there? Such a server should be Easy to update With a low latency for a specific region (I'm planning on renting EU and US servers)"} {"_id": 47, "text": "What's the proper practice to organize relationship between components in an ECS pattern? I'm new to ECS concept and trying to refactor my app with an ECS manner. After reading some articles, I still don't get a sense about how to organize hierarchy for such pattern. My questions are Is a component allowed to have another component inside? For example I saw a RenderComponent that contains a Mesh inside. Is the mesh also a component or the raw data of it, which should be stored inside the RenderComponent? What happens when an instance of component needs to be shared by two entities? If an entity should be just an integer, how do you organize the relationship between entities? Should it have a parent child linked entity or should all these relationship be managed by the system? Thanks!"} {"_id": 47, "text": "ECS System calling other systems I'm trying to build my first (2D) game with ECS but I always end up with some system calling other systems. Here's an example. There is a RegionSystem that manages RegionComponents. On each frame, this system loops through all the RegionComponents and checks if the player is inside any of them. When the player enters the water, the player's sprite must be changed from PLAYER RUNNING to PLAYER SIWMMING. When the player steps onto a teleporter, an animation will play around the player, he'll be rotating and a new level will be loaded. When the player steps into a hole, he will lose some health and will be repositioned in the level. So, first of all, it needs the coordinates of the player's body to check if it is in a region (check point in rectangle). Hence it will ask the RigidbodySystem to get the coordinates. Then if the player is inside a region, it will call PlayerSystem OnInsideRegion(regionInfo). In turn this function, PlayerSystem OnInsideRegion must react differently depending on the type of the region for the water case, it needs to call the SpriteSystem to change a sprite, the PlayerSystem to set a boolean (m inWater True ) and the RigidBodySystem to get the coordinates of the player's body for the teleporter case, it needs to call the LevelSystem and tell him to switch to another level on the next frame for the hole case, well, simply descrease the member m health of the player component, so no need to call another system here. I have the feeling this is a horrible design and does not fit the ECS architecture. I read that people use a message system where systems can subscribe and unsubscribe to particular type of message. But I also read that it can be tricky to react to them in a proper order."} {"_id": 47, "text": "Entity component system where did attributes and behaviors come from? I recently spent quite some time understanding and building a component based system. I got stuck on a few problems and after searching for quite some time ran across this answer which is talking about behaviours and attributes. From what I understand, attributes are an entity's data I thought that's what the component is? And what are behaviours? Is it another term for Entity Processing System?"} {"_id": 47, "text": "Handling of persistent key presses in an ECS I'm currently in the planning phase of a game. The whole thing should be based on the entity component system (ECS) pattern. All logic is concentrated inside of the systems, i.e. that the components hold data only. Communication across the systems is performed using asynchronous events. Using this design, I'm unable to find a clean solution for the simple example task of moving player While the input system generates key press events, I'm looking for a way to query the key state, since the player will most likely want to move the player for more than one frame. There are two possible ways I can think of solving this problem Retrigger the key press event every frame Pass the corresponding systems a reference to the input system Neither possibility sounds \"correct\", since they both require the abuse of the design. Is there a better approach for solving this issue?"} {"_id": 47, "text": "Packet Event Based Entity Component System I know what one of the big commonalities I see in ECS projects is that there is a main game loop that iterates through systems and calls their respective update methods (for example, RenderSystem). I'm a bit stumped on how this applies to an event based game where the client sends packets of information and you update from there. For example MovementPacket Read incoming movement packet and send to appropriate packet handler, which makes changes to appropriate components regarding entity through systems. Packets are then sent back through the systems (which work with components to access the data needed to write these packets). nbsp Now, I'm not sure where a game loop really comes in here, since everything seems to be event based. I'm scared that most of the work I'm doing ultimately for ECS just isn't being done right. My systems are typically becoming \"containers that do logic and stuff, but don't operate within a game loop.\" In fact, the game itself doesn't have a game loop, since we haven't really found an area to insert it in. Is the approach just wrong? Is my approach towards interweaving ECS with this packet based game for the most part incorrect?"} {"_id": 47, "text": "ECS, databases, XML and serialization My entity component system engine is coming along quite nicely I have two very different apps working on the same executable. (One 2 d scroller, one 3D Asteroids type game). In the interest of getting something working, I've been creating XML definitions of the games, and editing them using a small custom tool that does little more than ensure that I don't add components that don't exist, and that the files are valid XML. I'm at something of an apex or flection point in that the tools and process I'm using really aren't suitable for production. Hand editing large XML files is an error prone, painful process. (JSON is well supported and pithy, but still requires visual syntax checking.) I could switch to a database such as SQLite, but I have yet to find a good graphical interface (something along the lines of SQL Server Management Studio would be nice). Are there any COTS tools that can ease this process? I found a C SQLite implementation with a basic ORM, but it doesn't support complex types like Vector3 or Rectangle. I can serialize these into strings or edit the ORM code to support those types, but then I wind up with my own branch of an OSS component which invites maintenance headaches further down the road. Another thought was to just do everything in SQL Server and generate the XML from there, and have a tool that keeps the DB schema in sync with the component types in my engine, which is similar to using an ORM. What's a good solution for this problem? I've read that bigger studios (as in, more than one guy) build their own tools for this kind of thing. I can do that, but I'd really rather be writing my game than building a tool set that only I will ever see. To clarify how do those that use entity component system engines create and maintain their data that defines the game?"} {"_id": 47, "text": "Entity Component System Physics Animation Matrix Calculation? The problem is how many times the matrices representing the bones (for animation and rendering) of an entity get calculated. If i have these components Position Skeleton (holds matrices for bones) Physics Animation When the physics get's updated, the position is changed to move the entity. This sends a message, that position has changed. The skeleton takes note and updates the matrices for the changed position (and potentially rotation). The animations are then updated in a separate system, the skeleton then gets updated and changed again. So essentially the matrices are being updated twice (unnecessarily) instead of just once. Am i going about this the wrong way? Is this just the price of having everything disjoint?"} {"_id": 47, "text": "Central logic in entity component architectures I've build a architecture based on the entity component system idea. So I got Components Just store Data Systems Operates isolated on Components Scripts Which are just objects from type Script and attached to a ScriptComponent. A ScriptSystem will execute the init() and update() functions on the scripts then. However, I'm wondering where to place the central game logic since the I have to check a few things about the overall game process, holding the map, counting the points, checks the points if they are enough for the end screen, etc. ... Should I create a single entitiy with just such a script attached to it or are there better solutions out there?"} {"_id": 47, "text": "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 class Entity list of components add component remove component update comentent .... So you are building your entities at runtime. I assume it will look like this Entity ork ork.add(AI).add(movement).add(physics).add(renderer) The 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. What is the advantage of building your objects that way instead of doing it like this? class Ork IEntity movementComp AiComp physicsComp rendererComp .... wire everything together One 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. Would you please enlighten me?"} {"_id": 47, "text": "Should I load scenes from files, or hard code them? In a game engine I'm working on, I'm using scenes similar to what you would find in Unity. The entities, in my game, are composed of reusable components and custom data which is linked to those components. Entities have children, and one parent. This is shown, below class Entity ...custom data here... let parent Component var children Component var components Component ...methods... If the entities did not have custom data, then creating a scene would be described by the following steps Loading a file into memory. Creating a tree of entities. Adding components to them, with parameters listed in the file. However, this does not leave room for custom data. My other alternative is to create a scene by creating a scene object, then hard coding the entities in. It would look something a bit like this var opening scene Scene() opening scene.addEntity(Player()) opening scene.addEntity(Car()) opening scene.addEntity(Terrain()) ... The downside to this is that everything is hard coded. What can I do to create scenes in a game more efficiently?"} {"_id": 47, "text": "How to use batch rendering with an entity component system? I have an entity component system and a 2D rendering engine. Because I have a lot of repeating sprites (the entities are non animated, the background is tile based) I would really like to use batch rendering to reduce calls to the drawing routine. What would be the best way to integrate this with an engtity system? I thought about creating and populating the sprite batche every frame update, but that will probably be very slow. A better way would be to add a reference to an entity's quad to the sprite batch at initialization, but that would mean that the entity factory has to be aware of the Rendering System or that the sprite batch has to be a component of some Cache entity. One case violates encapsulation pretty heavily, while the other forces a non game object entity in the entity system, which I am not sure I like a lot. As for engine, I am using Love2D (Love2D website) and FEZ ( FEZ website) as entity system(so everything is in Lua). I am more interested in a generic pattern of how to properly implement that rather than a language library specific solution. Thanks in advance!"} {"_id": 47, "text": "Why is it a bad idea to store methods in Entities and Components? (Along with some other Entity System questions.) This is a followup to this question, which I answered, but this one tackles with a much more specific subject. This answer helped me understand Entity Systems even better than the article. I've read the (yes, the) article about Entity Systems, and it told me the following Entities are just an id and an array of components (the articles says that storing entities in components isn't a good way of doing things, but doesn't provide an alternative). Components are pieces of data, that indicate what can be done with a certain entity. Systems are the \"methods\", they perform manipulation of data on entities. This seems really practical in many situations, but the part about components being just data classes is bothering me. For example, how could I implement my Vector2D class (Position) in an Entity System? The Vector2D class holds data x and y coordinates, but it also has methods, which are crucial to its usefulness and distinguish the class from just a two element array. Example methods are add(), rotate(point, r, angle), substract(), normalize(), and all other standard, useful, and absolutely needed methods that positions (which are instances of the Vector2D class) should have. If the component was just a data holder, it wouldn't be able to have these methods! One solution that could probably pop up would be to implement them inside systems, but that seems very counter intuitive. These methods are things that I want to perform now, have them be complete and ready to use. I don't want to wait for the MovementSystem to read some expensive set of messages that instruct it to perform a calculation on the position of an entity! And, the article very clearly states that only systems should have any functionality, and the only explanation for that, which I could find, was \"to avoid OOP\". First of all, I don't understand why should I refrain from using methods in entities and components. The memory overhead is practically the same, and when coupled with systems these should be very easy to implement and combine in interesting ways. The systems, for example, could only provide basic logic to entities components, which know the implementation themselves. If you ask me this is basically taking the goodies from both ES and OOP, something that can't be done according to the author of the article, but to me seems like a good practice. Think about it this way there are many different types of drawable objects in a game. Plain old images, animations (update(), getCurrentFrame(), etc), combinations of these primitive types, and all of them could simply provide a draw() method to the render system, which then doesn't need to care about how the sprite of an entity is implemented, only about the interface (draw) and the position. And then, I would only need an animation system which would call animation specific methods that have nothing to do with the rendering. And just one other thing... Is there really an alternative to arrays when it comes to storing components? I see no other place for components to be stored other than arrays inside an Entity class... Maybe, this is a better approach store components as simple properties of entities. For example, a position component would be glued to entity.position. The only other way would be to have some kind of a strange lookup table inside systems, that references different entities. But that seems very inefficient and more complicated to develop than simply storing components in the entity."} {"_id": 47, "text": "Superclassing RPG Game Entities I am in the design process of an RPG game and I have no experience at all in game dev. This question is about how I should approach entity management using OOP classes. My train of thought is as followed Have Entity interface with basic update() function \"Mortal\" class and \"NPC\" class implement Entity \"Hero\" and \"Monster\" class inherit from \"Mortal\" class In this case, Mortal class are all those entities that have statuses such as HP and MP. NPC are self explanatory. I am sure my approach is naive so I would like to know the pros and cons and what would be a better way to approach this."} {"_id": 47, "text": "Entity Component Systems with Model View Controller Can the Model View Controller design pattern be used with non OOP coding style, specifically with Entity Component System?"} {"_id": 47, "text": "Ways to persist entities and components in an ECS? I am working on a small multiplayer game with rpg elements using java and quot Artemis ODB quot . Most of the logic is already done but one important thing is missing. The persistence. So i am searching for different ways to persist my game. One thing is important, the world is huge and i cant load in the whole world at once. I already stumbled upon two different ways on my own. Using a relational database or a nosql database. But one thing scares me... entity references. In my game i have an player entity and item entities. The player entity owns a inventory component which stores a reference to some item entities. In my ecs, each entity reference is an simple integer. So this looks like this... Represents the Inventory of our game, contains references to entities acting as items. public class Inventory extends HibernateComponent public Set lt Integer gt itemEntities new LinkedHashSet lt gt () Why does this scare me ? Well... Entity references are Integers in my case. They are no real ID and i cant set or change this quot ID quot of an entity because my framework permits it. This brings us straight to the problem. When i serialize this component or the whole player entity it would look like this. Inventory itemEntities 40,2,5,50 So when we save this and load it later on we have no entity with the id 40... and even if we recreate that entity we cant set it to an id of 40, because the frameworks permits it. So how the heck do we save references between entities ? So all in all... what are common ways to save, load entities from an ecs ? How do you do it ? And what would you recommend ?"} {"_id": 47, "text": "in an ECS framework why are components indexed via their name rather than an Enum? I have been reading through a number of discussions on ECS framework and very often I see components being referred to via name rather than through a string object such as an enum or a struct. I'm starting to build a test implementation myself and feel as though they should have a strong type rather than a string so that I can pick the component I am looking for from a list rather than 'guessing' with a string. As an example you will often see Entity.GetComponent(\"Position\") rather than Entity.GetComponent(ComponentTypes.Position)"} {"_id": 47, "text": "Defining collision response in an Entity system I'm building a really simple top down 2d shooter which uses an Entity Component pattern. I've added several different entities to a level and given them different collision groups. I have an entity to represent a teleporter (assigned to collision group A), a player entity (group B), and a bunch of enemies (Group C). I understand that the actual collision response should be decided in the collision System based on the groups that the colliding entities belong to. What I can't figure out is how to define the specifics of a collision. For example, if a player collides with a teleporter I need to move the player across the level. Where do I store the target location? I'd assume in a component on the teleporter. Should I create a whole new component just for that data? I feel it should be stored in the teleporters collision component but no all entities that use the collision component will require this data. Could someone please try to enlighten me? Thanks"} {"_id": 47, "text": "Should components in Entity Component System pattern have logic? Is often read that in entity component system pattern we should treat components just as a passive data structure with no logic at all, this way we follow to a data oriented design approach with efficient usage of cache memory and gain performance. I was developing a simple game using this rule and when the game was getting bigger I start facing some serious code smells such as repeated code in systems, let's suppose its a shooter to illustrate an example. In this shooter I had bullets being fired so I created a BulletComponent and a BulletSystem that handles when it collides and make some damage and if don't collide with anything the bullet dissapear in five seconds. Then I wanted some explosives so I created the ExplosiveComponent and ExplosionSystem, once the explosive is placed it explodes in ten seconds. At this point we can notice the first repeated code between systems then we can make an abstraction and we create a DurationComponent and a DurationSystem so the bullet and the explosive contains it with the time it should last.Then I realized that when the explosive should explode I want to create some particle effect in the area so this abstraction is no longer valid as I want to perform differents actions when time runs out, but if I do as at the beginning I have the repeated code between systems (ugh!). This example is simple but I'm facing this with more complex things like AI, or reacting to collisions. One solution I came to this is that I really wanted an ActionComponent with a ActionSystem that executes the action contained in the component but this way I'm breaking that components only contains data and they should not have logic! this is more an 'hybrid' approach. But if you start thinking deeply the ActionSystem is very generic and you can almost do anything with it so it's hard to determine whether a system is necessary or not. The same can be applied to collisions, instead of having lots of systems with logic for different entities colliding, you can just have a CollisionHandlerComponent with the logic on it for each entity. I found the following advantages making generic systems like this Higher flexibility (you can customize each entity easily) No repeated code Less systems (more performance?) But as I said the main disadvantage is that is really confusing if a system is needed as you can stick logic to components. Is it wrong to follow this sort of hybrid ecs? If yes, what would be your approach to the example without repeating code in systems?"} {"_id": 47, "text": "How should one component \"trigger\" another one in a component system? In my game I have a MoveComponent and a ClimbComponent. Some characters can only move around on one level, others are able to climb to the next floor. My intention is to have characters randomly be able to climb if the are about to bounce into a wall. How would I manage this? Should the ClimbComponent be added dynamically and also be removed again, or should random characters always have the ClimbComponent and it would be activated and deactivated dynamically?"} {"_id": 47, "text": "Where should complex state logic in an ECS reside? I've been using ECS for a while, at the moment I'm using my own, but it's pretty standard. Components are data only, Entities pretty much just a Map with some additional metadata and Systems that match combinations of components and contain the logic. You have combinations of components that result in the more general functionality. For example Position Graphics gives me some nice static background image. Position Graphics Physics gives me a entity that can move around etc etc This question is about the various options for implementing more specific game logic. But say I want to implement a Door. It has Position, Graphics and a Collidable Hull but it needs 2 states, open and closed. When its open it has texture A and its Collidable Hull is disabled, and when its closed it has texture B and its Collidable Hull is enabled. Lets say the state change should be triggered across some internal channel in the engine. What are the options for implementing this state change? Option 1 is to create Door component, with say 2 variables, door state and state change channel. I'd also need a door system that handled the logic to manipulate the components when it receive the open close message. Option 2 would be to create a FSM. The FSM is probably also a component with a corresponding FSM System. Logic and state would need to reside somewhere, possibly by sub classing the FSM or having a generic property map in the FSM and static logic functions for the Door defined elsewhere. There are more exotic alternatives to FSM's i.e. Actions Lists or Behaviour trees, but they are similar to option 2. What considerations are there for choosing a full component system over an more generic FSM type solution? What if I had 100 different game objects with different behaviours? Would you really expect 100 component system pairs for each one or would you try and create a more generalized solution? Are there any other options?"} {"_id": 47, "text": "How can I utilize external libraries within an entity system? I'm implementing an entity system for educational purposes. I wanted to focus on the system itself and don't know much about rendering and physics, so I'm using external libraries for those tasks. These libraries come with pre defined classes for their objects (sprites, bodies, etc.) These do not fit into my entity system easily. How can I utilize existing libraries and classes within an entity system?"} {"_id": 47, "text": "How do components and systems relate to each other in an entity component system? I'm trying to learn and understand the ECS (Entity Component System) so that I can create a game using this design pattern but I've got a lot of things that I still don't understand. Lets say I've got a PositionComponent and a MovementSystem or PhysicsSystem. The PhysicsSystem will heavily rely on the PositionComponent since in order to calculate, for example a rigid body motion, it needs the x and y positions (in a 2D game) wich is contained by the PositionComponent. What is the relationship between Components and Systems? How does the MovementSystem get the x and y values from the PositionComponent?"} {"_id": 47, "text": "Handling movement using an Entity Component based System Architecture I have seen various descriptions of how to handle movement in a component based entity framework. The most common I've stumbled across is the idea of using components called Controller, Physics, Transform, Velocity, and Collider. The idea here is that the Controller influences the Velocity component when movement keystrokes are detected. The Velocity component in turn influences Physics. Once the simulation has been stepped, the Collider is either affected if a collision occured or is not if no collision happened. In the end, the Transform is updated with the new position from the physics simulation step and thusly the Renderable needs to be adjusted so it is drawn in the proper location. I have often read that one needs to consider both physics driven and non physics driven entities. As outlined in the above paragraph, manipulating physics driven entities seems like a piece of cake. The difference with non physics driven entities is that the Velocity component values need to simply be applied to the the Transform based on delta time. This would allow moving the entity without being concerned with physics nor collision detection. For physics driven entities, one simply iterates entities with both Velocity and Physics components. But for non physics driven entities, simply iterating over entities with a Velocity component isn't sufficient as it would include the above subset as well. So there must be some factor that clearly separates these two cases. So with these two cases in mind, how would movement actions that influence the values of Velocity be carried out in such a system to manipulate both types of entities whether physics plays a roll in their movement or not?? And lastly, considering that there may be times where the transform for an entity needs to be manipulated directly, such as player clicking on a portal to be teleported to another x y z position, how would one properly propagate this change to adjust both the physics step simultation and the renderable's draw location? EDIT bobenko Your explanations provide insight to the most common case where objects are simulated via physics but I'm somewhat lost on the Kinematic aspect regarding updating an entities position via a velocity value? Are you simply implying that some code of my own will apply movement to the entity via velocity, thus being Kinematic? I still am interested in your explanation on how to avoid cyclic notifications effectively when aspects of these components involved change. For all who answered, I'm still not clear how would you handle teleporting an entity from one position to another? Would this involve turning off physics, teleporting the player, then turning physics on after teleport finished? Turning physics on off can be as simply as setting the entity as Kinematic YES NO, right?"} {"_id": 47, "text": "Should I implement Entity Component System in all my projects? I'm not here to ask for any specific code implementation, I'm here just to make my ideas clearer. But let me explain the situation I have already developed some little and amatorial game projects (never published tho) but I recently found some interesting articles about ECS and I began to read more about it. I found the whole ECS concept every interesting and I thought I could implement it in a very tiny game I'm working on in my free time. The problem is should I implement this pattern on a every little project with simple game mechanics and poor gameplay ? The 2D game I'm working on will be entirely developed by me, so I do not actually need to make the code easier to mantain by other people. This game will basically have just 2 players, some weapons and a large variety of bullets and superpowers. No IA enemies, no vehicles, static and tiny maps and.. Just that. It will have, of course, a simply physics system (just to make players fall and bullets move, for example), and a tiled but very little map which is editabile by players (destroying tiles). So the point is why should I actually write an ECS for such a basic game ? Do I really have any real advantage considering the game design ? I mean, I know it is very good to make your code very flexible and easy to mantain even in the future, but I also know that this pattern was invented to avoid some limitations and the code duplication which the old hierarchical game structure provides, but this game doesn't have a wide hierarchical structure, as far as I can see. I started coding it, but I discovered some aspects which, to be honest, scare me. Like having all the components talking to each other through a reference of their owner (the entity they are bound to), which as far as I know, is not very good to avoid cache misses. The last thing is that I have the feeling that I won't write more than 2 components of the same type, and this would make the ECS less useful. I know I don't have the whole ECS concept really clear in my mind, this is the first time I implement it, by the way, but I hope you got the point of my problem."} {"_id": 47, "text": "Particles instancing groups in an Entity Component system I've been playing with an entity component system design recently, and I've come across a couple of stumbling blocks. Instancing Let's say I have a few hundred \"things\" (asteroids, chickens, whatever) that are being drawn with instancing. In a classic component hierarchy, I'd have a game object that keeps the individual instance index and vertex buffers, as well as the second dynamic vertex buffer for the instance data (collection of matrices, etc.). That object would be responsible for checking collisions with other objects and between the instances themselves. In an ES system, I'd like to track each instance as an individual entity, but I don't want to give up simplicity and performance of instancing. The first thing that occurred to me was to create an \"instance group\" component, with a field that defines a group ID to enable handling of multiple types of instanced geometry. An \"Instance System\" would collect those components and maintain the instance vertex buffer. My entity manager already notifies systems when an entity is created or destroyed which makes this part pretty easy to implement. My confusion comes from how to cleanly integrate that with the rendering system. If each instance appears as a separate entity with a \"renderable\" component attribute, the render system will process them individually. I could Include a special case for entities that have both a \"renderable\" and an \"instanced\" component, but that seems messy and feels like starting down the path of having a huge render system with tons of special cases. Have the render system maintain a collection of instance vertex buffers, query the entity list for \"instanced\" entities, filter based on a group ID, etc., and render as appropriate, so the render system becomes responsible for maintaining instance collections, but that seems like the wrong place to put that sort of logic. I could also include a single entity in addition to the instances with, say, an \"InstanceOutput\" component attribute and a Renderable component, and remove the Renderable component from the individual instance entities, giving a single render point for all of the instances. This component would probably also server as a place to keep the geometry and persistent instance vertex buffer. Is there a better way? Rendering I have several types of renderable entities. Some have procedural geometry and textures, some are just sprites, some are text displays. What's the best way to differentiate these from the point of view of the rendering system without having to write a massive switch statement? In a game object hierarchy, each of these types would have their own Draw() method, but moving the logic into a Render System doesn't seem to provide a lot of flexibility in terms of different effect parameters, etc."} {"_id": 47, "text": "Component Entity Systems Code Generation I'm really enjoying component entity approach (I'm currently using ASH haxe, but particular language framework doesn't really matter). However the problem is there're way too many elementary classes that need frequent update. So I'd like to have something like yml config file for components and nodes, and actual classes to be generated from it. Is there any already existing solution that utilizes such codegen, or maybe some generic codegen solution that should be easy to configure for such task?"} {"_id": 47, "text": "Defining collision response in an Entity system I'm building a really simple top down 2d shooter which uses an Entity Component pattern. I've added several different entities to a level and given them different collision groups. I have an entity to represent a teleporter (assigned to collision group A), a player entity (group B), and a bunch of enemies (Group C). I understand that the actual collision response should be decided in the collision System based on the groups that the colliding entities belong to. What I can't figure out is how to define the specifics of a collision. For example, if a player collides with a teleporter I need to move the player across the level. Where do I store the target location? I'd assume in a component on the teleporter. Should I create a whole new component just for that data? I feel it should be stored in the teleporters collision component but no all entities that use the collision component will require this data. Could someone please try to enlighten me? Thanks"} {"_id": 47, "text": "Superclassing RPG Game Entities I am in the design process of an RPG game and I have no experience at all in game dev. This question is about how I should approach entity management using OOP classes. My train of thought is as followed Have Entity interface with basic update() function \"Mortal\" class and \"NPC\" class implement Entity \"Hero\" and \"Monster\" class inherit from \"Mortal\" class In this case, Mortal class are all those entities that have statuses such as HP and MP. NPC are self explanatory. I am sure my approach is naive so I would like to know the pros and cons and what would be a better way to approach this."} {"_id": 47, "text": "Where should complex state logic in an ECS reside? I've been using ECS for a while, at the moment I'm using my own, but it's pretty standard. Components are data only, Entities pretty much just a Map with some additional metadata and Systems that match combinations of components and contain the logic. You have combinations of components that result in the more general functionality. For example Position Graphics gives me some nice static background image. Position Graphics Physics gives me a entity that can move around etc etc This question is about the various options for implementing more specific game logic. But say I want to implement a Door. It has Position, Graphics and a Collidable Hull but it needs 2 states, open and closed. When its open it has texture A and its Collidable Hull is disabled, and when its closed it has texture B and its Collidable Hull is enabled. Lets say the state change should be triggered across some internal channel in the engine. What are the options for implementing this state change? Option 1 is to create Door component, with say 2 variables, door state and state change channel. I'd also need a door system that handled the logic to manipulate the components when it receive the open close message. Option 2 would be to create a FSM. The FSM is probably also a component with a corresponding FSM System. Logic and state would need to reside somewhere, possibly by sub classing the FSM or having a generic property map in the FSM and static logic functions for the Door defined elsewhere. There are more exotic alternatives to FSM's i.e. Actions Lists or Behaviour trees, but they are similar to option 2. What considerations are there for choosing a full component system over an more generic FSM type solution? What if I had 100 different game objects with different behaviours? Would you really expect 100 component system pairs for each one or would you try and create a more generalized solution? Are there any other options?"} {"_id": 47, "text": "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. I 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. I 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. Can I get any suggestions on a solid approach? Am I on the correct track with my first idea? Thanks for any help Aedon"} {"_id": 47, "text": "Handling of persistent key presses in an ECS I'm currently in the planning phase of a game. The whole thing should be based on the entity component system (ECS) pattern. All logic is concentrated inside of the systems, i.e. that the components hold data only. Communication across the systems is performed using asynchronous events. Using this design, I'm unable to find a clean solution for the simple example task of moving player While the input system generates key press events, I'm looking for a way to query the key state, since the player will most likely want to move the player for more than one frame. There are two possible ways I can think of solving this problem Retrigger the key press event every frame Pass the corresponding systems a reference to the input system Neither possibility sounds \"correct\", since they both require the abuse of the design. Is there a better approach for solving this issue?"} {"_id": 47, "text": "Intersystem communication in a ECS game Apologies if this question has been answered before, but after relentless searching I couldn't find anything. As many, I've recently jumped on the ECS bandwagon, and I am currently killing some time by making a modest ECS game. The game is a somewhat simple 2D platform game. It is programmed in plain JS. The layout of the game is essentially as following The core of the game is the Engine, the Engine runs the game loop and holds an EventManager, responsible for raising events, and an EntityManager, responsible for containing all components of all entities. All logic is done by systems. The systems registers event handlers (i.e. member functions) with the EventHandler for specific EventTypes, which gets called when an event of that type is raised. For example this.eventManager.registerHandler(EventType.EVENT RENDER, this.render, null, this) I recently switched from calling all systems relevant functions explicitly in the Engine to this pattern. But over to my problem and question. For rendering I have a RenderSystem. This system contains references to several type of drawable animatable components which it, you guessed it, renders. Until recently, this system also contained a reference to another system, MapSystem, which spatially indexes all entities. The reason for this reference was to be able to call a function along the lines of mapSystem.search(frame bound) effectively pruning away all entities not needing to be rendered. So I have a couple of questions regarding this Is it very bad practice for systems to communicate directly? Something about it just doesn't smell right to me. I see how it might severely complicate your code if you have say 100 systems, and each system holds references to many of the other systems. Hello O(n 2). If I am not to hold inter system references, how do I perform communication like described above? My initial thoughts was to create an entity whose primary purpose were to hold the necessary information (i.e. all entities currently in the frame). Then let MapSystem write to and RenderSystem read from this entity. But this also seems to be rather unclean to me. Especially as MapSystems search function might be useful to call in many different contexts. Creating an entity per calling context doesn't really seem like a good way to go about it either. TL DR Is it bad for systems in a ECS game to communicate directly and hold references to each other?"} {"_id": 47, "text": "Viewing one of multiple worlds in a component entity system? I've been working on a space simulation game. The player can control a ship and fly through wormholes to get from one solar system to another. I would like the player to be able to switch the camera view between the different solar systems they own something in (world, factories, defenses, etc). If am using just one component entity world then how do I tell the rendering system that looks for sprite components to only draw the sprite components of one solar system? I could add a \"solar system id\" field to each sprite component and have the rendering system check each component before rendering to make sure it's in the \"active\" solar system. It doesn't seem like a good idea though. Mostly because I'd be adding another if case before processing every single sprite, at the very least (other components may need similar checks). I could have the rendering system maintain an internal map of which solar system contains which entities, but then I have to write entity systems that keep track of all the entities, which is my entity system framework's job (Artemis for Java). Currently I am planning on making all of the solar systems separate from each other. They wouldn't exist in the same coordinate system. I suppose I could instead put everything on the same coordinate system and just move the camera around based on which solar system the player wanted to view at that time. The problem with that would be that my sprite rendering system would still be looping through all the sprites in the game, instead of just the ones at the active solar system. So, for lack of better options, I'm leaning toward using multiple component entity worlds. So each solar system would get its own set of systems (including the rendering system), and I'd set which one was active to enable the rendering systems for that solar system. I didn't want to take this approach for two reasons. First, it adds another layer of complexity on top of everything. Second, it seems like it might lessen some of the performance benefits (caching) of looping through all the same types of components and running the same entity system algorithm. Instead of doing a breadth first loop through all the components it would be more of a depth first loop through all the systems' components. So what is the best way to handle this?"} {"_id": 47, "text": "Should fields in components in an ECS use polymorphism? I've just started to try and learn how to use ECS (Entity component systems), but I'm having trouble understanding the concepts behind components. Should adding more types of components, or trying to make a component reusable through its fields be favored? For example, if I'm trying to give all entities a shape for collision detection, should I have a different component for every shape (RectangleComponent, CircleComponent, PolygonComponent), or should I have one ShapeComponent, and in there have a field which is of type Shape, with class Shape having subclasses Rectangle, Circle, and Polygon. I'm unsure because using a Shape seems to be much more flexible and easier to implement systems, but it also feels like I'm violating the ECS rule of not having any functionality in components."} {"_id": 47, "text": "Ways to persist entities and components in an ECS? I am working on a small multiplayer game with rpg elements using java and quot Artemis ODB quot . Most of the logic is already done but one important thing is missing. The persistence. So i am searching for different ways to persist my game. One thing is important, the world is huge and i cant load in the whole world at once. I already stumbled upon two different ways on my own. Using a relational database or a nosql database. But one thing scares me... entity references. In my game i have an player entity and item entities. The player entity owns a inventory component which stores a reference to some item entities. In my ecs, each entity reference is an simple integer. So this looks like this... Represents the Inventory of our game, contains references to entities acting as items. public class Inventory extends HibernateComponent public Set lt Integer gt itemEntities new LinkedHashSet lt gt () Why does this scare me ? Well... Entity references are Integers in my case. They are no real ID and i cant set or change this quot ID quot of an entity because my framework permits it. This brings us straight to the problem. When i serialize this component or the whole player entity it would look like this. Inventory itemEntities 40,2,5,50 So when we save this and load it later on we have no entity with the id 40... and even if we recreate that entity we cant set it to an id of 40, because the frameworks permits it. So how the heck do we save references between entities ? So all in all... what are common ways to save, load entities from an ecs ? How do you do it ? And what would you recommend ?"} {"_id": 47, "text": "Defining collision response in an Entity system I'm building a really simple top down 2d shooter which uses an Entity Component pattern. I've added several different entities to a level and given them different collision groups. I have an entity to represent a teleporter (assigned to collision group A), a player entity (group B), and a bunch of enemies (Group C). I understand that the actual collision response should be decided in the collision System based on the groups that the colliding entities belong to. What I can't figure out is how to define the specifics of a collision. For example, if a player collides with a teleporter I need to move the player across the level. Where do I store the target location? I'd assume in a component on the teleporter. Should I create a whole new component just for that data? I feel it should be stored in the teleporters collision component but no all entities that use the collision component will require this data. Could someone please try to enlighten me? Thanks"} {"_id": 47, "text": "How does an Engine like Source process entities? On the Source engine (and it's antecessor, goldsrc, quake's) the game objects are divided in two types, world and entities. The world is the map geometry and the entities are players, particles, sounds, scores, etc (for the Source Engine). Every entity has a think function, which do all the logic for that entity. So, if everything that needs to be processed comes from a base class with the think function, the game engine could store everything on a list and, on every frame, loop through it and call that function. On a first look, this idea is reasonable, but it can take too much resources, if the game has a lot of entities.. So, how does a engine like Source take care (process, update, draw, etc) of the game objects?"} {"_id": 47, "text": "How to use batch rendering with an entity component system? I have an entity component system and a 2D rendering engine. Because I have a lot of repeating sprites (the entities are non animated, the background is tile based) I would really like to use batch rendering to reduce calls to the drawing routine. What would be the best way to integrate this with an engtity system? I thought about creating and populating the sprite batche every frame update, but that will probably be very slow. A better way would be to add a reference to an entity's quad to the sprite batch at initialization, but that would mean that the entity factory has to be aware of the Rendering System or that the sprite batch has to be a component of some Cache entity. One case violates encapsulation pretty heavily, while the other forces a non game object entity in the entity system, which I am not sure I like a lot. As for engine, I am using Love2D (Love2D website) and FEZ ( FEZ website) as entity system(so everything is in Lua). I am more interested in a generic pattern of how to properly implement that rather than a language library specific solution. Thanks in advance!"} {"_id": 47, "text": "Multiple traversal of a component based hierarchy Let's say a game use a component based hierarchy to store all of its entities. So it can have objects, characters, lights organized in some kind of tree. When rendering the game, it needs to first render objects, then lights. So it needs to first traverse the hierarchy and render all the objects it finds, then traverse a second time to render all the lights it finds. What is a better way to do this? If the hierarchy has thousands of entities, it could be slow to traverse twice the tree. I thought about having two lists, one containing objects to render, the second one being lights. Each time the user adds an entity to the hierarchy, it adds it to the corresponding list. This way, the game only have to traverse the object list then the light list, without traversing useless entities. What is the best option?"} {"_id": 47, "text": "Should fields in components in an ECS use polymorphism? I've just started to try and learn how to use ECS (Entity component systems), but I'm having trouble understanding the concepts behind components. Should adding more types of components, or trying to make a component reusable through its fields be favored? For example, if I'm trying to give all entities a shape for collision detection, should I have a different component for every shape (RectangleComponent, CircleComponent, PolygonComponent), or should I have one ShapeComponent, and in there have a field which is of type Shape, with class Shape having subclasses Rectangle, Circle, and Polygon. I'm unsure because using a Shape seems to be much more flexible and easier to implement systems, but it also feels like I'm violating the ECS rule of not having any functionality in components."} {"_id": 47, "text": "Entity polymorphism and entity attributes I want to design the entity system of my game in a way such that entities are modular, easily modified without affecting other entities, and finally easy to add new types of entities. So ideally some version of component based design. In some parts of the code I want to deal with entities generally and abstractly, for example \"update all entities\" and \"render all entities\", however in other parts I want to deal with specific types of entity, like when a Soldier entity is fighting a Tank entity. The problem is some entities need attributes which others do not. For example a soldier needs HP but a missile do not. How do I keep entity attributes modular, and avoid adding every attribute in the game to the Entity object?"} {"_id": 47, "text": "Multiple lua scripts using newthread I'm trying to hook lua scripts to my entities, where several entities of the same type want to use a separate instance of the same script. Problem is, when I run two or more scripts and use any C api functionality, I get an access violation after some time. I'm guessing some kind of stack corruption occurs but I'm not sure. The application is single threaded but uses lua newthread for each entity, and I then use lua resume on each new thread for when I want the scripts to run. The code looks like this. Script 1 function Update(dt, owner) print(\"Script 1\") pos GetPosition(owner) end Script 2 function Update(dt, owner) print(\"Script 2\") end GetPosition() static int GetPosition(lua State L) Core Entity entity lua tonumber(L, 1) Core TransformationComponent tc WGETC lt Core TransformationComponent gt (entity) lua newtable(L) for (int i 0 i lt 2 i ) lua pushnumber(L, tc gt position i ) lua rawseti(L, 2, i) return 1 How I create new lua threads (m luaState is the global parent state to which I bind all my functions) lua State LuaCore CreateThread(std string file) lua State newState lua newthread(m luaState) lua newtable(newState) new globals table lua newtable(newState) metatable lua pushliteral(newState, \" index\") lua pushvalue(newState, LUA GLOBALSINDEX) original globals lua settable(newState, 3) lua setmetatable(newState, 2) lua replace(newState, LUA GLOBALSINDEX) replace newState's globals luaL dofile(newState, file.c str()) return newState How each script is called lua State ls GetChildState(stateIndex) lua pushstring(ls, functionName.c str()) lua gettable(ls, LUA GLOBALSINDEX) SimpleLuaCallData slcd (SimpleLuaCallData )inData lua pushnumber(ls, slcd gt dt) lua pushnumber(ls, slcd gt ownerID) lua pcall(ls, 2, 0, 0) return nullptr If I remove the call to GetPosition from Script 1, the application runs without issue. Am I missing some kind of required clean up or garbage collection problems? I'd like to try and avoid creating a new state for each entity, as that seems excessive and sharing globals via the core state is nice. lua pcall doesn't produce any results. The application eventually stops running Script 1 and after a few more cycles it gets the access violation on lua gettable(ls, LUA GLOBALSINDEX) in the calling function."} {"_id": 47, "text": "How can I efficiently implement a bitmask larger than 64 bits for component existence checks? In my ECS implementation, I use bit wise operations (as described and illustrated in this thread) to tell an entity what type of components it currently consists of. So my Entity class has the following member unsigned long m CompMask The different component types are then defined as an enum, whose member values are all power of two enum ComponentType COMP TYPE UNKNOWN 0, COMP TYPE PERSON 1, COMP TYPE RENDERABLE 2, COMP TYPE MOVEABLE 4, ... Each time a new component is added to my entity instance, I do the following bit operation to update the mask (where newType is a member of the enum mentioned above) m CompMask newType This approach enables me to efficiently check if a certain entity instance has a certain component (and hence might be relevant for a specific system), like so return (m CompMask amp type) The limiting factor in this approach however is the m CompMask variable since it won't be able to handle more than 64 component types (if I increase it to unsigned long long). I don't expect to be needing more than that in my current project, but nonetheless I'd like to hear some ideas regarding alternatives that allow more than 64 types (as big games certainly need to) while still maintaining the ease and efficiently of those bit wise operations as much as possible? Any ideas how this is handled in \"proper big\" projects?"} {"_id": 47, "text": "Handling movement using an Entity Component based System Architecture I have seen various descriptions of how to handle movement in a component based entity framework. The most common I've stumbled across is the idea of using components called Controller, Physics, Transform, Velocity, and Collider. The idea here is that the Controller influences the Velocity component when movement keystrokes are detected. The Velocity component in turn influences Physics. Once the simulation has been stepped, the Collider is either affected if a collision occured or is not if no collision happened. In the end, the Transform is updated with the new position from the physics simulation step and thusly the Renderable needs to be adjusted so it is drawn in the proper location. I have often read that one needs to consider both physics driven and non physics driven entities. As outlined in the above paragraph, manipulating physics driven entities seems like a piece of cake. The difference with non physics driven entities is that the Velocity component values need to simply be applied to the the Transform based on delta time. This would allow moving the entity without being concerned with physics nor collision detection. For physics driven entities, one simply iterates entities with both Velocity and Physics components. But for non physics driven entities, simply iterating over entities with a Velocity component isn't sufficient as it would include the above subset as well. So there must be some factor that clearly separates these two cases. So with these two cases in mind, how would movement actions that influence the values of Velocity be carried out in such a system to manipulate both types of entities whether physics plays a roll in their movement or not?? And lastly, considering that there may be times where the transform for an entity needs to be manipulated directly, such as player clicking on a portal to be teleported to another x y z position, how would one properly propagate this change to adjust both the physics step simultation and the renderable's draw location? EDIT bobenko Your explanations provide insight to the most common case where objects are simulated via physics but I'm somewhat lost on the Kinematic aspect regarding updating an entities position via a velocity value? Are you simply implying that some code of my own will apply movement to the entity via velocity, thus being Kinematic? I still am interested in your explanation on how to avoid cyclic notifications effectively when aspects of these components involved change. For all who answered, I'm still not clear how would you handle teleporting an entity from one position to another? Would this involve turning off physics, teleporting the player, then turning physics on after teleport finished? Turning physics on off can be as simply as setting the entity as Kinematic YES NO, right?"} {"_id": 47, "text": "Why is it a bad idea to store methods in Entities and Components? (Along with some other Entity System questions.) This is a followup to this question, which I answered, but this one tackles with a much more specific subject. This answer helped me understand Entity Systems even better than the article. I've read the (yes, the) article about Entity Systems, and it told me the following Entities are just an id and an array of components (the articles says that storing entities in components isn't a good way of doing things, but doesn't provide an alternative). Components are pieces of data, that indicate what can be done with a certain entity. Systems are the \"methods\", they perform manipulation of data on entities. This seems really practical in many situations, but the part about components being just data classes is bothering me. For example, how could I implement my Vector2D class (Position) in an Entity System? The Vector2D class holds data x and y coordinates, but it also has methods, which are crucial to its usefulness and distinguish the class from just a two element array. Example methods are add(), rotate(point, r, angle), substract(), normalize(), and all other standard, useful, and absolutely needed methods that positions (which are instances of the Vector2D class) should have. If the component was just a data holder, it wouldn't be able to have these methods! One solution that could probably pop up would be to implement them inside systems, but that seems very counter intuitive. These methods are things that I want to perform now, have them be complete and ready to use. I don't want to wait for the MovementSystem to read some expensive set of messages that instruct it to perform a calculation on the position of an entity! And, the article very clearly states that only systems should have any functionality, and the only explanation for that, which I could find, was \"to avoid OOP\". First of all, I don't understand why should I refrain from using methods in entities and components. The memory overhead is practically the same, and when coupled with systems these should be very easy to implement and combine in interesting ways. The systems, for example, could only provide basic logic to entities components, which know the implementation themselves. If you ask me this is basically taking the goodies from both ES and OOP, something that can't be done according to the author of the article, but to me seems like a good practice. Think about it this way there are many different types of drawable objects in a game. Plain old images, animations (update(), getCurrentFrame(), etc), combinations of these primitive types, and all of them could simply provide a draw() method to the render system, which then doesn't need to care about how the sprite of an entity is implemented, only about the interface (draw) and the position. And then, I would only need an animation system which would call animation specific methods that have nothing to do with the rendering. And just one other thing... Is there really an alternative to arrays when it comes to storing components? I see no other place for components to be stored other than arrays inside an Entity class... Maybe, this is a better approach store components as simple properties of entities. For example, a position component would be glued to entity.position. The only other way would be to have some kind of a strange lookup table inside systems, that references different entities. But that seems very inefficient and more complicated to develop than simply storing components in the entity."} {"_id": 47, "text": "How do I go about creating the \"Watcher\" component? Last weekend, I spent several hours writing a basic entity component model, in JavaScript. I was largely referencing the Ash Actionscript game engine. I successfully worked out how the systems, components, nodes, and entities all link up, but one thing that eludes me is how to implement the \"watcher\" that checks the entities for their components, creates nodes for them, adds those nodes to the various systems automatically, and watches for any changes in the components on an entity. I was a bit confused by the way it works, in Ash, and all of the posts and tutorials on the subject that I have read seem to forgo the details of that part of the implementation. Right now, I currently have the following Entity, which is assigned components. Engine, which keeps a track of the systems and entities. Node, which contains references to the components in an entity that we want the system to modify (I am currently creating these, manually, and adding it to the system). Component, which contains the data to be modified by the system. System, which operates on the nodes, which in turn change the data in the entity. I also have various other classes, dedicated to holding lists of the various objects. How do I go about creating the \"Watcher\" component?"} {"_id": 47, "text": "Superclassing RPG Game Entities I am in the design process of an RPG game and I have no experience at all in game dev. This question is about how I should approach entity management using OOP classes. My train of thought is as followed Have Entity interface with basic update() function \"Mortal\" class and \"NPC\" class implement Entity \"Hero\" and \"Monster\" class inherit from \"Mortal\" class In this case, Mortal class are all those entities that have statuses such as HP and MP. NPC are self explanatory. I am sure my approach is naive so I would like to know the pros and cons and what would be a better way to approach this."} {"_id": 47, "text": "Multiple lua scripts using newthread I'm trying to hook lua scripts to my entities, where several entities of the same type want to use a separate instance of the same script. Problem is, when I run two or more scripts and use any C api functionality, I get an access violation after some time. I'm guessing some kind of stack corruption occurs but I'm not sure. The application is single threaded but uses lua newthread for each entity, and I then use lua resume on each new thread for when I want the scripts to run. The code looks like this. Script 1 function Update(dt, owner) print(\"Script 1\") pos GetPosition(owner) end Script 2 function Update(dt, owner) print(\"Script 2\") end GetPosition() static int GetPosition(lua State L) Core Entity entity lua tonumber(L, 1) Core TransformationComponent tc WGETC lt Core TransformationComponent gt (entity) lua newtable(L) for (int i 0 i lt 2 i ) lua pushnumber(L, tc gt position i ) lua rawseti(L, 2, i) return 1 How I create new lua threads (m luaState is the global parent state to which I bind all my functions) lua State LuaCore CreateThread(std string file) lua State newState lua newthread(m luaState) lua newtable(newState) new globals table lua newtable(newState) metatable lua pushliteral(newState, \" index\") lua pushvalue(newState, LUA GLOBALSINDEX) original globals lua settable(newState, 3) lua setmetatable(newState, 2) lua replace(newState, LUA GLOBALSINDEX) replace newState's globals luaL dofile(newState, file.c str()) return newState How each script is called lua State ls GetChildState(stateIndex) lua pushstring(ls, functionName.c str()) lua gettable(ls, LUA GLOBALSINDEX) SimpleLuaCallData slcd (SimpleLuaCallData )inData lua pushnumber(ls, slcd gt dt) lua pushnumber(ls, slcd gt ownerID) lua pcall(ls, 2, 0, 0) return nullptr If I remove the call to GetPosition from Script 1, the application runs without issue. Am I missing some kind of required clean up or garbage collection problems? I'd like to try and avoid creating a new state for each entity, as that seems excessive and sharing globals via the core state is nice. lua pcall doesn't produce any results. The application eventually stops running Script 1 and after a few more cycles it gets the access violation on lua gettable(ls, LUA GLOBALSINDEX) in the calling function."} {"_id": 47, "text": "Superclassing RPG Game Entities I am in the design process of an RPG game and I have no experience at all in game dev. This question is about how I should approach entity management using OOP classes. My train of thought is as followed Have Entity interface with basic update() function \"Mortal\" class and \"NPC\" class implement Entity \"Hero\" and \"Monster\" class inherit from \"Mortal\" class In this case, Mortal class are all those entities that have statuses such as HP and MP. NPC are self explanatory. I am sure my approach is naive so I would like to know the pros and cons and what would be a better way to approach this."} {"_id": 47, "text": "State Screen management in Entity Component Systems My entity component system is happily humming along and, despite some performance concerns I initially had, everything is working fine. However, I've realized that I missed a crucial point when starting this thing how do you handle different screens? At the moment, I have a GameManager class which owns a component manager and entity manager. When I create an entity, the entity manager assigns it an ID and makes sure it's tracked. When I modify the components that are assigned to an entity. an UpdateEntity method is called, which alerts each of the systems that they may need to add or remove the entity from their respective entity lists. A problem with this is that the collection of entities operated on by each system is determined solely by the individual Systems, typically based on a \"required component\" filter. (An entity has to have a Renderable component to be rendered, for instance.) In this situation, I can't just keep collections of entities per screen and only Update Draw those collections. They'd have to either be added and removed depending on their applicability to the current screen, which would cause their associated components to be removed, or enable disable entities in a group per screen to hide what's not supposed to be visible. These approaches seem like really, really crappy kludges. What's a good way to handle this? A pretty straightforward way that comes to mind is to create a separate GameManager (which in my implementation owns all of the systems, entities, etc.) per screen, which means that everything outside of the device context would be duplicated. That's bothersome because some things are always visible, or I might want to continue to display the game under a translucent menu window. Another option would be to add a \"layer\" key to the GameManager class, which could be checked against a displayable layer stack held by the game manager. System.Draw() would be called for each active layer, in the required order as determined by the stack. When the systems request an iterator for their respective entity collections, it would be pre filtered to a (cached) set of those entities that participate in the active layer. Those collections could be updated from the same UpdateEntity event that's already used to maintain each system's entity collections. Still, kinda feels like a hack. If I've coded myself into a corner, feel free to throw tomatoes as long as they're labeled with a helpful suggestion. Hooray for learning curves."} {"_id": 48, "text": "Point welding on generated terrain I am converting two 2D images (A Voronoi graph and a Diamond Square noise map) into a 3D object. However when finding the corner points of the Voronoi I am left with gaps, so I thought to drop these by calculating adjacency to existing nodes before creating the vertex. However no matter which algorithm for the weld I use, or the tolerance level of the distance I can't seem to get it to work. This has led me to believe I am doing something wrong. Image of the issue These gaps do not appear if I run without the weld, they are created by the weld jumping to spots, but then later welds not finding that spot. I have even tried to increment the weld distance to a maximum of 10, if a suitable node wasn't found. But this is far to aggressive and has the effect of simplifying the mesh instead and creating more gaps. My Repo for the full code is here https github.com HughAJWood TerrainGenerator private void CalculatePolys() var nodesForEdges new List lt VNode gt () foreach (var region in regions) foreach (var point in region) if (point null) continue We calculate where the voronoi node corners are, and pass them into the region var diff ColoursDifferent(point) if (diff gt 1) RenderNodePointsOnImage(point) Points are 2D, so to translate to 3D they are set to the Z property of the 3D node var node new VNode X point.X, Z point.Y Weld points within 1 unit from each other by determining if we already have one that exists then using the existing node instead A weld is calculated by determining the X,Z distance to see if we have a node stored already that is within 2 units of the node we are creating VNode existingNode Nodes.FirstOrDefault(n gt n.Adjacent(node)) if (existingNode null) Optimise node creation by skipping perlin lookup and ID iteration for only when needed node.ID VNodeId node.Y perlin.GetPixel(point.X, point.Y).R Nodes.Add(node) Mesh.ControlPoints.Add(new Vector4(node.X, node.Y, node.Z, 1)) else node existingNode nodesForEdges.Add(node) if (i gt 20) return AddNodesToMeshAsPolys(nodesForEdges) nodesForEdges.Clear() The adjacency method is currently simplified to the fact I want to ignore the height of the node. internal static bool Adjacent(this VNode a, VNode b, int tolerance 3) var distance Math.Abs(a.X b.X) Math.Abs(a.Z b.Z) return distance lt tolerance UPDATE I have tried sorting the points by distance and fuzzy distance, both sort in the correct order. Then I tried taking the first point and using that as the welding point. Same effect. I tried to average the points at the intersections at the image level and pass that back as the point every time, then weld. Same effect. Clearly there are many approaches I can take for this, the problem arises when there are 2 points close to each other on the edge of a voronoi region. Sometimes they weld and create a gap. Sometimes however in some variances of the algorithm that the points don't weld even though their X,Z coordinates are very close to each. I'm still stumped as how to approach this."} {"_id": 48, "text": "Polygon count target range for MMO being released in 2 years What would a realistic poly count target range be for NPC and player models in a 3D MMO that will be released in 2 years? What about poly count target range for the entire camera view (environment, NPC and player meshes)? I read in some places that one should not aim too low if the game will come out in a couple years because technology is always advancing. If you can give some mesh poly stats on what other current MMOs MMORPGs are running and future projections, that would be great. Thank you."} {"_id": 48, "text": "How to convert an octree to a polygon mesh? So if I have dynamic voxel terrain data stored in an octree representation what would be the best way to go about converting the octree to a polygon mesh which I can render with OpenGL? A lot of the meshing algorithms I have found online assume that voxel data is stored in a 3D Array however for the level of detail I am using storing chunk data in a massive array isn't really an option (chunk size 64x1024x64 with each block roughly 4bytes) split into several 64x64x64 small octrees, I could make the chunk size smaller but then that means more draw calls etc. Basic searches on google for 'meshing an octree' seem to bring up lots of research on doing the inverse (converting from meshes to SVOs). The problem with using these algorithms on the octree instead of the array is that the octree has a much slower access time not to mention the time cost of copying the data from the octree representation. I have considered the possibility of converting to an RLE or spatial hashing system but these two systems both have their drawbacks especially since I plan to use the same octree when I come to implement collision detection. I would guess that it would be best to traverse down the tree rather than iterating over it like an array, but some more ideas about how I could optimise this would be appreciated."} {"_id": 48, "text": "Simulate dirt spread (Normal distribution?) This question is technically more math related, but it has to do with a simulation so I am here first. I can post this in the math SE instead if needed. I am in the process of trying out some mesh deformation simulating the effect of sand dirt being poured in a pile (Think hourglass sand) and I am trying to determine the best way to calculate the spread instead of becoming increasingly taller. I don't intend on actually matching sand dirt physics, I just want to get my mesh to be somewhat close to the shape that pile would make as it grows. I'm pretty sure that Normal Distribution is what I want, so in my desmos graph below, think of f(x) green line as the current dirt sand piling up (where I am at in my code) and f1(x) purple line as the spread version (what I want to happen instead). f1(x) is not correct but I think it is pretty close. Essentially i need the area of f1(x) to always equal the area of f(x) but as f(x) gets taller, f1(x) gets wider and taller, but not as tall as f(x). https www.desmos.com calculator ir8if2u8qq lt a title \"View with the Desmos Graphing Calculator\" href \"https www.desmos.com calculator ir8if2u8qq\" gt lt img src \"https s3.amazonaws.com calc thumbs production ir8if2u8qq.png\" width \"200px\" height \"200px\" style \"border 1px solid ccc border radius 5px\" gt lt a gt I hope this makes sense to you gurus. If not, I can try to clarify more. Edit Also, if you open that graph, the slider for variable 'h' is the one im essentially trying to work with."} {"_id": 48, "text": "How can I produce 3D environments for VR from HDRI images? I have a question regarding to the HDRI maps as many some of you have a bit of experience in this field especially for Oculus Rift platform! I've been trying to achieve a 3D landscape from this HDRI map. (Also I highly recommend this website for others )!) I even decided to render in Maya few images from the orthographic perspective but unfortunately still no luck. See the results here on YouTube. Is there any other method to reconstruct 3D models just from images and use them to create environment?"} {"_id": 48, "text": "Does it make sense to use voxel editors only for meshing? I am a hobbyist game developer. If there is something that I really don't like is 3D modeling, in particular all the work that needs to be put in the \"pipeline\" for the creation of models, in particular UV mapping. Remembering games like Minecraft or \"Little big planet\", I was wondering if voxel editors could be used for just modeling let me explain using a voxel editor to make each object I need for my games and then export them singularly as FBX with either marching cubes or even better dual contouring for meshing. Does an approach like this make sense in terms of performance? From what I can tell, I would need a voxel software which allows all of the following criteria. Dual contouring meshing FBX or OBJ export of meshed area Multiple materials Now, it looks like such software doesn't exist, which makes me think that this approach for 3D modeling may be totally wrong. Any heads up on this?"} {"_id": 48, "text": "matrix to transform unit cube to space defined by 8 arbitrary points I asked a question relating to similar to this already, but I think this is a clearer objective of what Im trying to achieve.. or whether its possible at all! Im trying to find a transformation (matrix ideally) which would transform the 8 points of a 3d unit cube to 8 arbitrary points in space. The 8 target points have no known structure. e.g My gut feeling is that a matrix is unable to provide this xform since the cube faces vertices can be concave.. but are there any other methods of transformation? Thanks!"} {"_id": 48, "text": "Vertex Normals, Loading Mesh Data My test FBX mesh is a cube. From what I surmise, it seems that the cube is on the extreme end of this issue, but I believe that the same issue would be able to occur in any mesh Each vertex has 3 normals, each pointing a different direction. Of course loading in any type of mesh, potentially ones having thousands of vertices, I need to use indices and not duplicate shared verts. Currently, I'm just writing the normals to the vertex at the index that the FBX data tells me they go to, which has the effect of overwriting any previous normal data. But for lighting calculations I need more info, something that's equivalent to a normal per face, but I have no idea how this should be done. Do I average the 3 different verts' normals together or what?"} {"_id": 48, "text": "Identifying mesh format from initial bytes I have a file containing mesh data whose blocks seem to start with DWORDS like 0x1 0x1 0x3100026f 0x1 0x30000112 or 0x1 0x1 0x310007b2 0x1 0x30000112 or 0x10000006 0x3 0x310001f6 0x310001f6 0x310001f6 They don't look like .x binaries. Any other ideas? UPDATE Here's more 00000001 00000001 3100026F 00000001 30000112 000000C7 BD869270 3F0372D4 00000000 BD41F15F 3F11A611 3F522E05 3E40EF5A 3E17CDF8 3E40993C BF504FBD 3F0CCC2A BF78001B BE654B6A 3DDA7965 BD80EB99 3F003679 3C0BDAE1 BD3DD880 3F112A76 3F528732 3E8EFD04 3E185DD8 3E3984B8 BF48A923 3F180DA9 BF7854DC BE6599AE 3DBF7319 BCD7235C 3F041CCC 00000000 BF52314E 3F12223D 00000000 3F727B04 3C22FD80 3E29BCD1 3F7C0367 3D6FCD12 3E70A826 BCE91707 BF78B921 BCD7235C 3F008C87 3C28E0F6 BF6B36D8 3BD28E32 3ECA109F 3F4AEA89 3D894EC0 BE18A98D 3F7CC7A8 3D57AE4B 3E48D2F6 B46C577B 3F7B0753 BE3DBAC2 3EF41E67 It looks like some of these are almost certainly floats and others are almost certainly not. And it appears (not shown here) that after a long list of valid floats, there is a long list of DWORDS that aren't valid floats. A list of vertices followed by some table of indices?"} {"_id": 48, "text": "Calculating vertex normals to be able to have both sharp edges and smooth gradients I'm computing area weighted vertex normals, but lighting looks bad on meshes containing sharp edges and corners (e.g. cubes look 'blobby' as the light leaks onto the dark sides). Is there a way of calculating using vertex normals to preserve sharp edges and still have smooth regions? Ideally, without the need to create extra geometry (e.g. splitting faces adjacent to a sharp edge and creating new vertices). Most sources talk about having different 'smoothing groups' which influence geometry generation. Could someone explain what are \"per corner\" normals? From Libigl tutorial \"Storing normals per corner is an efficient and convenient way of supporting both smooth and sharp (e.g. creases and corners) rendering.\""} {"_id": 48, "text": "Load destructible mesh at runtime Using the tutorial Components and Collision as a guide, to dynamically load a SphereShape the following is done AClass AClass() Create USphereComponent USphereComponent sphere NULL sphere CreateDefaultSubobject lt USphereComponent gt (TEXT(\"Root\")) sphere gt InitSphereRadius(1.0f) sphere gt SetCollisionProfileName(TEXT(\"PhysicsActor\")) sphere gt SetSimulatePhysics(true) sphere gt WakeRigidBody() Create UStaticMeshComponent UStaticMeshComponent mesh NULL mesh CreateDefaultSubobject lt UStaticMeshComponent gt (TEXT(\"Mesh\")) mesh gt SetupAttachment(RootComponent) Load asset from filesystem define ASSET TEXT(\" Game MobileStarterContent Shapes Shape Sphere.Shape Sphere\") static ConstructorHelpers FObjectFinder lt UStaticMesh gt asset(ASSET) undef ASSET if (asset.Succeeded()) mesh gt SetStaticMesh(asset.Object) RootComponent sphere Now, when I try the same set of steps, but this time for an Actor that has a UDestructibleComponent instead of a USphereComponent AClass AClass() Create our UDestructibleComponent UDestructibleComponent destructible NULL destructible CreateDefaultSubobject lt UDestructibleComponent gt (TEXT(\"Root\")) destructible gt SetCollisionEnabled(ECollisionEnabled PhysicsOnly) destructible gt SetSimulatePhysics(true) destructible gt SetEnableGravity(false) destructible gt WakeRigidBody(NAME None) Load asset from filesystem define ASSET TEXT(\" Game MobileStarterContent Shapes Shape Cube DM\") static ConstructorHelpers FObjectFinder lt UDestructibleMesh gt asset(ASSET) undef ASSET if (asset.Succeeded()) UE LOG(LogTemp, Warning, TEXT(\"It worked!\")) RootComponent destructible I receive the following errors ConstructorHelpers.h 105 20 error cannot initialize a parameter of type 'UObject ' with an lvalue of type 'UDestructibleMesh ' ValidateObject( Object, PathName, ObjectToFind ) ConstructorHelpers.h 29 19 error incomplete type 'UDestructibleMesh' named in nested name specifier UClass Class T StaticClass() I've also tried adding .Shape Cube DM to the end of the string, similar to how the first asset was imported, but no luck. What is the correct way to load a DestructibleMesh from the filesystem and apply it to the UDestructibleComponent?"} {"_id": 48, "text": "Smooth mesh from voxel grid Im trying to implement smooth voxel grid meshing using marching cubes algorithm but I dont quite understand how to do the interpolating (I understand that this would solve the problem) to achieve the smooth transitions on the borders between the empty space and filled space. In the picture above I have rendered my voxel grid cells as cubes. Currently the voxel grid is just a 3d array which stores the values if the cell is empty (0.0) or filled(1.0) (not sure if this is ok, do I need to store each cell corners instead). When processing marching cubes iteration I have to sample my data at floating point indices e.g. I need to look up if position (3.316, 0.16, 0.5) is empty space on the surface of the data inside the data. Currently I just check the cell value where the position is e.g. (3, 0, 0) for the example above which results with cube mesh. This shows what I want to do more or less"} {"_id": 48, "text": "Angle between two planes I have two triangles in 3d space which share 1 edge and I would like to determine if the angle between their normal vectors is \"uphill\" or \"downhill\". In other words, if you set one flat, would the angle between them be acute (uphill) or obtuse (downhill). Hopefully that makes sense. So far I have the normal vectors of each triangle and have calculated the angle between the two triangles, however this angle is always 90 degrees. Vector3 v1 triangle1.Normal Vector3 v2 triangle2.Normal float cosAngle Vector3.Dot(v1, v2) (v1.magnitude v2.magnitude) float degAngle Mathf.Acos(cosAngle) Mathf.Rad2Deg Is there a trick I am missing that lets me determine which direction this angle is in?"} {"_id": 48, "text": "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. To find the normal, I'm using the normalized vector from the nearest point on the mesh to the center of the sphere. Now 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. In 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). Now, 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. The 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?"} {"_id": 48, "text": "3D meshes for WPF (XAML)? I'm trying to make a WPF 3D game. WPF uses XAML. I'm trying to find free 3D assets from the internet. ) What format of 3D models I should be looking for, direct XAML or 3D Studio format or what? I know that there are some 3D Studio format to XAML converters, but I don't know if they really work..."} {"_id": 48, "text": "matrix to transform unit cube to space defined by 8 arbitrary points I asked a question relating to similar to this already, but I think this is a clearer objective of what Im trying to achieve.. or whether its possible at all! Im trying to find a transformation (matrix ideally) which would transform the 8 points of a 3d unit cube to 8 arbitrary points in space. The 8 target points have no known structure. e.g My gut feeling is that a matrix is unable to provide this xform since the cube faces vertices can be concave.. but are there any other methods of transformation? Thanks!"} {"_id": 48, "text": "How to convert an octree to a polygon mesh? So if I have dynamic voxel terrain data stored in an octree representation what would be the best way to go about converting the octree to a polygon mesh which I can render with OpenGL? A lot of the meshing algorithms I have found online assume that voxel data is stored in a 3D Array however for the level of detail I am using storing chunk data in a massive array isn't really an option (chunk size 64x1024x64 with each block roughly 4bytes) split into several 64x64x64 small octrees, I could make the chunk size smaller but then that means more draw calls etc. Basic searches on google for 'meshing an octree' seem to bring up lots of research on doing the inverse (converting from meshes to SVOs). The problem with using these algorithms on the octree instead of the array is that the octree has a much slower access time not to mention the time cost of copying the data from the octree representation. I have considered the possibility of converting to an RLE or spatial hashing system but these two systems both have their drawbacks especially since I plan to use the same octree when I come to implement collision detection. I would guess that it would be best to traverse down the tree rather than iterating over it like an array, but some more ideas about how I could optimise this would be appreciated."} {"_id": 48, "text": "Multiple UV coordinates in Unreal Engine Procedural Mesh Component? How can I have multiple UV coordinates per vertex in a Procedural Mesh Component? My goal is to create a UV editor. I know it is possible to generate multiple vertices per corner, as in UKismetProceduralMeshLibrary GenerateBoxMesh but that's 24 vertices instead of 8 for a simple box. Would this be a performance problem? I know that FRawMesh (used when importing an FBX into a static mesh) contains multiple UVs per \"wedge\" (properties stored for each corner of each face). But I don't know how to set or create the equivalent in custom mesh component (except by duplicating vertices). I know that casperjeff modified the Procedural Mesh Component plugin to add an additional UV set (as he explains here), but I don't really know how to make one UV set correspond to one face. I am looking for an efficient solution in terms of performances."} {"_id": 48, "text": "How to export 3D models that consist of several parts (eg. turret on a tank)? What are the standard alternatives for the mechanics of attaching turrets and such to 3D models for use in game? I don't mean the logic, but rather the graphics aspects. My naive approach is to extend the MD2 like format that I'm using (blender exported using a script) to include a new set of properties for a mesh that is anchored in another 'parent' mesh. The anchor is a point and normal in the parent mesh and a point and normal in the child mesh these will always be colinear, giving the child rotation but not translation relative to the parent point. has a normal that is aligned with a 'target'. Classically this target is the enemy that is being engaged, but it might be some other vector e.g. 'the wind' (for sails and flags (and smoke, which is a particle system but the same principle applies)) or 'upwards' (e.g. so bodies of riders bend properly when riding a horse up an incline etc). that the anchor and target alignments have maximum and minimum and a speed coeff. there is game logic for multiple turrets and on a model and deciding which engages which enemy. 'primary' and 'secondary' or 'target0' ... 'targetN' or some such annotation will be there. So to illustrate, a classic tank would be made from three meshes a main body mesh, a turret mesh that is anchored to the top of the main body so it can spin only horizontally and a barrel mesh that is anchored to the front of the turret and can only move vertically within some bounds. And there might be a forth flag mesh on top of the turret that is aligned with 'wind' where wind is a function the engine solves that merges environment's wind angle with angle the vehicle is travelling in an velocity, or something fancy. This gives each mesh one degree of freedom relative to its parent. Things with multiple degrees of freedom can be modelled by zero vertex connecting meshes perhaps? This is where I think the approach I outlined begins to feel inelegant, yet perhaps its still a workable system? This is why I want to know how it is done in professional games ) Are there better approaches? Are there formats that already include this information? Is this routine?"} {"_id": 48, "text": "How do I implement real time mesh deformation, with regards to environmental damage? I would like to be able to add the following feature to my tech demo at the moment bullets hit the walls, little pieces fly out of them, as well as decals appearing on the walls. Computing power is good enough, now, so that many games have destructible environments. I would like bullets to shatter small surface segments off the wall, ideally the segments that fly off would directly relate to the hole that is left, though I don't even know if this is how it's done in commercial games. How is this done? Are there simply a number of different meshes that are swapped out as, and when, objects are hit? I assumed that this would not be an accurate enough solution. Is real time mesh deformation feasible. and if so, how is it done?"} {"_id": 48, "text": "Polygon count target range for MMO being released in 2 years What would a realistic poly count target range be for NPC and player models in a 3D MMO that will be released in 2 years? What about poly count target range for the entire camera view (environment, NPC and player meshes)? I read in some places that one should not aim too low if the game will come out in a couple years because technology is always advancing. If you can give some mesh poly stats on what other current MMOs MMORPGs are running and future projections, that would be great. Thank you."} {"_id": 48, "text": "How to convert an octree to a polygon mesh? So if I have dynamic voxel terrain data stored in an octree representation what would be the best way to go about converting the octree to a polygon mesh which I can render with OpenGL? A lot of the meshing algorithms I have found online assume that voxel data is stored in a 3D Array however for the level of detail I am using storing chunk data in a massive array isn't really an option (chunk size 64x1024x64 with each block roughly 4bytes) split into several 64x64x64 small octrees, I could make the chunk size smaller but then that means more draw calls etc. Basic searches on google for 'meshing an octree' seem to bring up lots of research on doing the inverse (converting from meshes to SVOs). The problem with using these algorithms on the octree instead of the array is that the octree has a much slower access time not to mention the time cost of copying the data from the octree representation. I have considered the possibility of converting to an RLE or spatial hashing system but these two systems both have their drawbacks especially since I plan to use the same octree when I come to implement collision detection. I would guess that it would be best to traverse down the tree rather than iterating over it like an array, but some more ideas about how I could optimise this would be appreciated."} {"_id": 48, "text": "How to make low poly ground look better I'm working in Unity and have created some low poly meshes using blender. Currently, the meshes look good, but the ground seems very lacking. I am not sure how to make it feel natural or even look good in general. Here is a current image The ground needs to remain mostly flat due to the game placing flat objects on the top of the plane and the image shows the exact camera angle we are using. But, as you can see in the image, the ground is extremely lacking and it doesn't look like a ground but instead just a flat background color. I've tried textures but it does not look good with the trees and low poly design. How can I make the ground look better?"} {"_id": 48, "text": "Creating a basic character skeleton from code I'd like to have a procedural system that uses a string of data to create a 3d creature. The way I've thought to do this is to use the code to generate a simple creature skeleton (I'll get to the skin generation when I have time) so I can test different source data's effect on the structure produced. How can i use a set of data to generate the simple 3d skeleton? The code would have information used to show what type of bone it was(hierarchy), the bone length, and how the bone was positioned and use this to make the model. (At least in planning, I don't know how to implement it) Edit The goal is to create creatures of different forms and skeletons. The creation will be mirrored down the spine so both sides are the same. I'd like it to be highly adaptable but I'd like to specify a max of 4 legs and 4 arms (8 limb max only 4 on ground for walking). Being able to create a basic structure for humanoids, quadrupeds, and mixes (like a centaur or biped with no arms) is the goal. I've looked for how to create a model off of the code procedurally, looking at stuff like FRep isosurfaces and metaballs, but I'm stumped on how to make it happen. I decided any progress is better that none, so I'd like to get a generator for something like an animators skeleton example to make sure I can get working structures (and later have something to work with to begin working on the animation algorithm). Sorry for the lack of information at first, I was trying to keep the question simple. If you have an idea for the creation of the structure(skeleton) or maybe even the form itself I'd appreciate the help. Thanks"} {"_id": 48, "text": "MD5Mesh Calculate Vertex Normals I am writing an MD5 3D model loader to display animated models. The vertices and texcoords load in correctly, but the lighting is supposed to be smooth. I calculate per vertex normals by looping through all triangles, finding the triangle normal, and then adding that to each of the triangle's vertices' normal (follow?). Then, I normalize all the normals. This should work, but md5 declares each vertex with a texcoord, meaning that if I have a single vertex that has different texcoords for each of the faces it's attached to, it declares multiple vertices at the same position. Each of these will end up with its own normal, resulting in flat shading. Should I somehow merge duplicate vertices, or export the model differently, or do something fancy that I haven't thought of? Thanks!"} {"_id": 48, "text": "3DS Max equivalent to vertex weight painting I'm working in 3ds max on models for an Iphone game project and finding that using the Physique modifier is to general for rigging. When working with so few vertices I want to be able to directly tell how much weight a bone should have on a specific vertex. Is there a 3ds max equivalent to the Softimage XSI vertex weight painting? As this would be perfect for this job. Many thanks"} {"_id": 48, "text": "What are perimeter and aspect ratio, in the context of 3D mesh approximate convex decomposition? I'm trying to understand the logic behind Mamou and Ghorbel's algorithm in their paper A Simple And Efficient Approach For 3D Mesh Approximate Convex Decomposition. I cannot understand what is the aspect ratio of a surface as defined by the author. It includes the perimeter of two vertices v and w. These two vertices represent two triangles in the original mesh as they come from the dual graph as the authors define it. So I'm guessing they are talking about the perimeter of the two triangles these vertices correspond to. What is the perimeter of two triangles? Do they mean the sum? The algorithm proceeds like this Create a dual graph of the mesh, where each vertex corresponds to a triangle of the original mesh, and two vertices are connected by an edge iff their corresponding triangles share an edge. Iteratively choose and collapse an edge, so that two vertices are merged into one. We keep track of the \"ancestors\" of each vertex, A(v) that have been merged into it in this way. Here's where I get confused The decimation process described in the previous section is guided by a cost function describing the concavity and the aspect ratio 5 of the surface S(v, w) resulting from the unification of the vertices v and w and their ancestors S(v, w) A(v) A(w) w, v . (2) As in 5 , we define the aspect ratio E shape (v, w) of the surface S(v, w) as follows E shape (v, w) frac 2(S(v, w)) 4 (S(v, w)) , (3) where (S(v, w)) and (S(v, w)) are respectively the perimeter and the area of S(v, w) ."} {"_id": 48, "text": "Simulate dirt spread (Normal distribution?) This question is technically more math related, but it has to do with a simulation so I am here first. I can post this in the math SE instead if needed. I am in the process of trying out some mesh deformation simulating the effect of sand dirt being poured in a pile (Think hourglass sand) and I am trying to determine the best way to calculate the spread instead of becoming increasingly taller. I don't intend on actually matching sand dirt physics, I just want to get my mesh to be somewhat close to the shape that pile would make as it grows. I'm pretty sure that Normal Distribution is what I want, so in my desmos graph below, think of f(x) green line as the current dirt sand piling up (where I am at in my code) and f1(x) purple line as the spread version (what I want to happen instead). f1(x) is not correct but I think it is pretty close. Essentially i need the area of f1(x) to always equal the area of f(x) but as f(x) gets taller, f1(x) gets wider and taller, but not as tall as f(x). https www.desmos.com calculator ir8if2u8qq lt a title \"View with the Desmos Graphing Calculator\" href \"https www.desmos.com calculator ir8if2u8qq\" gt lt img src \"https s3.amazonaws.com calc thumbs production ir8if2u8qq.png\" width \"200px\" height \"200px\" style \"border 1px solid ccc border radius 5px\" gt lt a gt I hope this makes sense to you gurus. If not, I can try to clarify more. Edit Also, if you open that graph, the slider for variable 'h' is the one im essentially trying to work with."} {"_id": 48, "text": "Swapping limbs between meshes I'm trying to achieve what was done in the game impossible creatures. I will have a skeleton to which I will apply different meshes to i.e. torso mesh, leg mesh, etc. I would also like these meshes to be skinned together at the joints so that it looks like an animal and not like a robot. Any ideas as to how I go about achieving this?"} {"_id": 48, "text": "How do I import real world models into a game engine? What are the hardware and software tools required to import physical worlds into a game engine? Can I use a HD camera to do that? What do the popular game engines support?"} {"_id": 48, "text": "How to fix a crowbar mesh deformation problem I am having a problem exporting my model to Garry's Mod. Every time i compile the model in crowbar it comes out deformed like this when the model is really suppose to look like this how do I fix this is there something wrong with the collision? I am also ready to provide whatever files information are needed to solve this problem. I should also mention that the mesh has multiple objects from each sphere that are joined but not connected. I went to the arqade for this at first but they said it was offtopic and that I should come here instead."} {"_id": 48, "text": "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. To find the normal, I'm using the normalized vector from the nearest point on the mesh to the center of the sphere. Now 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. In 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). Now, 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. The 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?"} {"_id": 48, "text": "Generate Mesh of Shadow Volume Given a mesh, I want to generate another mesh that is effectively a shadow volume of this mesh. I am looking for an algorithm solution implementation reference that can do this under the following constraints I have a single, point light source. Thus Not a polygon I want hard edges faces (not soft shadows) The light source is at infinity, in fact can be assumed to by directly above the mesh. Thus The projection is actually orthographic and depends only on a single direction. I want an exact solution. The result mesh is not used for display so cannot be based on resolution dependent rasterization as many algorithms are. A naive algorithm is to extrude all mesh triangles in the direction away from the light, e.g. downward, and do a CSG union of all these extruded \"prisms\". The drawback here is that It does this for all triangles and not just the visible ones (how to do exact visibility?) it requires a massive amount of CSG operations which are expensive. I'm looking for a more efficient algorithm."} {"_id": 48, "text": "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. To find the normal, I'm using the normalized vector from the nearest point on the mesh to the center of the sphere. Now 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. In 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). Now, 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. The 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?"} {"_id": 48, "text": "How to quickly create meshes that have cutouts of other meshes? I have a mesh and I would like to quickly create planes (or boxes) that have cutouts in the shape of the silhouette that mesh, but rotated at various angles. I would like to have a system to which I can feed any mesh and it will output these cutout planes, either for random or predefined rotations of the mesh. In the game I'm making, you have a 3D object, like a chess piece, that you rotate and translate to try to fit it in a hole in a wall that has the shape of the object. But the hole can be in the shape of any rotation of that object. For instance, in the case of a pawn, the hole can look like an upright pawn, so you wouldn't have to rotate the pawn at all or it could just be a circle the size of the base of the piece, so you would have to rotate the pawn so it either goes in feet or head first. I want a program to procedurally generate walls with these kinds of holes for any mesh I give it."} {"_id": 48, "text": "matrix to transform unit cube to space defined by 8 arbitrary points I asked a question relating to similar to this already, but I think this is a clearer objective of what Im trying to achieve.. or whether its possible at all! Im trying to find a transformation (matrix ideally) which would transform the 8 points of a 3d unit cube to 8 arbitrary points in space. The 8 target points have no known structure. e.g My gut feeling is that a matrix is unable to provide this xform since the cube faces vertices can be concave.. but are there any other methods of transformation? Thanks!"} {"_id": 48, "text": "Simulate dirt spread (Normal distribution?) This question is technically more math related, but it has to do with a simulation so I am here first. I can post this in the math SE instead if needed. I am in the process of trying out some mesh deformation simulating the effect of sand dirt being poured in a pile (Think hourglass sand) and I am trying to determine the best way to calculate the spread instead of becoming increasingly taller. I don't intend on actually matching sand dirt physics, I just want to get my mesh to be somewhat close to the shape that pile would make as it grows. I'm pretty sure that Normal Distribution is what I want, so in my desmos graph below, think of f(x) green line as the current dirt sand piling up (where I am at in my code) and f1(x) purple line as the spread version (what I want to happen instead). f1(x) is not correct but I think it is pretty close. Essentially i need the area of f1(x) to always equal the area of f(x) but as f(x) gets taller, f1(x) gets wider and taller, but not as tall as f(x). https www.desmos.com calculator ir8if2u8qq lt a title \"View with the Desmos Graphing Calculator\" href \"https www.desmos.com calculator ir8if2u8qq\" gt lt img src \"https s3.amazonaws.com calc thumbs production ir8if2u8qq.png\" width \"200px\" height \"200px\" style \"border 1px solid ccc border radius 5px\" gt lt a gt I hope this makes sense to you gurus. If not, I can try to clarify more. Edit Also, if you open that graph, the slider for variable 'h' is the one im essentially trying to work with."} {"_id": 48, "text": "How can I select and scale an edge loop within Blender? I'm a web developer looking into game development as a hobby for fun and the challenge. I have just started learning blender 2.6. I am currently doing a tutorial at http cgcookie.com blender 2010 12 22 modeling a building at around 9 30 after making loop cuts he scales a column. I cant get the same selection as he did. he has vertices selected but selected the whole loop cut? can someone tell me how to make that selection he did. Also what setting does he use to display the dimension numbers of his selections?"} {"_id": 48, "text": "Swap limbs of a skinned mesh If I have a model, such as a robot, I am able to swap its limb meshes out and replace them with other robot limb meshes by merely removing the limb mesh from the skeleton and attaching the new one to the appropriate bone. Now I want to essentially do the same thing but with a skinned mesh, say a human monster character. For example I want to swap a normal human arm for some bad ass demon arm. How do I go about doing this as I believe I need to take into account skin bone weights etc. Didn't Spore do something similar? Although my skeleton would be predefined as opposed to the ones created in Spore."} {"_id": 48, "text": "Angle between two planes I have two triangles in 3d space which share 1 edge and I would like to determine if the angle between their normal vectors is \"uphill\" or \"downhill\". In other words, if you set one flat, would the angle between them be acute (uphill) or obtuse (downhill). Hopefully that makes sense. So far I have the normal vectors of each triangle and have calculated the angle between the two triangles, however this angle is always 90 degrees. Vector3 v1 triangle1.Normal Vector3 v2 triangle2.Normal float cosAngle Vector3.Dot(v1, v2) (v1.magnitude v2.magnitude) float degAngle Mathf.Acos(cosAngle) Mathf.Rad2Deg Is there a trick I am missing that lets me determine which direction this angle is in?"} {"_id": 48, "text": "Creating a basic character skeleton from code I'd like to have a procedural system that uses a string of data to create a 3d creature. The way I've thought to do this is to use the code to generate a simple creature skeleton (I'll get to the skin generation when I have time) so I can test different source data's effect on the structure produced. How can i use a set of data to generate the simple 3d skeleton? The code would have information used to show what type of bone it was(hierarchy), the bone length, and how the bone was positioned and use this to make the model. (At least in planning, I don't know how to implement it) Edit The goal is to create creatures of different forms and skeletons. The creation will be mirrored down the spine so both sides are the same. I'd like it to be highly adaptable but I'd like to specify a max of 4 legs and 4 arms (8 limb max only 4 on ground for walking). Being able to create a basic structure for humanoids, quadrupeds, and mixes (like a centaur or biped with no arms) is the goal. I've looked for how to create a model off of the code procedurally, looking at stuff like FRep isosurfaces and metaballs, but I'm stumped on how to make it happen. I decided any progress is better that none, so I'd like to get a generator for something like an animators skeleton example to make sure I can get working structures (and later have something to work with to begin working on the animation algorithm). Sorry for the lack of information at first, I was trying to keep the question simple. If you have an idea for the creation of the structure(skeleton) or maybe even the form itself I'd appreciate the help. Thanks"} {"_id": 48, "text": "Generate Mesh of Shadow Volume Given a mesh, I want to generate another mesh that is effectively a shadow volume of this mesh. I am looking for an algorithm solution implementation reference that can do this under the following constraints I have a single, point light source. Thus Not a polygon I want hard edges faces (not soft shadows) The light source is at infinity, in fact can be assumed to by directly above the mesh. Thus The projection is actually orthographic and depends only on a single direction. I want an exact solution. The result mesh is not used for display so cannot be based on resolution dependent rasterization as many algorithms are. A naive algorithm is to extrude all mesh triangles in the direction away from the light, e.g. downward, and do a CSG union of all these extruded \"prisms\". The drawback here is that It does this for all triangles and not just the visible ones (how to do exact visibility?) it requires a massive amount of CSG operations which are expensive. I'm looking for a more efficient algorithm."} {"_id": 48, "text": "3D meshes for WPF (XAML)? I'm trying to make a WPF 3D game. WPF uses XAML. I'm trying to find free 3D assets from the internet. ) What format of 3D models I should be looking for, direct XAML or 3D Studio format or what? I know that there are some 3D Studio format to XAML converters, but I don't know if they really work..."} {"_id": 48, "text": "MD5Mesh Calculate Vertex Normals I am writing an MD5 3D model loader to display animated models. The vertices and texcoords load in correctly, but the lighting is supposed to be smooth. I calculate per vertex normals by looping through all triangles, finding the triangle normal, and then adding that to each of the triangle's vertices' normal (follow?). Then, I normalize all the normals. This should work, but md5 declares each vertex with a texcoord, meaning that if I have a single vertex that has different texcoords for each of the faces it's attached to, it declares multiple vertices at the same position. Each of these will end up with its own normal, resulting in flat shading. Should I somehow merge duplicate vertices, or export the model differently, or do something fancy that I haven't thought of? Thanks!"} {"_id": 48, "text": "How to generate AABB, OBB Sphere from polygon soup How can I generate AABB, OOBB and Sphere from a polygon soup, where the bounding volumes are defined as follows AABB should be specified by min(x,y,z) max(x,y,z) OOBB should be specified by min(x,y,z) max(x,y,z) and a quaternion for rotation Sphere is specified as position(x,y,z) and radius"} {"_id": 48, "text": "What are perimeter and aspect ratio, in the context of 3D mesh approximate convex decomposition? I'm trying to understand the logic behind Mamou and Ghorbel's algorithm in their paper A Simple And Efficient Approach For 3D Mesh Approximate Convex Decomposition. I cannot understand what is the aspect ratio of a surface as defined by the author. It includes the perimeter of two vertices v and w. These two vertices represent two triangles in the original mesh as they come from the dual graph as the authors define it. So I'm guessing they are talking about the perimeter of the two triangles these vertices correspond to. What is the perimeter of two triangles? Do they mean the sum? The algorithm proceeds like this Create a dual graph of the mesh, where each vertex corresponds to a triangle of the original mesh, and two vertices are connected by an edge iff their corresponding triangles share an edge. Iteratively choose and collapse an edge, so that two vertices are merged into one. We keep track of the \"ancestors\" of each vertex, A(v) that have been merged into it in this way. Here's where I get confused The decimation process described in the previous section is guided by a cost function describing the concavity and the aspect ratio 5 of the surface S(v, w) resulting from the unification of the vertices v and w and their ancestors S(v, w) A(v) A(w) w, v . (2) As in 5 , we define the aspect ratio E shape (v, w) of the surface S(v, w) as follows E shape (v, w) frac 2(S(v, w)) 4 (S(v, w)) , (3) where (S(v, w)) and (S(v, w)) are respectively the perimeter and the area of S(v, w) ."} {"_id": 48, "text": "Vertex Normals, Loading Mesh Data My test FBX mesh is a cube. From what I surmise, it seems that the cube is on the extreme end of this issue, but I believe that the same issue would be able to occur in any mesh Each vertex has 3 normals, each pointing a different direction. Of course loading in any type of mesh, potentially ones having thousands of vertices, I need to use indices and not duplicate shared verts. Currently, I'm just writing the normals to the vertex at the index that the FBX data tells me they go to, which has the effect of overwriting any previous normal data. But for lighting calculations I need more info, something that's equivalent to a normal per face, but I have no idea how this should be done. Do I average the 3 different verts' normals together or what?"} {"_id": 48, "text": "MeshParts Why do they exist? For my current game I'm working on I've decided to implement a custom model class to store my models in. Reasons being is that I want to make adding new models as painless as possible for the rest of the team without needing to go through the XNA Monogame content pipeline (Them having VS Dev framework installed just to compile a few models, or passing them onto me to compile every time a change is made would just get tedious further on, not to mention different timezones when testing slowing things down) To this end I've been looking at the model structure of different frameworks, XNA Monogame, SharpDX and AssImp.NET being the main ones. The structure for XNA MG and SharpDX is Model MeshCollection MeshPartCollection, whereas Assimp only has Scene MeshCollection. From previous experience in XNA, MeshParts seem kinda redundant. None of my meshes ever had more than one, and a lot of the XNA examples I've seen only ever had one mesh part per mesh. From everything I've experienced and seen, MeshParts seem redundant, surplus to requirements and just makes for an extra level of complexity (Should I use a loop, or just hardcode it to use the first element in the collection?). Is there some useful aspect of them that I am not aware of, or a particular use case or scenario where they are actually useful?"} {"_id": 48, "text": "How do I implement real time mesh deformation, with regards to environmental damage? I would like to be able to add the following feature to my tech demo at the moment bullets hit the walls, little pieces fly out of them, as well as decals appearing on the walls. Computing power is good enough, now, so that many games have destructible environments. I would like bullets to shatter small surface segments off the wall, ideally the segments that fly off would directly relate to the hole that is left, though I don't even know if this is how it's done in commercial games. How is this done? Are there simply a number of different meshes that are swapped out as, and when, objects are hit? I assumed that this would not be an accurate enough solution. Is real time mesh deformation feasible. and if so, how is it done?"} {"_id": 48, "text": "Point welding on generated terrain I am converting two 2D images (A Voronoi graph and a Diamond Square noise map) into a 3D object. However when finding the corner points of the Voronoi I am left with gaps, so I thought to drop these by calculating adjacency to existing nodes before creating the vertex. However no matter which algorithm for the weld I use, or the tolerance level of the distance I can't seem to get it to work. This has led me to believe I am doing something wrong. Image of the issue These gaps do not appear if I run without the weld, they are created by the weld jumping to spots, but then later welds not finding that spot. I have even tried to increment the weld distance to a maximum of 10, if a suitable node wasn't found. But this is far to aggressive and has the effect of simplifying the mesh instead and creating more gaps. My Repo for the full code is here https github.com HughAJWood TerrainGenerator private void CalculatePolys() var nodesForEdges new List lt VNode gt () foreach (var region in regions) foreach (var point in region) if (point null) continue We calculate where the voronoi node corners are, and pass them into the region var diff ColoursDifferent(point) if (diff gt 1) RenderNodePointsOnImage(point) Points are 2D, so to translate to 3D they are set to the Z property of the 3D node var node new VNode X point.X, Z point.Y Weld points within 1 unit from each other by determining if we already have one that exists then using the existing node instead A weld is calculated by determining the X,Z distance to see if we have a node stored already that is within 2 units of the node we are creating VNode existingNode Nodes.FirstOrDefault(n gt n.Adjacent(node)) if (existingNode null) Optimise node creation by skipping perlin lookup and ID iteration for only when needed node.ID VNodeId node.Y perlin.GetPixel(point.X, point.Y).R Nodes.Add(node) Mesh.ControlPoints.Add(new Vector4(node.X, node.Y, node.Z, 1)) else node existingNode nodesForEdges.Add(node) if (i gt 20) return AddNodesToMeshAsPolys(nodesForEdges) nodesForEdges.Clear() The adjacency method is currently simplified to the fact I want to ignore the height of the node. internal static bool Adjacent(this VNode a, VNode b, int tolerance 3) var distance Math.Abs(a.X b.X) Math.Abs(a.Z b.Z) return distance lt tolerance UPDATE I have tried sorting the points by distance and fuzzy distance, both sort in the correct order. Then I tried taking the first point and using that as the welding point. Same effect. I tried to average the points at the intersections at the image level and pass that back as the point every time, then weld. Same effect. Clearly there are many approaches I can take for this, the problem arises when there are 2 points close to each other on the edge of a voronoi region. Sometimes they weld and create a gap. Sometimes however in some variances of the algorithm that the points don't weld even though their X,Z coordinates are very close to each. I'm still stumped as how to approach this."} {"_id": 49, "text": "How to calculate the price for acquisition of a mobile game I searched long and hard thru the Game Dev community here and I didn't manage to find a good enough answer for a situation that I need help with. Here is the deal I've spent about a year to single handedly develop a mobile game which is a mix between MMORPG and idle battle games. Wouldn't like to go into too much depth as to which game we are talking about and who is trying to buy it but, a company I have worked for before reached out to me with a proposal to buy the game from me so they can reap the profit from it and develop it further since they are a professional game dev company while I am a single person and I can't really reach the game's full potential as far as growth and player base goes. Now the game is pretty beneficial for me since I live in a region with a very low income standard so the money I get from the game might not be much for many other people but for me, they are equal to about 1.5 2 monthly salaries (we are talking average salary for this country). That is about 600 Euros of pure profit after I pay for all the expenses. Of course, this number fluctuates depending on different events and sales I release and general user activity. It is a free to play game so the income is mostly from microtransactions for in game rare currency and special event item packs purchases. Now the issue I have is that I am not sure how to set a price for the acquisition. What feels right for me would be to calculate the potential average income from the game in the next 12 months and add to this the average salary per month for a game dev of my qualifications multiplied by the number of months it took me to develop it to its released state. That would round up to about 15k euros. When I think about it 15k euro isn't a small price to pay, but the game will pay that off in the next 1 2 years, and it might even grow much faster after they make investments for advertising and release new features and so on and so on. This means that after the second year they should be on a clean juicy profit from that deal, and that sounds good to me as well since 15k euros for me is a decent sum of money considering that the game has been running for about 14 months. And lets not forget that it has been beneficial for me for the last few months so it hasn't been always uphill. What I need really is an advice as to is this price of around 15k Euro justified and is it a good deal for both sides, since I don't want to shoot way high and blow the acquisition, but I don't want to give the game away for a low price since it really holds a lot of potential, and it is my first fully released game."} {"_id": 49, "text": "Novice Mobile Game Developers Publishing on our own or Publisher? So we are almost done with our first indie game, developed on Android. We believe that the game has potential, our graphics guy is damn good so we have some good eye candy in our game. Now we are thinking what should be our starting step? We can purchase the Google Play account and launch it on our own, but we aren't sure if we'd be able to advertise it well and get something big out of it. Or we can contact a publisher, and talk about some deal. Which one is better? What are the pros and cons of both, considering this is only our first game and we intend to make a lot more. Also considering that we're only students yet, currently in our senior year. We would love to generate some revenue out of it. What are the best ways of contacting publishers? How do we approach them and deal with them? Many thanks for your kind help!"} {"_id": 49, "text": "Keep game name after complete rebuild, engine migration and change from 2D to 3D? I have published an Alpha version of a game with XNA in 2D, but I am now learning Unreal with full intention of porting the game to 3D there. I expect that in 3 months time, or less with a little luck, I will have a comparable version of the game in 3D, but I am already really close to the point where I can release some early footage. With this in mind, I am also beginning to think about the game's promotion, its IndieDB page has it listed as a 2D XNA game, but there's two considerations a) Should I change the engine, given that earlier images and uploads are still there and I haven't got a release to replace them with? b) Should I keep the name, considering that, 1) it is associated with the 2D game, and 2) search results bring up Fallout content, and the abbreviation SW is already fully associated with Star Wars? I am, in the meantime, going to try to contact IndieDB and see if I am even allowed to change the game's listing (in terms of game engine and type) and will edit the post when I have an answer."} {"_id": 49, "text": "Advertising before seeking a publisher I'm nearing competition of my first title and I'd like to seek out publishers but I'm also eager to show it off on social media. Should I hold off until I've spoken to publishers or is it mostly harmless?"} {"_id": 49, "text": "Whats the best way to publish and promote an app by myself? My first little casual action android game is nearly finished. Its my first one and i dont expect any sucess. But nevertheless i want to try to publish and market it by myself. But what can i do without any bugdet? How do i attract and reach people ? Are there any tricks ? How did you published and promoted your first app game ? And what is your experience with self publishing marketing ?"} {"_id": 49, "text": "Where to find market research info on adventure games? Looks like adventure games are on the rise again. There were several great releases in 2012, including brilliant and highly acclaimed Walking Dead from TellTale. Is there a market research that proves the new rise of adventure games? Bonus points for revenue estimates and such. I'm particularly interested in mobile games segment, but everything else is of interest as well."} {"_id": 49, "text": "Where can I advertise my engine, library or framework to attract users? I have just finished my hypothetical game engine, library or framework. Now, I want to share it with people who may find it useful in their projects. Where can I advertise it to gain users? By advertise, I mean to spread the word of its existence not advertise it for money."} {"_id": 49, "text": "How can I get multiple players play my multiplayer game at launch? Lets take a example of Apex Legends, it was release in February 4, 2019 and got 25 millions users in after a week (Source The Verge). I know EA is the publisher so its easy for them to market and have huge user base but what if Im new in the industry and have been funded or invested to make huge game like that but could not get million of user in such short period of time? How could I achieve something like this? How can I get a lot of players to play my game when I launch it? I thought of adding AI bots to keep the real players in until my player mass is good enough, but is that just it? Are there other options?"} {"_id": 49, "text": "How can I get into the educational market? I believe that my current game project is very well suited for educational gaming so well suited, in fact, that I know of several different schools (one community college and at least one or two high schools) that have used versions of it at some time or another. And that's without any such marketing on my part. I'd like to expand on this part of the potential user base. But I have absolutely no experience in dealing with school administrations. How can I break into this market enough to be noticed? And on a side note, could marketing the game as educational kill the gamers market?"} {"_id": 49, "text": "What distinguishes a free to play game from one worth paying for? There's a heck of a lot of free games available out there, some of which are as good as games that you have to pay for. My question is, what makes the difference between a game that people will be willing to pay for, and one which is best left as a free to download play online game subsidised with advertising?"} {"_id": 49, "text": "What are the pros and cons to building an audience with a small, simple, free game first as opposed to focusing efforts on a commercial release There are two projects we can work on. One would be a small free game to try and get our name out build an audience. The second is our main idea for a first product. What are the pros and cons of building the small, simple, free game first instead of focusing that time effort into the main money making project."} {"_id": 49, "text": "How do you market assets that are niche but that those people definitely want? I just got done canvasing surveying developers, and it is clear that there is a market for a few niche categories of audio assets that I suspected would be useful to them. While the overall category of assets is commonly desired, it can only be broken down into separate categories, which individually are completely niche due to the wide variety of games nowadays. How can a niche but useful asset be effectively marketed to (mostly indie) game developers? It is known that there are people out there who want it, but the likelihood of a completely random individual wanting it is low. So if the asset was created, and there was low competition among asset producers for it, how could one ensure at least some of those people find it (without actually cold calling them)? I would explain in more detail, but I don't want to come off as though I'm trying to advertise anything here."} {"_id": 49, "text": "Getting Early User Feedback on Games Disclaimer It may be that I'm already doing all the \"right\" things, but just don't have enough traffic for it to pay off with people giving feedback. My question is how do you attract early and quality feedback into games, from end users? Ideally, I'm looking at a model where the seed of an idea comes from you (or from them, even) and you build it into a game, molding it along the lines that people tell you are best. Because you're just one opinion. And game developers have a reputation for doing weird and sub par quality stuff, sometimes. I'm currently practicing the following VIP List I have a \"VIP\" mailing list (mostly friends) who agreed to try out game releases and give me feedback. They seem hesitant to say anything negative, and most of them are not really gamers, just doing it because they know me and like my niche. 2 4 Week Releases I use a form of agile and release iterations every two to four weeks. This means every release is functionally small, but somewhat polished. Press Releases With every release, I also post a small \"press release\" post identifying the good, the bad, what's next, and screenshots (along with a link to play the latest release version). I'm not getting that much feedback. What am I missing?"} {"_id": 49, "text": "Best free advertising for Facebook strategy game I have written a game for Facebook. I think the game is fun to play, although the graphic presentation is primitive since I am not a graphic artist web designer I am the only Facebook user playing the game at this time. It does not appear to appeal to FB's demographic audience who seem to prefer less complex and less challenging games. Does anyone have any ideas on how I could get the word out about my game to the proper audience while spending very little or no money?"} {"_id": 49, "text": "Keep game name after complete rebuild, engine migration and change from 2D to 3D? I have published an Alpha version of a game with XNA in 2D, but I am now learning Unreal with full intention of porting the game to 3D there. I expect that in 3 months time, or less with a little luck, I will have a comparable version of the game in 3D, but I am already really close to the point where I can release some early footage. With this in mind, I am also beginning to think about the game's promotion, its IndieDB page has it listed as a 2D XNA game, but there's two considerations a) Should I change the engine, given that earlier images and uploads are still there and I haven't got a release to replace them with? b) Should I keep the name, considering that, 1) it is associated with the 2D game, and 2) search results bring up Fallout content, and the abbreviation SW is already fully associated with Star Wars? I am, in the meantime, going to try to contact IndieDB and see if I am even allowed to change the game's listing (in terms of game engine and type) and will edit the post when I have an answer."} {"_id": 49, "text": "How should I prepare for pitching a game to potential sponsors? We have developed a mobile game, and are preparing ourselves for demo day. We will be presenting our game to potential sponsors, and we are having trouble deciding how to make a quality presentation. Specifically, what are the unique challenges and opportunities in pitching a game, in contrast with product demos generally? Being developers, we are worried we might wrongly focus on elements important to developers, but not to investors. How can we go about identifying them? For demoing game play, in what situation should we consider switching to a separate app, embedding the game in a slide show, showing canned game footage, or something else?"} {"_id": 49, "text": "Novice Mobile Game Developers Publishing on our own or Publisher? So we are almost done with our first indie game, developed on Android. We believe that the game has potential, our graphics guy is damn good so we have some good eye candy in our game. Now we are thinking what should be our starting step? We can purchase the Google Play account and launch it on our own, but we aren't sure if we'd be able to advertise it well and get something big out of it. Or we can contact a publisher, and talk about some deal. Which one is better? What are the pros and cons of both, considering this is only our first game and we intend to make a lot more. Also considering that we're only students yet, currently in our senior year. We would love to generate some revenue out of it. What are the best ways of contacting publishers? How do we approach them and deal with them? Many thanks for your kind help!"} {"_id": 49, "text": "How important is a character's sexuality when it come to audience appeal I ask because I came across this comment about putting gay characters in games The necessity of exposing the larger playerbase to the homosexual tendencies of two of its cast mates is never really expounded upon by ScreenRant. That s not to mention that only a tiny percentage of people even identify as on the LGBTQ spectrum, even according to Gallup, which puts the national average at 4.5 . So why exactly would Blizzard force the majority of their straight players to have to engage with the homosexual tendencies of two of its non straight characters? (Source) And here So what better way to get back at the core gamers who dropped one liners and zingers that have become memes of legend, than to strip away from gamers the last remaining normal character in Overwatch? Most people figured Soldier 76 would be safe. He s a patriotic military man, a hard fighting soldier with undying loyalty, and a code of honor. He s the perfect representation for what the majority of gamers like to see out of a hero. And besides, you need at least one normal sized, healthy, properly muscled straight, white male with all of his limbs intact to cater to the majority of your playerbase. Right? RIGHT?! The average male gamer typically gravitates toward a game where there s a character who looks like he can kick butt and take names, and Soldier 76 was that guy. .... The last bastion for masculinity in a game that s constantly bleeding testosterone faster than the Overwatch League bleeds viewership, (Source) It's obvious that this guy thought that 76 was straight before this. So his outrage that his face character was revealed to be gay when there was no evidence to say otherwise beforehand is pretty sad. Beyond this there is a point he makes that is interesting. Is a characters sexuality really that important? Yes most gamers are straight, but does that automatically mean that every game character needs to be straight? Or is this an appeal to the majority fallacy?"} {"_id": 49, "text": "Best free advertising for Facebook strategy game I have written a game for Facebook. I think the game is fun to play, although the graphic presentation is primitive since I am not a graphic artist web designer I am the only Facebook user playing the game at this time. It does not appear to appeal to FB's demographic audience who seem to prefer less complex and less challenging games. Does anyone have any ideas on how I could get the word out about my game to the proper audience while spending very little or no money?"} {"_id": 49, "text": "Market as a single game or as a studio? I'm creating an RPG with a theme of a hero that must restore peace to a world fallen to evil forces. It serves as an educational tool. I'm creating a promotional website for it and using other online social tools for marketing. I only have one focus to make this game as great as possible for people to learn. I've seen some companies that market themselves as their product name, like DuoLingo, and some that market as the studio, such as Strawberry Games. I don't have a game studio and have simply been marketing (FB page, website URL, etc) as the game's name, Lexicana's Destiny. Does it really matter which way I market it? If so, why?"} {"_id": 49, "text": "Where to promote your indie game? Possible Duplicate Where to advertise my game? Let's say I have developed a game and I want to \"get it out there\". What I have in mind is open source, non commercial games. What websites do you know of where you can promote your newly developed game, rather than simply posting it on your blog?"} {"_id": 49, "text": "When should I publish my Steam page? I developing my game, which still in alpha, and plan to sell it via Steam. I already applied to Steam partnership program and want to publish my 'coming soon' Steam page to start gather wishlists, but it on hold for now. I don't have any promotional material yet, but people on social media positively reacting to gifs of my game. Is it good idea to publish Steam page right now with temporary thumbnail and screenshots of current version and then change everything later? Or should I make my page appealing first?"} {"_id": 49, "text": "Novice Mobile Game Developers Publishing on our own or Publisher? So we are almost done with our first indie game, developed on Android. We believe that the game has potential, our graphics guy is damn good so we have some good eye candy in our game. Now we are thinking what should be our starting step? We can purchase the Google Play account and launch it on our own, but we aren't sure if we'd be able to advertise it well and get something big out of it. Or we can contact a publisher, and talk about some deal. Which one is better? What are the pros and cons of both, considering this is only our first game and we intend to make a lot more. Also considering that we're only students yet, currently in our senior year. We would love to generate some revenue out of it. What are the best ways of contacting publishers? How do we approach them and deal with them? Many thanks for your kind help!"} {"_id": 49, "text": "Where can I advertise my engine, library or framework to attract users? I have just finished my hypothetical game engine, library or framework. Now, I want to share it with people who may find it useful in their projects. Where can I advertise it to gain users? By advertise, I mean to spread the word of its existence not advertise it for money."} {"_id": 49, "text": "When should I publish my Steam page? I developing my game, which still in alpha, and plan to sell it via Steam. I already applied to Steam partnership program and want to publish my 'coming soon' Steam page to start gather wishlists, but it on hold for now. I don't have any promotional material yet, but people on social media positively reacting to gifs of my game. Is it good idea to publish Steam page right now with temporary thumbnail and screenshots of current version and then change everything later? Or should I make my page appealing first?"} {"_id": 49, "text": "How important is a character's sexuality when it come to audience appeal I ask because I came across this comment about putting gay characters in games The necessity of exposing the larger playerbase to the homosexual tendencies of two of its cast mates is never really expounded upon by ScreenRant. That s not to mention that only a tiny percentage of people even identify as on the LGBTQ spectrum, even according to Gallup, which puts the national average at 4.5 . So why exactly would Blizzard force the majority of their straight players to have to engage with the homosexual tendencies of two of its non straight characters? (Source) And here So what better way to get back at the core gamers who dropped one liners and zingers that have become memes of legend, than to strip away from gamers the last remaining normal character in Overwatch? Most people figured Soldier 76 would be safe. He s a patriotic military man, a hard fighting soldier with undying loyalty, and a code of honor. He s the perfect representation for what the majority of gamers like to see out of a hero. And besides, you need at least one normal sized, healthy, properly muscled straight, white male with all of his limbs intact to cater to the majority of your playerbase. Right? RIGHT?! The average male gamer typically gravitates toward a game where there s a character who looks like he can kick butt and take names, and Soldier 76 was that guy. .... The last bastion for masculinity in a game that s constantly bleeding testosterone faster than the Overwatch League bleeds viewership, (Source) It's obvious that this guy thought that 76 was straight before this. So his outrage that his face character was revealed to be gay when there was no evidence to say otherwise beforehand is pretty sad. Beyond this there is a point he makes that is interesting. Is a characters sexuality really that important? Yes most gamers are straight, but does that automatically mean that every game character needs to be straight? Or is this an appeal to the majority fallacy?"} {"_id": 49, "text": "Is a game's world wide visibility in app stores affected by the publisher's country of residence? I've noticed on Apple Store (and I assume on Google Playstore too) I find different games and apps in France than in the US. Does this mean if my company resides in a small country and I register my game in this country, it'll only be shown to users of my country? Or is it just a matter of some settings and I can decide to be shown all around the world, for instance for American users (which is a larger market than my country), same as game producers living there? Does a game developer's country of residence influence how many downloads world wide he can reach at all? My question is about Apple Store and Google Playstore, but answers for other platforms are welcome too."} {"_id": 49, "text": "Where to find market research info on adventure games? Looks like adventure games are on the rise again. There were several great releases in 2012, including brilliant and highly acclaimed Walking Dead from TellTale. Is there a market research that proves the new rise of adventure games? Bonus points for revenue estimates and such. I'm particularly interested in mobile games segment, but everything else is of interest as well."} {"_id": 49, "text": "What do I risk if I name my game the same as another company? I came up with the best title for my game a title that is catchy and also indicative of the gameplay, plus there isn't any other game on the market with a similar name. But after a Google search, I found a company in another country using the same name. To put my situation better in context, imagine a game like Minecraft being in development, only to find out that there's another company called something like Minecraft Studios in a far off country dealing with digital graphics and art for media (including games). Aside from the legal aspect of it (lawsuits, cease and desists, etc.), what disadvantages would there be to have my game named the same as a company dealing in a similar field?"} {"_id": 49, "text": "Money in different platforms So first of all, let me start off by saying that I am not in this to make money as of right now. I'm a novice however I would like (in the frture) to be able to earn some extra cash on the side with my games. I have several ideas for what my first game could be and then I started considering the platform on which my game should run. So I started thinking iOS amp Android mobile devices already have a built in store that everyone uses. This means that even if my game doesn't get a lot of attention (and doesn't reach the highest position on the market) everyone would still be able to find my game on the same platform. How is this possible with games made for web or even desktop? Are the chances of making money of web and desktop as big as on the mobile market?"} {"_id": 49, "text": "Do I have to ask for permission to use real company logos for advertising props in the world in my sports game? I'm making a simple turn based Android ball flicking soccer game and I was thinking of creating a theme in a sports game, like soccer for example, usually had advertisement banner on walls and a bit realistic but cartoony. It is usually encountered in most sports based game in any gaming platform. I have a question regarding this topic. Is it required to ask a permission to used some recognized ad banner designed walls (e.g. Adidas, Samsung, McDonalds, etc.) to be used as props for the game field like this one for example?"} {"_id": 49, "text": "How can I record my vector graphics game without blurring the graphics? A lot of people asked for a trailer for my game, because screenshots do not do it justice. I have tested PlayClaw, Fraps, CamStudio, VirtualDub, and some other minor tools none have produced a viable result. My game uses vector graphics and is designed to run at 60fps, so lossy compression of a regular screen capture video destroys the graphical appeal. How can I record gameplay without blurring my graphics and slowing down the framerate?"} {"_id": 49, "text": "How important is a character's sexuality when it come to audience appeal I ask because I came across this comment about putting gay characters in games The necessity of exposing the larger playerbase to the homosexual tendencies of two of its cast mates is never really expounded upon by ScreenRant. That s not to mention that only a tiny percentage of people even identify as on the LGBTQ spectrum, even according to Gallup, which puts the national average at 4.5 . So why exactly would Blizzard force the majority of their straight players to have to engage with the homosexual tendencies of two of its non straight characters? (Source) And here So what better way to get back at the core gamers who dropped one liners and zingers that have become memes of legend, than to strip away from gamers the last remaining normal character in Overwatch? Most people figured Soldier 76 would be safe. He s a patriotic military man, a hard fighting soldier with undying loyalty, and a code of honor. He s the perfect representation for what the majority of gamers like to see out of a hero. And besides, you need at least one normal sized, healthy, properly muscled straight, white male with all of his limbs intact to cater to the majority of your playerbase. Right? RIGHT?! The average male gamer typically gravitates toward a game where there s a character who looks like he can kick butt and take names, and Soldier 76 was that guy. .... The last bastion for masculinity in a game that s constantly bleeding testosterone faster than the Overwatch League bleeds viewership, (Source) It's obvious that this guy thought that 76 was straight before this. So his outrage that his face character was revealed to be gay when there was no evidence to say otherwise beforehand is pretty sad. Beyond this there is a point he makes that is interesting. Is a characters sexuality really that important? Yes most gamers are straight, but does that automatically mean that every game character needs to be straight? Or is this an appeal to the majority fallacy?"} {"_id": 49, "text": "Which is better More puzzle apps in Store or more puzzle levels in a single app The Question Given a freemium model (ad supported with in app purchase of additional levels hints)... are chances of overall success better with a single puzzle app with lots (but varied) levels playing styles, OR... multiple apps, each app focused on a singular theme playing style? Scenario Our puzzle engine can support multiple types of puzzles based on the puzzle piece styles. While the game mechanics are roughly the same, changing the puzzle piece changes the visual aesthetic of the app and gameplay somewhat. The puzzle piece imparts a theme of sorts to the puzzle. Sorry for the lack of further specifics. I feel that multiple apps will allow us to market the different content more easily. I worry though that spreading the content over say, 4 different apps might limit the playing life of each individual app (the app content is mathematically limited). At which point you hope that cross promotion will guide your player to the additional app content. Are there any precedents here? I've assumed that with the freemium model having more apps in the pipeline is always a good thing. But having your 4 apps on a single player's device sounds challenging."} {"_id": 49, "text": "Why the shareware (not demo) model died? In the early days of the industry, instead of fighting piracy, companies let the users share their games freely, and put some nag screen or something like that on the game. Then they would sell DLC and expansions (yes, DLC is 20 years old actually P), hintbooks, cheat codes, swags, etc... Why this model died? Note I am talking about classic shareware, not the crippleware or demo crap."} {"_id": 49, "text": "Market as a single game or as a studio? I'm creating an RPG with a theme of a hero that must restore peace to a world fallen to evil forces. It serves as an educational tool. I'm creating a promotional website for it and using other online social tools for marketing. I only have one focus to make this game as great as possible for people to learn. I've seen some companies that market themselves as their product name, like DuoLingo, and some that market as the studio, such as Strawberry Games. I don't have a game studio and have simply been marketing (FB page, website URL, etc) as the game's name, Lexicana's Destiny. Does it really matter which way I market it? If so, why?"} {"_id": 49, "text": "How can I acquire marketing and sales data for games? I need to evaluate a marketing perspective for a videogame in order to predict its income, sold units, etc. Since this sounds like quite a bit of an impossible task, I thought I could collect some statistic for similar games in order to have an idea. Is there a way which I could figure out selling statistics about games on specific platform? For example collect statistic for game xyz available on Steam platform or game abc available on HumbleBundle. I think that could be a good practice to achieve this goal. EDIT recently was published SteamSpy, which offers a lot of statistics about games on Steam platform."} {"_id": 49, "text": "Money in different platforms So first of all, let me start off by saying that I am not in this to make money as of right now. I'm a novice however I would like (in the frture) to be able to earn some extra cash on the side with my games. I have several ideas for what my first game could be and then I started considering the platform on which my game should run. So I started thinking iOS amp Android mobile devices already have a built in store that everyone uses. This means that even if my game doesn't get a lot of attention (and doesn't reach the highest position on the market) everyone would still be able to find my game on the same platform. How is this possible with games made for web or even desktop? Are the chances of making money of web and desktop as big as on the mobile market?"} {"_id": 49, "text": "How was the world game market segmented in 2011? Is there a source (or perhaps several) presenting how was the world game market segmented in 2011 (or does anybody know themselves)? For example How many casual gamers there are? What is the total business, of which how much in virtual item sales? How many console gamers there are? How much is spent in hardware, how much in software? How many mobile gamers there are? How much is spent in hardware, how much in software? And how all above is in different regions countries?"} {"_id": 49, "text": "What do I risk if I name my game the same as another company? I came up with the best title for my game a title that is catchy and also indicative of the gameplay, plus there isn't any other game on the market with a similar name. But after a Google search, I found a company in another country using the same name. To put my situation better in context, imagine a game like Minecraft being in development, only to find out that there's another company called something like Minecraft Studios in a far off country dealing with digital graphics and art for media (including games). Aside from the legal aspect of it (lawsuits, cease and desists, etc.), what disadvantages would there be to have my game named the same as a company dealing in a similar field?"} {"_id": 49, "text": "How can I record my vector graphics game without blurring the graphics? A lot of people asked for a trailer for my game, because screenshots do not do it justice. I have tested PlayClaw, Fraps, CamStudio, VirtualDub, and some other minor tools none have produced a viable result. My game uses vector graphics and is designed to run at 60fps, so lossy compression of a regular screen capture video destroys the graphical appeal. How can I record gameplay without blurring my graphics and slowing down the framerate?"} {"_id": 49, "text": "What are the pros and cons to building an audience with a small, simple, free game first as opposed to focusing efforts on a commercial release There are two projects we can work on. One would be a small free game to try and get our name out build an audience. The second is our main idea for a first product. What are the pros and cons of building the small, simple, free game first instead of focusing that time effort into the main money making project."} {"_id": 49, "text": "Why the shareware (not demo) model died? In the early days of the industry, instead of fighting piracy, companies let the users share their games freely, and put some nag screen or something like that on the game. Then they would sell DLC and expansions (yes, DLC is 20 years old actually P), hintbooks, cheat codes, swags, etc... Why this model died? Note I am talking about classic shareware, not the crippleware or demo crap."} {"_id": 49, "text": "How can I get into the educational market? I believe that my current game project is very well suited for educational gaming so well suited, in fact, that I know of several different schools (one community college and at least one or two high schools) that have used versions of it at some time or another. And that's without any such marketing on my part. I'd like to expand on this part of the potential user base. But I have absolutely no experience in dealing with school administrations. How can I break into this market enough to be noticed? And on a side note, could marketing the game as educational kill the gamers market?"} {"_id": 49, "text": "Is a game's world wide visibility in app stores affected by the publisher's country of residence? I've noticed on Apple Store (and I assume on Google Playstore too) I find different games and apps in France than in the US. Does this mean if my company resides in a small country and I register my game in this country, it'll only be shown to users of my country? Or is it just a matter of some settings and I can decide to be shown all around the world, for instance for American users (which is a larger market than my country), same as game producers living there? Does a game developer's country of residence influence how many downloads world wide he can reach at all? My question is about Apple Store and Google Playstore, but answers for other platforms are welcome too."} {"_id": 49, "text": "How can I promote my game? I am a beginning indie developer, and I want to get the word out about my game. What sites can I go to to ask about reviews of my game, and where might I be able to talk about and get feedback on my game from players?"} {"_id": 49, "text": "Popular genres in Asian (non Japanese) markets? From time to time I've wondered what kind of games are popular in Asia (India, China, Korea, Singapore, etc...). I hear about developers in the US and UK who outsource work there, but what goes into the games they make for themselves? Related, you hear these days about how Japanese developers have been marketing their games more for American audiences these days (with mixed success). In what ways could American developers aim their development toward Asian audiences?"} {"_id": 49, "text": "Video recording and editing for game promo video I would like to screen record a beta of an RPG I've created. The format will be narration over video with the ability to edit. It's an indie game I'm marketing, so the video quality and narration need to be semi professional. I'm curious as to which video production packages are of good enough quality to accomplish this without breaking the bank (free is the best!). If there are no good packages, then separate software recommendations for screen recording, editing, and narration would be helpful! Notes I have a Mac I would rather do video recording first, then narration later with an overlay I've used Quicktime in the past, not sure if there was something better This video is for my Kickstarter campaign"} {"_id": 49, "text": "Marketing my mobile game I have almost finished my game I want to upload it to Google Play and the App Store. I will make it free but with Admob advertising. What is the best way to market my app (without any app promotion companies)? Please give me a detailed explanation."} {"_id": 49, "text": "Where to promote your indie game? Possible Duplicate Where to advertise my game? Let's say I have developed a game and I want to \"get it out there\". What I have in mind is open source, non commercial games. What websites do you know of where you can promote your newly developed game, rather than simply posting it on your blog?"}