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().


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.


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?


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


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?


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?


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.


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?


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?


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


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?


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)?


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?


Check Supported Platforms for Editor How can I find out from script(c ) did I download specific platfrom support for current Unity version?


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?


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


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


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)


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?


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


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


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().


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.


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?


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!


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?


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.


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.


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?


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()


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.


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?


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


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.


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!


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?


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()?


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.


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.


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.


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.


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.


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.


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?


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?


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


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.


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?


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?


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.


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...


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


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


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?


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?


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)


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


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?


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


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.


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)


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?


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?


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


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?


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?


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.


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.


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.


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.


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.


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?


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


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.


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.


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?


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?


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


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?


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!


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.


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?


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?


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?


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.


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.


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!


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.


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?


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.


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.


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.


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.