_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Understanding Screen Position Node in Unity Shader Graph I'm struggling to understand what exactly the Screen Position node outputs in Unity's Shader Graph. I'm using the screen position with scene depth to calculate the distance between two objects. Every tutorial I saw (like Brackey's forcefield one) is using the alpha channel of the Screen Position output I read that the Screen Position node outputs the mesh vertex screen positions. Does it means the 2D position on the screen projection? Or the vertex 3D position from the eye space? And more importantly, what is exactly the apha channel of this output? (I have the feeling this is related to the quot clip space W component quot in the documentation)
|
0 |
Unity Water shader vertex offset how to add mesh collider which updates with vertex offset? I have written a shader (in the new LWRP shader graph) which simulates an ocean with vertices which offset to create a moving "waves" effect. I believe that in order to have objects "float" on my moving waves, I shall need to create a mesh collider which is a trigger (please correct me if I'm wrong) which updates with the moving vertices of the mesh as per direction from the shader. How is such an effect possible? Am I taking the correct approach here? Please advise ) Many thanks in advance!! (the original model for the water is a plane which has been subdivided multiple times to provide suitable resolution for the vertices to be offset)
|
0 |
Can I develop a game for Kinect without a Kinect? I have to make a game in Unity3D using Kinect. The problem is I don't have the Kinect yet. I need to wait until they deliver it to me. Can I imitate Kinect's movement for debugging my app?
|
0 |
Wait for AudioClip finish before destroy Object If I Play the gun sound on my "bullet" object, how can I prevent the end of Audio sound if the bullet hit something so it destroy. To clarify Bullet prefab Audio Source Audio Clip MachineGun.mp3 PlayOnAwake true When I instantiate bullet, MachineGun AudioClip is played. But the bullet is fast and hit something before the clip is end. This Kill the machine audio effect making it irrealistic. How can I tell Unity "Play the sound to the end, despite the object is destroyed". I've tried Destroy(gameObject, AudioClip.length) But it seems not works
|
0 |
When is transform width in code not equal to the transform width in inspector? I've come across a strange case in Unity's UI where the width of a RectTransform isn't the same as what is being reported. I have a transform which is 50 by 50 with no scaling, it is a root object of the canvas yet when I use the information that I get from the transform in code to draw from the bottom left edge of the transform to the top right it doesn't reach all the way! Gizmos.color Color.red Vector2 pos new Vector2(transform.position.x, transform.position.y) Gizmos.DrawLine(pos transform.sizeDelta, pos transform.sizeDelta) Vector3 corners new Vector3 4 transform.GetWorldCorners(corners) Gizmos.color Color.magenta Gizmos.DrawLine(corners 3 , corners 0 ) Gizmos.DrawLine(corners 0 , corners 1 ) Gizmos.DrawLine(corners 1 , corners 2 ) Gizmos.DrawLine(corners 2 , corners 3 ) The first section should draw a line from the bottom left to the top right according to what the transform reports are the width and height however they don't reach across the entire transform. Using GetWorldCorners the actual corners can be found and drawn around, with that data you can extract that the actual width is 60 (150.2 30.2 120 2 60)! Why? Is this a bug or an I missing something obvious here?
|
0 |
Getting the Halo property of a point light in Unity I am adding point lights in my scene ( max 6 ) and I want to be able to enable its Halo property via script. However in the documentation reference, they haven't mentioned how to enable the halo property of a light source via script. This is what I have so far. GameObject lightObj new GameObject("Light") lightObj.AddComponent lt Light gt () lightObj.light.color Color.blue lightObj.transform.position city.transform.position new Vector3( 6.0f,0,0) Point Lights have a property "Draw Halo" on the Inspector but how do I enable it via script?
|
0 |
Upon import, isosphere is missing To build my tank for a Unity game, I am using Blender. Currently, I am making a turret consisting of an isosphere with half of the faces removed (I needed the bottom to be "flat") with some minor visual edits, two cylinders (one is the hatch, the other the antenna), and a cube to act as a hinge The inside is hollow. When I imported it to Unity (drag and drop from File Explorer straight to Unity Assets folder), the entire isosphere was missing as you can see from the preview I have tried to correct the normals with CTRL N as mentioned in other Blender forum pages but it still doesn't work. How exactly do I make my isosphere appear in Unity? NOTE This works if imported as a .fbx file but I would much prefer the file to be a .blend file instead (which is default).
|
0 |
Unity text component not updating text properly It was worked fine previously, but after some point, it's not working. This is the code. It's not a pseudo code, actual code in game public Text healthText void Start() healthText GameObject.Find("UI InGameUI CharacterStatus HealthText").GetComponent lt Text gt () void Update() if(healthText) print(health) healthText.text Time.deltaTime.ToString() healthText.text "HP " health.ToString() healthText.text "HP " health variable "health" is float value. I just want to print it to the screen, but it's always prints "Health 100" even it changes. So I printed the value to the console, but it prints well in the console and only text components was not printed properly. So I printed Time.deltaTime instead of the health and it works! Seriously, what the hell is happening? Is this a bug? If health variable wasn't changed, it should be also printed 100 in the console, but it's not! Try this to another text component, still not working.
|
0 |
Unity ECS Issues with rotation Posting this here because I spent several days trying to figure out why I couldn't rotate my entities the way I wanted to in Unity. For a little bit of background, I'm creating a flight dynamics model using Unity's Entities package. Part of this project involves providing keyboard input to a system in order to manipulate the motion of an aircraft a very basic simulator. I encountered an issue when I tried rotating my aircraft entity using the Rotation.Euler() method. In fact, just about every approach I saw on every forum I visited could not provide the answer I was looking for. My keyboard input logic manipulated the bank angle (roll), alpha (pitch), and yaw, and I was trying to set an absolute angle for my entity based on those values. It seemed that I was unable to set the rotation values the way I would in the inspector panel, since rotating the entity one direction would make rotating it along another axis unpredictable. Such is the nature of quaternions. Thus, I found a solution to my issue, involving a simple helper function that converts a float3 array of rotation values (one for each axis) to a quaternion. I'll be posting the code and explanation in the answer below. EDIT In the previous iteration of my code, this is what I had tried in order to update my entity's rotation Vector3 temp transform.rotation.eulerAngles temp.x 90.0f state.bank temp.y 0.0f temp.z state.alpha Entities.ForEach((ref Translation translation, ref Rotation rotation, ref AircraftData aircraftData) gt translation.Value position rotation.Value Quaternion.Euler(temp) ).Schedule() All other code within the answer below was the same (minus the new quaternion calculations).
|
0 |
How to access "move" values from move node in Rain behavior tree? I have a blend tree for the NPC that takes an "input magnitude" value 0 to 1.0 for how fast the character should move...and an "angular input" float negative pi to positive pi for how fast the character should turn. How do I get the rain behavior tree to update these values correctly in the behavior tree "set parameter" leaves? I see that I can set the parameter with some kind of variable name, but I don't see where I can specify that variable with a script...and I don't see how I can access the "move" instructions given from the move node on the behavior tree, and use them to set the variables either. How would I accomplish this steering with Rain?
|
0 |
Unity Erase Image from mouse pointer I want to erase the image for mouse pointer in unity. My pointer should be as a eraser. What is I do create the eraser? My sprite is always change because it provide from the server. Please help me.
|
0 |
Unity3d seamless level loading I've read that application.loadLeveAdditiveAsync is a pro only feature. I'm looking for an asset that can do something similar. I would like to load assets based on the camera player position. Ideally, it would be great to dispense with scenes entirely and just load information based on some distance value. This asset seems to be doing just that https www.assetstore.unity3d.com en ! content 8015 however I'm not sure if the author is active anymore, and recent customers are complaining about a serious bug. Any recommendations about assets that allow for seamless, open world style transitions between scenes would be great. (using Unity 3D 5, basic version, and writing in c ).
|
0 |
Detecting if "Wall" To The Left or Right Of Player Unity3D I am working on a 3D Platformer in Unity3D and I need to prevent the player from going through walls. The movement for my player works like this (A bird eye view representation)The areas the player can move a divided into layers. He can slide into the 2nd, 1st , or 3rd layers. The player is not a rigid body, and is controlled using a character controller. To move the player into these layers I simply increase his Z Axis. Currently if my player is behind the wall he will slide directly into it. How can I determine if there is a wall to the left of the player in Unity 3D? If so, I simply wont allow the user to move to the layer until they have steered clear of the obstacle. Does anyone have any suggestions of what I should do?
|
0 |
How to update Unity? I have clicked on check for updates but it says I have latest Unity. But latest is 5.6. How to update it to 5.6?
|
0 |
How can I stop showing camera image in my Scene? Unity How can I stop showing camera image in my Scene in Unity? As you can see on the screenshot there is an image of a camera inside a player in the Scene view. How can I disable the image?
|
0 |
How to destroy a clone of an effect attached to an object? I want to use some particle effects into a bonus object that will be destroyed upon contact with the player object. This object as its name suggests will add a certain benefit for the player for a certain amount of time. I was following a tutorial on Youtube. The code from the Tutorial worked fine but there is one problem I was not able to solve the explosion will not be destroyed after the object is collided with player and after the script is triggered because it seems that it was cloned into the scene. The instantiation created a clone of the effect's prefab I referenced into the script. After looking into the internet, I tried to affect the instantiation of the effect into a variable called clone and then destroyed it after the bonus is over but the problem was still present. I researched and I really did not obtain any answer. bonus.cs using System.Collections using System.Collections.Generic using UnityEngine public class bonus MonoBehaviour public float multiplier 2.0f public GameObject pickup effect public float duration 10 private GameObject clone private void OnTriggerEnter(Collider other) if (other.CompareTag("Player")) StartCoroutine( pickup(other)) IEnumerator pickup(Collider player) Debug.Log("You picked a bonus!") spawn cool effect clone Instantiate(pickup effect, transform.position, transform.rotation) apply effect yo the player our.score value 10 player.transform.localScale multiplier GetComponent lt MeshRenderer gt ().enabled false GetComponent lt Collider gt ().enabled false wait x amount of seconds yield return new WaitForSeconds(duration) remove the effect from theplayer player.transform.localScale multiplier Destroy(gameObject) Destroy(clone,4f) I tried disabling the "loop" option in the effect's particle system options but it gave the same results. I disabled the "Play on Awake" option and the effect will not play at all. The script is added directly to the object that is a simple 3D cube with MeshCollider, Mesh Renderer and Box collider. The effect I used is a BigExplosionEffect taken from Unity Particle Pack 5.x from the Asset Store. I would like to know what is exactly wrong? Is it probably related to the effect itself rather than the script? Or is there a far better solution?
|
0 |
Unity Button still interactable even when interactable is set to false my button can still be pressed in game even if I set it to button.interactable false What I'm trying to achieve is when the Panel CropsPanel is opened, or active in Unity, I want the EquipmentButton to be disabled and to be not usable by the user. Here is the code I've written public void Start () GetComponent lt Button gt ().interactable false if (CropsPanel.activeInHierarchy true) EquipmentButton.interactable false I have also set all buttons in the inspector, placed a Debug.Log("msg here") to see if the particular code is working. But I can't seem to get it working. Am I missing something? Thanks guys!
|
0 |
Pixelated shadows in Unity I have tried everything I can think of and all the solutions I could find on forums, but I haven't been able to fix this problem. I have a point light that is shining on several spheres which are casting shadows. The shadows work fine, but they are quite obviously pixelated. How do I get them to be smoother? These are the settings that I took this screenshot with. I've tried tweaking most of the them, but it's possible I wasn't using the right combination to get the smoother shadows.
|
0 |
Unity create water issue I use daylight water in my project but by the default it has not got any waves or light tracing effects. But in some tutorials I see how the user add standard water asset and it has got beautiful world reflection on the surface and beautiful waves. Is this issue because that I am using not a PRO version?
|
0 |
Adding Grass to a Low Poly Mesh in Unity How would I go about adding grass to a low poly mesh in Unity? Here is what I have looked into Object2Terrain I am not using Unity's built in terrain system because I am going for a low poly art style. I tried converting my terrain mesh object to a terrain (using Object2Terrain) however this removes the sharp edges on the terrain, because Unity uses a height map for optimization. PolyMesh From the get go I knew this approach wasn't going to work. I knew it would be incredibly inefficient to render that many meshes at once. I still tried it though, and to no surprise, it was very laggy. Particle System From what I've read, this should work fine for randomly scattering grass over your mesh, however I do want some control when placing grass. I followed this tutorial image as suggested by a comment in this question on Reddit, however, I was never able to achieve the desired result. Nevertheless, I do want control over placing the grass, and so I moved onto another approach. Shaders I'm not experienced at all when it comes to creating (or even using) shaders, and it's quite a daunting topic to me. I've read that this is the most efficient approach, however haven't been able to understand how this means I could draw grass onto a mesh? On the same Reddit post linked above, "UpstairsCurrency" was kind enough to link their source code (here), however I'd like to understand what is happening? I'm reluctant to say that I'm not even sure I understand how to implement it into my project in the first place. Would appreciate any sources for reading up to help understand what is going on! Thanks!
|
0 |
Fill all unallocated space with texture I have a system of bunkers underground, and I need to fill all the free space where there are no buildings with earth. Yes, I can manually add a ground texture to the plane, but I have procedural level generation. I thought there might be some kind of filter on the camera that I don't know about. Or maybe there are some other solutions?
|
0 |
Get all objects of Additively loaded Scene? (LoadSceneMode.Additive) I learned how to Load and unload scenes in unity. using LoadSceneMode.Additive. I like to spit up my scenes as much as possible and retain the stuff I need as I go along. I'd like to be able to find all objects loaded from a specific scene. Obviously Unity knows but I can't find how to get them. For now, my workaround is to put them in a specifically named empty or have them tagged in a certain way, but that is a workaround. Is there an easier way?
|
0 |
How to remove terrain in 3d? After the release of Minecraft I saw more and more rip offs of the game but some actually began to change it up a bit making the game have a organic look instead of the iconic blocky one that Minecraft does. If you'd like to look at the game that i'm referring to you can do so here. If you skip to around 50 seconds on the first video the steam page offers you can see the mining part that i'm wondering about. I was wondering how this affect is achieved where they are able to remove part of the 3D object on collison with the players pick. I have heard about constructive solid geometry before and figured that could have been used but i'm not so sure.
|
0 |
How make animation only consider the final position? I'm trying to make an energy indicator for a puzzle, and i decide to user animation to set the position of the red indicator(photo). My first ideia is to make 9 animations, and for every black arrow i set the final position to the red indicator. And organizer in the animation controller. But the main problem is, after every animation, the red indicator got to the first position, in the case the first arrow black, and then go the final position, because all the animation have the same position in the begin (0s). How can i animation the trasition of red indicator to only got to the end position? Like, if the position of the red indicator was in the 7th black arrow and then go to 3th arrow. Is possible with animation?
|
0 |
How to Replace two object by rotating in center I created Find Rock game but I have problem In replacing two object by rotating in center and when rotating finish stop rotating how can I do this? using UnityEngine using System.Collections public class example MonoBehaviour public GameObject obj public int Randomize new int 2 void Start() StartCoroutine (Delay ()) IEnumerator Delay() Randomize 0 Random.Range (0, obj.Length) Randomize 1 Random.Range (0, obj.Length) while (Randomize 0 Randomize 1 ) Randomize 0 Random.Range (0, obj.Length) yield return new WaitForSeconds (2) obj Randomize 0 .transform.rotation Quaternion.Euler (new Vector3 (0, 0, 0)) obj Randomize 1 .transform.rotation Quaternion.Euler (new Vector3 (0, 0, 0)) StartCoroutine (Delay ()) void Update() if (obj Randomize 0 .transform.rotation.eulerAngles.y lt 90 obj Randomize 1 .transform.rotation.eulerAngles.y lt 90) obj Randomize 0 .transform.RotateAround (obj Randomize 1 .transform.position, Vector3.up, Time.deltaTime 100) obj Randomize 1 .transform.RotateAround (obj Randomize 0 .transform.position, Vector3.up, Time.deltaTime 100) I can make this game but when rotating finish they aren't Directed. this video link describe my problem and this is unity package of my game. how can I use mathf clamp RotateAround for stopping rotation?!
|
0 |
Shader to see silhouette through alpha blended sprites I want to achieve in Unity a see through effect like the one in these examples In my specific scenario there are a couple of requirements Sprites are using alpha blending, and sprites have transparent areas. There are 2 kind of elements that occlude the character. One should create the silhouette effect, and the other one should behave like normal. For occluding elements that create the silhouette I enable ZWrite, and disable it for elements that doesn't. For the character I tried setting the queue of the shader to transparent 1, and added this pass Pass ZTest Greater Lighting Off Color Color And the effect works partially The silhouette is drawn all over the character, even the parts that are transparent. Transparent parts shouldn't create a silhouette. The silhouette is created when the character is behind a sprite, even if that part of the sprite is transparent. Being behind a transparent part of the sprite shouldn't create the silhouette. The character appears infront the rest of the elements, even if it is behind them. I guess this is because setting the queue to Transparent 1. But if I leave it as Transparent, the character is drawn in the correct order, but the silhouette is never seen. I tried to follow these tips someone gave me, but I'm unable to get it to work 1) Leave the pass that renders the sprites as is. 2) Add a pass that writes to the z buffer, but has a shader that uses clip() to discard pixels based on alpha. You can't use the z buffer to make soft z tests without using MSAA and alpha to coverage. The quality of that won't be great, but it's the best you can do. A faster alternative is a pattern or noise dither, or a good old fashioned threshold if your sprites all have fairly sharp edges. 3) Add third pass to occludable objects that draws the occlusion color using the z test and make sure it's drawn as a final pass. I'm kind of new to shaders, specially in Unity, and I just can't figure out how to make it work properly.
|
0 |
How to make the camera follow the mouse in first or third person camera I currently I have a game made of a few small scripts, the PlayerController, PlayerStats, and CameraChange (each below). My question is how do I get the camera to follow the mouse movement? I want the player to be able to switch between each camera and look around with the mouse. Any idea as to how I'd go about doing this? My current theory is I would some how have to access the current active camera and make it follow the mouse but not sure how to do that. PlayerController using UnityEngine public class PlayerContorller MonoBehaviour Update is called once per frame void Update () var x Input.GetAxis("Horizontal") Time.deltaTime 150.0f var z Input.GetAxis("Vertical") Time.deltaTime 3.0f transform.Rotate(0, x, 0) transform.Translate(0, 0, z) PlayerStats using System.Collections using System.Collections.Generic using UnityEngine public class PlayerStats MonoBehaviour public int Health 100 public int Stamina 100 public int magic 100 Use this for initialization void Start () Update is called once per frame void Update () if () CameraChange using System.Collections using System.Collections.Generic using UnityEngine public class CameraChange MonoBehaviour public GameObject ThirdCam public GameObject FirstCam public int CamMode Update is called once per frame void Update () if (Input.GetButtonDown("Camera")) if (CamMode 1) CamMode 0 else CamMode 1 StartCoroutine(CamChange()) IEnumerator CamChange() yield return new WaitForSeconds(0.01f) if(CamMode 0) ThirdCam.SetActive(true) FirstCam.SetActive(false) if(CamMode 1) FirstCam.SetActive(true) ThirdCam.SetActive(false)
|
0 |
How can I create a tunnel parallax depth effect based on mobile device tilting? I would like to create applications similar to what's displayed in these videos VR Tunnel Live Wallpaper for Android The parallax view Part 1 These mobile application are supposed to react to tilting of the phone, so I created a few 3D objects for this purpose in Blender (one similar shape 2nd link), but I do not know how to move the back of this object in Unity because I am a beginner. Can you give me some tips on how to figure this out? I m not talking about a ready solution or something, I just do not know how to ask a specific question and I do not know what to do next.
|
0 |
Problem with coroutines unity 3d I cannot understand why the coroutines are not waiting the designated number of seconds before executing the code below it. At the moment, the animation bleeds into the next state. I could get around this by using .time and if statements but I thought the whole point of coroutines is that you can avoid that sort of mess. public IEnumerator LoadBow() this.gameObject.GetComponent lt Animation gt ().CrossFade("Load Bow") yield return new WaitForSeconds(this.gameObject.GetComponent lt Animation gt () "Load Bow" .length) aimStates AimStates.Draw public IEnumerator DrawBow() this.gameObject.GetComponent lt Animation gt ().CrossFade("Draw Bow") yield return new WaitForSeconds(this.gameObject.GetComponent lt Animation gt () "Draw Bow" .length) aimStates AimStates.Aim public void Aiming() moveTarget.SetActive(false) switch(aimStates) case AimStates.Load StartCoroutine(LoadBow()) break case AimStates.Draw StartCoroutine(DrawBow()) break
|
0 |
How do you "branch" a Unity project How do you branch a unity project? Suppose you have Game Project A, and say there is variant A' that requires a large convoluted plugin. But the idea is also that you want to keep developing this without the plugin getting in the way, for the other variants say A and A'' that don't require it.
|
0 |
Terrain Destruction Accuracy I am making a game in unity that allows you to destroy terrain, The problem I am having is that the farther away that I get from the origin (0,0), The more inaccurate the point where the destruction occurs is. Is there a way to make it more accurate? Use this for initialization void Start () The width and height of the heightMap xRes TerrainMain.terrainData.heightmapWidth yRes TerrainMain.terrainData.heightmapHeight Getting the heightMap points saved TerrainMain.terrainData.GetHeights(0, 0, xRes, yRes) heights TerrainMain.terrainData.GetHeights(0, 0, xRes, yRes) void TerrainDestruction() Vector3 actualPosition actualPosition.x MyPosition.x actualPosition.y MyPosition.y actualPosition.z MyPosition.z Getting the x and y position of the player int xPosition (int)(actualPosition.x) int zPosition (int)(actualPosition.z) Debug.Log("x " xPosition) Debug.Log("z " zPosition) heights zPosition, xPosition 0.001f TerrainMain.terrainData.SetHeights(0, 0, heights) TerrainMain.terrainData.SetHeights(0, 0, heights) void OnApplicationQuit() TerrainMain.terrainData.SetHeights(0, 0, saved) Update is called once per frame void Update () Getting the actual Position of the player with respect to the terrain MyPosition MyMouse.mousePosition if (Input.GetMouseButtonDown(0)) TerrainDestruction()
|
0 |
3D game with Pre rendered background So a friend of mine and myself are starting to create our first game together. We descided on doing a 2.5D kind of game, so a static camera that moves with the player but cannot rotate. I got the collisions object from my friend which in unity looks like this Now I'd like to create an overlay with a JPG image which is going to cover the entire viewport and is going to "be" the map itself. I want to use this JPG as a kind of background image and then hide the collisions so the player will walk into the collisions and stop there but can't actually see them. In stead, he will see the image with buildings on it. How can I do this correctly? I've gotten as far as creating a second camera which will show me the image and then trying to create an Image (Create gameobject UI Image). But I cannot find any way to continue on this. Is this a good way to do this whole 2.5D kind of thing? We want lightweight maps in our game and thought this was a good idea to go about this. Edit My friend and me are trying to create an isometric game like this. The reason behind this is that the amount of work for the map is going to be massively reduced if we can do it like this since he can then just work in photoshop, in which he's super good. This was he does not have to bother with the 3d design in detail and can make the collision blocks much faster. So does anyone know how to get this to work? Maybe someone has a partial guide on this because I cannot seem to find anyone doing it like this but I imagine that ie Commandos is made like this. It would be much appreciated!
|
0 |
My GameObject keeps spawning when it shouldn't I'm trying to instantiate a new gameObject when the current gameObject gets to a select point. The problem comes when the program gets to the second if() statement. It sets the floorsSpawned to 1 and when it does, the game object instantiates a bunch of times. Shouldn't the floorSpawned be set to 2 in the first if() statement and only instantiated once? public class FloorMovement MonoBehaviour public GameObject floor SerializeField int speed 10 public int floorsSpawned 1 Start is called before the first frame update void Start() Update is called once per frame void Update() transform.Translate(Vector2.left Time.deltaTime speed) if (transform.position.x lt 18.0 amp amp floorsSpawned 1) floorsSpawned 2 Instantiate(floor, new Vector2(11.5f, 2.0f), Quaternion.identity) if (transform.position.x lt 40.25 amp amp floorsSpawned 2) floorsSpawned 1 Destroy(floor, 3)
|
0 |
Spawning large numbers of navmeshagents causes them to jump position Cross posted on StackOverflow I'm making a tower defense style game in 3D using Unity. I'm experiencing a frustrating issue with spawning large numbers of characters in an area of navmesh where if I spawn too many near the same location many of them will 'teleport' immediately after instantiation to near the navmesh destination. Here's a doodle of one of the levels The black spot is the player base the NPCs have to get to. The green scenery has no navmesh and uses mesh colliders. Scenery is mostly steep hills forming a valley the NPCs should path through. It is composed of multiple meshes marked Unwalkable in navigation. The large blue spot is the first spawn location I tried, I later tried a larger area indicated in the right side of the image (see 'things I've tried' below). When instantiating at the original spawn location if I spawn more than about 20 NPCs at once many of them will jump to the the area indicated by the red spots. The NPCs have a radius of about 1.5m, as do their colliders and navmeshagents avoidance property. Things I've tried Spawning to a random position inside a circle with a radius of 50m. Adding a large new hidden area of navmesh as in the image above, defining an array of vector positions spread well apart and spawning at each position in turn so no two navmeshagents spawn near each other. Adding a delay to navmeshAgent.SetDestination(playerBase) after instantiation hoping this would prevent the immediate jump to near the destination. Reducing navmeshagents avoidance radius. This sometimes reduces the problem a little but still, even with a radius of 0.1 any more than around 50 NPCs triggers the problem. Turning avoidance off althogether (setting to none in navmeshagent), again, can spawn more but problem still happens Turning off auto traverse links and auto repath in navmeshagent Increasing the time between instantiations, a large gap of several seconds works but makes the game too easy Not setting a destination oddly they still teleport to near the player base, so I guess destination is not a factor How can I spawn large numbers of navmeshagents in a short timeframe, avoiding this 'teleporting' behaviour?
|
0 |
Canvas overlapped by scene objects I am doing a space game and I have a little problem when doing the GUI. As you can see here the objects from the scene overlap the text from the GUI. From what I've seen on other topics, it seems that using Camera screen space any object closer than the Plane distance overlaps, but if I decrease the plane distance I can't see the canvas. I've also tried setting the screen space to overlay, which should fix this, but then the GUI is not shown in the screen. Anybody knows how to prevent the overlapping or at least what should I do for being able to use screen space overlay? Thanks!
|
0 |
How to make sure an object NEVER passes through an edge collider (2D)? In my top down perspective game, I have a ball that bounces off of walls. The ball should behave in a way where it will always bounce off in a 90 degree angle. The ball can only move up, down, left and right and the walls are slanted so that they should always (theoretically) bounce a ball up, down, left or right. On the ball object, I have a small circle collider 2D and a Rigidbody 2D attached, the walls have a single edge collider 2D attached. Approximately one time out of twelve times, the ball will simply pass through the edge collider, so it's not consistent. How can I make sure that the ball always registers the collision? Here's my setup The script I use to move the ball void Update () switch (direction) case 'u' transform.Translate(0f, ballSpeed Time.deltaTime, 0f) break case 'd' transform.Translate(0f, ballSpeed 1 Time.deltaTime, 0f) break case 'l' transform.Translate(ballSpeed 1 Time.deltaTime, 0f, 0f) break case 'r' transform.Translate(ballSpeed Time.deltaTime, 0f, 0f) break Additional info every wall is it's own object with it's own edge collider. the ball always hits the center of the wall because I center the ball object using the center of the wall it touches. Note I had issues with the ball passing through walls even before I implemented the centering.
|
0 |
How can I switch between texture atlases based on the iOS version? How can I switch between atlases (with different resolutions) in Unity based on the runtime iOS version?
|
0 |
problem on enable and disable GameObject I'm trying to enable and disable GameObject (canvas) using this code public int canvaslevel 1 public GameObject one public GameObject two public GameObject three void Update() if(canvaslevel 1) one.SetActive(true) two.SetActive(false) three.SetActive(false) if(canvaslevel 2) one.SetActive(false) two.SetActive(true) three.SetActive(false) if(canvaslevel 3) one.SetActive(false) two.SetActive(false) three.SetActive(true) but it doesn't work!!! error Cannot implicitly convert type int' tobool'
|
0 |
In Unity's Shader Graph how do you access parameters from code? I recently rewrote a shared I was using into Shader Graph. As an example I carried out the color as an external parameter. In my traditional shader to set the color I would call something like MyMaterial.SetColor(" NewColor", color) In the new code, I could not figure out the name of the parameter until I looked at the generated code. Turns out my Color parameter was actually named "Color D027E98" So now my code is MyMaterial.SetColor("Color D027E98", color) Not very pretty and I don't know how constant D027E98 is. Is this the correct way of changing a shader's parameter? Should I be doing something different using Shader Graph Is this number going to change on me as if I update my shader?
|
0 |
Attach a method to every GameObject or use a manager script I'm new to Unity but not new to development so I'm wondering what the standard way of doing this in with Unity. In the scene from the start is an empty GameObject that has a script that contains all of the items in the game. Once the game starts, chest prefabs are going to be spawned in the game and upon interaction they will reveal some random loot from the items script. Is it better practice to have a script on all of the chests that accesses the items script or should I create another empty GameObject as a sort of a chest manager that accesses the item script and keeps track of all of the chests in the game and what all of their loot is.
|
0 |
How to always land a square box in 90 degree How can i Always Land a box in 90 degree Here What i want Here what i don't want public Rigidbody2D boxRb public float jumpSpeed public Vector3 rotation public float rotationSpeed public bool rotationEnabled public float gravityMultiplier void FixedUpdate() if (Input.GetMouseButtonDown(0)) boxRb.velocity jumpSpeed Vector2.up if (rotationEnabled true) transform.Rotate(rotation rotationSpeed Time.deltaTime) if (Input.GetMouseButtonDown(1)) boxRb.velocity Vector2.up Physics2D.gravity.y (gravityMultiplier 1) Time.deltaTime void OnCollisionEnter2D(Collision2D collision) rotationEnabled false Debug.Log("Collided") rotationSpeed 0f boxRb.constraints RigidbodyConstraints2D.FreezePositionX transform.Rotate(0, 0, 90f) void OnCollisionStay2D(Collision2D collision) rotationEnabled false Debug.Log("In collison") rotationSpeed 0f boxRb.constraints RigidbodyConstraints2D.FreezePositionX void OnCollisionExit2D(Collision2D collision) rotationEnabled true Debug.Log("Free") rotationSpeed 10f
|
0 |
How can I convert an html5 web game to an android app? I have already made an html5 game and it is in service. I want to service this at Android app too. I know little about Java or Kotlin, so I think the least risky way is to use a webview. There is already a function to save game data with Oauth authentication. I thought this part should be replaced with google play Oauth. However, there is a problem that the app does not run when the player is offline. (Run the app fails to load any html document) However, if you load a local html file, it will be rejected from the existing firebase SDK because there is no domain. In fact, I know very little about native app development, so I don't know that what I don't know, what I need. What should I do in this situation? Do I need to rebuild my app in Kotlin or Java from scratch? Do I have to use the same engine as Unity? Do I have to rebuild with a framework like cordova? The question may not fit here, but I need help. Please.
|
0 |
How can I get Unity to tell me the battery status of my OS X laptop? How do I get battery status on an OS X laptop in Unity? This is un Googlable I keep finding either mobile stuff (iOS or Android) or people complaining about laptop battery life.
|
0 |
Unity Re import doesn't re import fbx So I have an fbx file with animations and materials on it. Simple stuff. But when I change something on the fbx, like adjusting some animation, then re export as fbx, Unity does not re import the fbx when I do RMB gt Re Import. It shows the loading bar but doesn't actually effect the current mesh by re importing. Is this normal? Is there a way to re import the fbx while keeping the modification I made on the mesh. Like, I changed the Scale Factor and some other things, so I want to keep these while re importing.
|
0 |
Water drops on camera How can I create water drops on camera something like we see in Ripitude GP, I tried using Unity's default GlassStainedBumpDistort shader though its performance heavy on mobile plus it do not let animate water drops.
|
0 |
How can I use Unity AR without cloud services? From what I've read so far, it looks like if I want to build AR apps with Unity, I need to use some kind of cloud service. Is there a way to use AR without sharing my (and my users) data to some 3rd party? If so, how do I do this?
|
0 |
Appropriate use for prefabs in Unity in a coordinate based game? I am wondering how exactly to use prefabs in Unity for my discretely coordinate based game. Should they only be for gameObjects that are exactly the same? Or can they have small variations? Example a treasure chest is interactable and it holds items, so I would make it an empty gameObject, add an interactable component and then an itemContainer component and then drag and drop it into my prefabs folder and delete the instance in the scene. But the question remains, if I make this treasure chest a prefab, how do I edit the itemContainer component of this treasure chest? Moreover, how would I serialize it for later use, and organize my data? Would I have to use external data files and reconstruct the ItemContainerComponent, just for a treasure chest? That sounds like a lot of work. If I edit the itemContainer component as a prefab, then all treasure chests will have the same items. Obviously this is not feasible. Do I drag my treasureChest prefab from the prefabs folder and then simply drop it in the game? That's how most people use it, right? I would prefer not to just drag and drop the prefabs, because I want a more industrialized approach, and I do want some way of saving what is in each treasure chest. I can't for the life of me figure out a good way. Help appreciated! EDIT I see the link provided that marks this as a possible duplicate. However, none of the answers in that link are clear enough to be useful to me, e.g., the "factory." It would be nice if someone could explain the factory idea in more concrete terms.
|
0 |
What is best for 2D movement velocity or AddForce? So I have tried both Velocity and addForce but I'm not getting the result I was expecting which makes me wonder if I fully understand what they do. Move script (test script 1) void Update () if(Input.GetKeyDown(KeyCode.Space)) rb.velocity new Vector2(rb.velocity.x, jumpHeight) if(Input.GetKeyDown(KeyCode.A)) rb.velocity new Vector2( moveSpeed, rb.velocity.y) if (Input.GetKeyDown(KeyCode.D)) rb.velocity new Vector2(moveSpeed, rb.velocity.y) Move2 script (test script 2) void FixedUpdate() float x Input.GetAxis("Horizontal") float y Input.GetAxis("Vertical") rbody.velocity new Vector2(x speed, y speed) Both scripts are used independently. Velocity when I press the key down (D or A) it stops after short time but addForce seems to do the same while that is set in FixedUpdate() or Update(), which is confusing as I thought it would keep it moving till the key was released? I have also found that if I press D it moves then stops but if I release D and press again and repeat the player does not move until I press a different move direction. Any ideas?
|
0 |
How people get their game ideas? One thing that always stop me when I want to start making a game is having no idea what to do. How do people get ideas for their game ? I mean realistic ideas for people who are alone with the minimum ressources (no money for assets, blender and unity). I will never stop being impressed by all new concept, mecanics or crazy ideas of game indie developpers come up with, like making game out of random everyday objects. I wish I was able to do that. Do developpers get their inspiration by looking at other games and trying to mix them or change the concept ? Do they look outside trying to come up with what they wish was a game ? Or do they simply walk around and try to imagine a game with whatever they see or reallife situations or concept ?
|
0 |
Runtime Access to Unity 2d Tiles I'm trying to use Unity's 2017 tilemap features. What I would like to do is push a tile's sprite up (change its offset), so that the sprite moves up pixel by pixel and the top of the sprite loops (wraps) back around to the bottom. Basically, I want to animate my "Water" sprite without having to build 20 different versions of the sprite to achieve the same effect. I was able to do this in Rotorz tiles by accessing its Atlas' MainTexture Offset or something like that but this product is discontinued. This animation is similar to the water in classic RPG games like Ultima 4. More than that, I would just love to have runtime access to the tiles to do other things change out the entire sprite on a single tile, change the color, etc. I have made a custom Tile class using this example https docs.unity3d.com Manual Tilemap ScriptableTiles Example.html But this only seems to affect tiles at the time of placement. Is this possible and does anyone have a good example? Docs on this feature are scarce.
|
0 |
How to make an object jump an equal height whenever it hits the ground? So, I want to make an object jump an equal height whenever it touches the ground. Something like a bouncing ball. But I can't use Physics Materials. Here are some ways that I tried Used Physics.CheckSphere isGrounded Physics.CheckSphere(rayPoint.position, grounDistance, groundLayer) if(isGrounded ) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) Used Raycast bool groundHit Physics.Raycast(rayPoint.position, transform.up, rayDistance, groundLayer) if(groundHit) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) In each cases, the object jumps a different amount of height each time it reaches the ground. How can I make it jump an equal height each time?
|
0 |
add random force and direction to rigidbodies every x seconds i need to add a windForce to multiple rigidbodies, with random direction and random force every x lapse of time. I'm using InvokeRepeating to update the windDirection so that the rigidbodies can be pushed in a different direction every x seconds. Here's the code void windRotate() windDirection.y Random.Range(0, 360) transform.Rotate(windDirection smooth) if (objectsInWind.Count gt 0) foreach (Rigidbody rigid in objectsInWind) rigid.AddForce(windDirection 10) This way the rigidbodies don't receive any force. I guess the system does not recognize the Vector3 Update of windDirection, so I need to recalculate it, bit I was not able. On the other hand if I use this rigid.AddForce(Vector3.Up 10) the rigidbodies moves but in one direction only, and it's not updated on the next windDirection change. I tried playing with the various Vector3 values (up, right etc..) and different force methods (AddRelativeForce) but nothing changed. By using Debug.Log(windDirection) i know that windDirection is updating correctly ever 3 seconds, so it should also be updated in my methods when i apply the force, but id does not work. Any suggestion? Thanks
|
0 |
Unity Scripting Runtime Version Option Missing I have been trying to open and run my couple months old project in Unity3D, and I'm getting about 500 errors. So idecided to reinstall Unity. On the tutorial for the project, it tells us to make sure the "Scripting Runtime Version" is set to 4.x equivalent. Only problem for me is I cannot see such an option in Unity5.5.4p4. How can I set .NET 4.x in Unity for good?
|
0 |
Conditional Variables in Scriptable Objects While using ScriptableObjects, how can I make some variables conditional? Example Code System.Serializable public class Test ScriptableObject public bool testbool public string teststring public int testint Goal When testbool true then teststring is available to edit, when testbool false then testint is available to edit while the other one is "grayed out".
|
0 |
Unity Guitext object always triggering a collision 2D I have a guitext object which I can drag. I have attached a 2d rigid body. I have also attached the collider with the following code void setCollider() Rect box this.guiText.GetScreenRect () BoxCollider2D boxCollider (BoxCollider2D) gameObject.AddComponent (typeof (BoxCollider2D)) var boxX box.width var boxY box.height Debug.Log ("boxX " boxX "boxY " boxY) boxCollider.size new Vector2(boxX, boxY) I have a sprite with a collider set as trigger. However, it triggers as soon as the game starts and is not anywhere near the trigger sprite. It will only trigger the one time when it starts. My Trigger on my sprite is as follows void OnTriggerEnter2D (Collider2D other) Debug.Log ("Order Right Arm") Debug.Log (other.bounds) EDIT based on answer I have changed the size of the collider to account for the pixel unit difference void setCollider() float pixelRatio (Camera.main.orthographicSize 2) Camera.main.pixelHeight Debug.Log ("Pixel Ratio " pixelRatio) Rect box this.guiText.GetScreenRect () BoxCollider2D boxCollider (BoxCollider2D) gameObject.AddComponent (typeof (BoxCollider2D)) float boxX box.width pixelRatio float boxY box.height pixelRatio Debug.Log ("boxX " boxX "boxY " boxY) boxCollider.size new Vector2(boxX, boxY) Any ideas on how I can get this to trigger only when I drag the guitext over the sprite?
|
0 |
How to make a custom event system framerate friendly? I have a simple event system class GameEvent float executionTime Action action class EventMgr MonoBehaviour List lt GameEvent gt events new List lt GameEvent gt () void Update() float timeNow Time.time for(int i events.Count 1 i gt 0 i ) if(timeNow gt events i .executionTime) exents i .action() events.RemoveAt(i) public void ScheduleEvent(float delay, Action action) events.Add(new GameEvent() action action, executionTime Time.time delay ) Then, I schedule events like this eventMgr.ScheduleEvent(0.1f, () gt EVENT A should be fired first eventMgr.ScheduleEvent(0.15f, () gt EVENT B should be fired second Everything works fine when I play on 60 FPS. Update() is fired once every 0.016s. When I play the game on a device with 20 40FPS things got a little bit tricky. Events seem to run in an incorrect order (Event B fired before event A). The only possible cause is of course the framerate itself. If the game runs at 20FPS, Update() would be called less frequently and both of these events would be fired in the same frame and then, the order of their execution depends on the list itself. What to do here? Is there any trick to prevent this, is there any pattern for accurate, ordered event system in games which is FPS friendly?
|
0 |
NavMeshAgent fails to find paths in certain areas in NavMesh I've been using Unity for about 2 days, and I have a scene with a navmesh. I can click on the NavMesh and get the NavMeshAgents to move to that position most of the time. However, there is a region of the NavMesh where it fails to generate a path to. I technically have two NavMeshes, because I have two different sized NavMeshAgents, but both fail in the same region. Since I'm very new to Unity, I don't know how to diagnose this, much less fix it. How should I go about learning more about this problem? I can path through the affected area, as long as the destination point is on the other side of it. Also, when I put a cube in the middle of the affected area and rebake the NavMesh, the problem area moves to a new location, so it must have something to do with the geometry.
|
0 |
Unity how do I play an intro only the first time the player starts the game? I have an intro animation scene in my game that I want to play the first time the player hits play from the main menu. How do I do this?
|
0 |
Unity How to calculate max distance (range) of a Projectile taking drag into account? I am able to calculate the projectile max distance, but it only works when there is no drag applied on the spherical projectile. I used the formula for range of a projectile as follows void OnCollisionExit(Collision other) if(other.gameObject.name "bat") initVel ballRigidbody.velocity.magnitude lineObject.transform.LookAt(transform) angle Mathf.Abs(lineObject.transform.eulerAngles.x 360) radianAngle Mathf.Abs(Mathf.Deg2Rad angle) maxDistance (initVel initVel Mathf.Sin (2 radianAngle)) g This works well if there is no drag. But as I add drag, the range ends up being far away from where the projectile actually lands. I looked up https en.wikipedia.org wiki Projectile motion Trajectory of a projectile with air resistance but can't quite understand how to use it. Here's a solution I tried if(ballHeight gt maxHeight) maxHeight ballHeight else if(!flag) maxHalfDistance Vector3.Distance(ballFollow.transform.position, centerPoint.position) maxDistance maxHalfDistance Mathf.Clamp(maxHalfDistance, 1f, 1.75f) flag true Basically calculating horizontal distance at max height and multiplying it a value between 1 and 1.75. ballFollow is horizontal position of ball and centerPoint is the launch position. This works perfectly but there is a problem that actual range isn't calculated until the ball reaches its maxHeight. So, how can range of a projectile be calculated taking air resistance in account?
|
0 |
Lerp vs Vector math one better than the other? In Unity3D (all versions, I believe), there is a static function for the Vector3D class called "lerp". It interpolates a point between two points a point, based off a provided percentage related to the desired distance between the two. Alternatively, I could just get the direction I want to go as a point, subtract it from my current position, Normalize() the resulting vector, then multiply that times a speed value. So Is one way faster than another? and Is there a third better faster easier more efficient way I don't know about? Thanks.
|
0 |
How to implement Fog Of War with an shader? Okay, I'm creating a RTS game and want to implement an AgeOfEmpires like Fog Of War(FOW). That means a tile(or pixel) can be 0 transparent (unexplored) 50 transparent black (explored but not in viewrange) 100 transparent(explored and in viewrange) RTS means I'll have many explorers (NPCs, buildings, ...). Okay, so I have an 2d array of bytes byte , explored. The byte value correlates the transparency. The question is, how do I pass this array to my shader? Well I think it is not possible to pass an entire array. So what technique shall I use to let my shader know if a pixel tile is visible or not?
|
0 |
Voxel terrain generation performance problems I am trying to create a minecraft clone to practice some stuff in Unity including Raycasting, terrain generation and player controlls. Terrain is generating without any problem with a perlinNoise. My problem is the then following performance problems. The terrain is only 1 block high with no underlying blocks. Each block constist out of 6 quads with a 64x64 texture. I generate terrain at 200 x 200 size. I can't imagine why 4000 voxels with such simple textures can lag out whilst my pc runs objects with 50k tris and complex textures without any problem. My code ... public int xVoxels 200 public int zVoxels 200 ... for (int x 0 x lt xVoxels x ) for (int z 0 z lt zVoxels z ) voxel script parameter GameObject newVoxel GameObject.Instantiate(voxel) Vector3 position new Vector3() position.x xVoxels 2 x position.z zVoxels 2 z PerlinNoise stripped out for testing position.y 0f newVoxel.transform.position position Solutions I tried Combining meshes Combining all meshes to a single one per material worked wonderfully... until I wanted to interact with each voxel determined by Raycasting from the Camera, I had a raycast hit to the combined mesh and not to my determined voxel Generating the planes myself Instead of using the unity plane object I generated all vertecies myself, same performance problems
|
0 |
Unity Save load in a sandbox game, how to instantiate saved objects I have a game where a player can place GameObjects. I can save load this GameObjects data with using JSON, for example its position, but I cannot think of a good way to tell my save file (and my load) what Prefab it needs to instantiate at position X. How I could this be done in a clever way?
|
0 |
Are there drawbacks to resizing mesh renderer bounds? I had a problem yesterday where some of the meshes were not visible. I figured out the problem, which was that the mesh renderer bounds were not in the cameras field of view. So, in order to make the mashes visible, I'm thinking of either making the bounds of the mesh renderer larger, or moving them forward so they are in the camera view. If I do this, are there any drawbacks, like potential glitches, problems, more strain on the system, etc that might happen?
|
0 |
Rotate meshes with different pivots, equality If I have multiple equal meshes but with different pivots and I make a rotation on the first, is there a way to replicate this rotation to all meshes using a rotation Matrix? For example, if I have a cube, one with it's pivot in the center and another with the pivot outside of the mesh, how can I rotate the first one 90 degrees on the X axis and use it's rotation Matrix to have the second model rotate on itself and not on his pivot? Assuming that when I pass on the rotation matrix to other meshes I can't pass the vector of the pivot, is this possible?
|
0 |
Unity Behavior Designer get gameobject I am trying to create my own action in Behavior Designer. However i cannot seem to get the game object that designer is attached to. if i attempt to do protected Combatant enemyCombatantObject public override void OnAwake() enemyCombatantObject GameObject.GetComponent lt Combatant gt () base.OnAwake() It gives me an error the property or indexer 'Task.GameObject' cannot be used in this context because it lacks the get accessor Can anyone tell me how to get the GameObject that the script is attached to?
|
0 |
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?
|
0 |
When to use a blend tree vs state machine for animation Im an experienced game dev hobbiest making my first game with 3d animated characters (in Unity) and am struggling to figure out when to use blend trees vs animation state machines. I understand both conceptually but have seen both blend trees and animation state machines used for character animation in a bunch of tutorials both from Unity and from other sources. I am not sure when why one is better than the other am hoping someone can point me in the right direction. My game is a 3rd person action rpg a'la WoW or KOTOR or Mass Effect (different systems I know but the perspectives and combat styles are kinda close at a high level). I have tons and tons of animations for attacks, blocks, feigns, deaths, walking, running, jumping, shooting etc but I am unclear on how to sequence them together naturally. I have seen blend trees used for locomotion which makes sense to me when trying to keep character motion fluid, but I dont understand how to go from that blend tree to an attack state and nothing I have seen so far has gone past locomotion (no attacks etc). Do I need to make blend trees from my motion states to attack death dodge states? Do I have more control using just state machines? Im a little cautious of state machines because of the transition bloat that is so common with them and because I suspect there is greater potential for janky animation sequencing without blending. I am planning to use the Unity character controller and write my own logic scripts to drive it. For the AI I will be using the built in nav mesh agents. Are character controller animations handled differently than the AI ones? Any insights would be more than welcome! Thanks
|
0 |
Is coroutine as good as a delay() function I'm new to Unity and I was learning the usage of coroutines. Is calling a coroutine as good as a delay() function? Does Unity have a delay() function?
|
0 |
How to efficiently implement a 7 segment display? I want to construct a 7 segment display (as shown below). When you input a number, the script will read the input number and light up the respective segment (change the spriterenderer color to red) to display the number. But I think the code has become too long, since there is 0 9 digit to display, I need 10 if statements, 8 scripts and the function of each statement is to light up the respective segment so it displays the number correctly. Is there any better way to make the code shorter? using UnityEngine public class ClockController MonoBehaviour Rect1 rect1 Rect2 rect2 Rect3 rect3 public GameObject othergameobjectrect2 public GameObject othergameobjectrect3 void Start() int x 1 if (x 1) rect1 GetComponent lt Rect1 gt () rect1.Rectangle1() rect2 othergameobjectrect2.GetComponent lt Rect2 gt () rect2.Rectangle2() rect3 othergameobjectrect3.GetComponent lt Rect3 gt () rect3.Rectangle3() using UnityEngine public class Rect3 MonoBehaviour public void Rectangle3() GetComponent lt SpriteRenderer gt ().color Color.red using UnityEngine public class Rect2 MonoBehaviour public void Rectangle2() GetComponent lt SpriteRenderer gt ().color Color.red using UnityEngine public class Rect1 MonoBehaviour public void Rectangle1() GetComponent lt SpriteRenderer gt ().color Color.red
|
0 |
place sprites in grid pattern within an area I have been trying to do this for a few hours in unity now but cant get my head around it. basically i have 4 points(vector3) 1 each for the 4 corners topleft, topright, bottomleft, bottomright. now i have a sprite that i use as a block what i want to do is basically fit X number of blocks within the four points. see the image below. Icant think of a way to do this right now. I would really appreciate any help in how to achieve this. thanks for helping.
|
0 |
How to add to a MonoBehavior array from an Editor script in Unity I've made an editor which makes a list of tags and splits them into two rows of true or false values (selectable by the user). I then compile this list into a dictionary, and each entry is like so "tag", bool, bool On my MonoBehavior script, I have two arrays string depth tags string angle tags My goal is to essentially save the dictionary data and be able to recall it also have it affect the script. To do this, I've been trying to add to these arrays according to the values found in the Editor script's dictionary. I've done quite a bit of searching and this was the only potential solution I could come up with, but sadly it did not work. EDIT Ok, I can now edit the list (added and subtracted from arraySize when doing operations on them), but I have a new problem The array reports as being twice as large as it should be. The first half of the arrays are correct and as they should be, but the latter half is made up of empty values. When I try to access beyond the first half, Unity throws an error saying that I exceeded the array's max range. EDIT 2 FIXED Answers telling you to increase and decrease arraySize are WRONG OUTDATED. Clearing, inserting, and deleting from the table does that for you! Quick Tip Inserting at index 0 in a serialized table takes care of the element bumping for you! No need to cycle through the table and move each array. void update tags() SerializedProperty depth tags serializedObject.FindProperty("depth tags") SerializedProperty angle tags serializedObject.FindProperty("angle tags") depth tags.ClearArray() angle tags.ClearArray() foreach (string tag in tag list values.Keys) if (tag list values tag 0 true) depth tags.InsertArrayElementAtIndex(0) depth tags.GetArrayElementAtIndex(0).stringValue tag if (tag list values tag 1 true) angle tags.InsertArrayElementAtIndex(0) angle tags.GetArrayElementAtIndex(0).stringValue tag serializedObject.ApplyModifiedProperties()
|
0 |
How to import animation from MotionBuilder to Unity? I have an animation (https i.imgur.com VZcdgHs.mp4) working in MotionBuilder. I have tried exporting the whole thing as an FBX, and also have tried exporting as a Motion File. Either way, when I import it into Unity and set up the Mecanim and Animation Controller and set the animation as the quot Entry State quot animation... My character moves to one pose and then stays frozen. Does anyone know how to correctly get an animation from MotionBuilder to animate a character in Unity?
|
0 |
How can I play and stop a Visual Effect Graph effect through script? Can anyone please give an example lines of code one could use to play stop a VFX through C script.
|
0 |
How to show a float with no decimals I want to show the current health and stamina of the player using GUI.Label. All is working fine however it shows the values with decimals to the millionth (example http gfycat.com SkeletalSinfulKouprey). How would I go about showing only the whole number? My code var cur stamina float var cur health float var staminaRegenRate float 5 var healthRegenRate float 1 regen if(cur stamina lt max stamina) cur stamina staminaRegenRate Time.deltaTime if(cur health lt max health) cur health healthRegenRate Time.deltaTime function OnGUI() GUI.Label(Rect(1,1,100,20), "Health " cur health) GUI.Label(Rect(1,15,1000,20), "Stamina " cur stamina) GUI.Label(Rect(1,30,100,20), "Ammo " cur ammo)
|
0 |
How do I set something when 2 or more touches are pressed? I currently have a working controller with left and right but I want to set the velocity of the character to 0 Stop when 2 or more touches are detected. This is my current working code but I want to make the player stop when 2 touches are detected. void TouchMove() if(Input.touchCount gt 0) Touch touch Input.GetTouch(0) float middle Screen.width 2 if(touch.position.x lt middle amp amp touch.phase TouchPhase.Began) MoveLeft() else if (touch.position.x gt middle amp amp touch.phase TouchPhase.Began) MoveRight() else SetVelocityZero() This is how my game looks like
|
0 |
Objects do not stop when colliding each other while using mouse drag I work on a 2D game and I have multiple objects that the player can control. The objects each have a RigidBody2D and a Collider, and a method OnMouseDrag() with which I can drag the objects. I want the dragging to stop when the objects hit each other. I tried by using this rigidbody2d.velocity Vector3.zero rigidbody.isKinematic true But the objects do not stop. I want exactly like this video. I tried this but it isn't work too. https www.youtube.com watch?v ZfjVR 0ZFHU amp t 270s using UnityEngine using System.Collections public class NewBehaviourScript1 MonoBehaviour bool allowDrag true void OnCollisionEnter(Collision collision) allowDrag false void OnMouseDrag() if(allowDrag) float distance 7 Vector3 mousePosition new Vector3 (Input.mousePosition.x, Input.mousePosition.y , distance) Vector3 objPosition Camera.main.ScreenToWorldPoint (mousePosition) transform.position objPosition if ((transform.position.x lt 0)) Vector3 tmp transform.position tmp.x 0 transform.position tmp if ((transform.position.x gt 4.5f)) Vector3 tp transform.position tp.x 4.5f transform.position tp void OnMouseUp() if ((transform.position.x gt 0) amp amp (transform.position.x lt 0.375f)) Vector3 tr transform.position tr.x 0 transform.position tr if ((transform.position.x gt 0.375f) amp amp (transform.position.x lt 1.25f)) Vector3 fs transform.position fs.x 0.75f transform.position fs if ((transform.position.x gt 1.125f) amp amp (transform.position.x lt 1.875f)) Vector3 tr2 transform.position tr2.x 1.5f transform.position tr2 if ((transform.position.x gt 1.875f) amp amp (transform.position.x lt 2.625f)) Vector3 tr4 transform.position tr4.x 2.25f transform.position tr4 if ((transform.position.x gt 2.625f) amp amp (transform.position.x lt 3.375f)) Vector3 tr6 transform.position tr6.x 3 transform.position tr6 if ((transform.position.x gt 3.375f) amp amp (transform.position.x lt 4.125f)) Vector3 tr7 transform.position tr7.x 3.75f transform.position tr7 if ((transform.position.x gt 4.125f) amp amp (transform.position.x lt 4.875f)) Vector3 tr8 transform.position tr8.x 4.5f transform.position tr8 void Start () void Update() Please help!
|
0 |
Change the min width height of a LayoutElement to scale with the screen size I want to change the Min Width and Min Height configured in my LayoutElement so that they scale proportionate to the screen size. For example, at a screen resolution of 1920x1080, the min width is 300. Then if I reduce my screen size to 1280x720 (one third smaller), then the min width should become 200. How can I do this?
|
0 |
How do I check if animation is of Animation Type "Humanoid"? One can set the Rig Animation type of an animation to quot Generic quot , quot Humanoid quot , etc. How could I check by script if an animation rig has been set to type quot Humanoid quot ?
|
0 |
GameObject with Audio File called with FindGameObjectWithTag returns "Object reference not set to an instance of an object" I'm puzzled with this error because in a different file (see below), I'm doing exact same process to an object to enable disable and works fine. But this new object throws the error, the object has a Script calling an audio file. Enabling manually the Object, and playing the game the audio is fine. I hit the check box to disable it and I get the error "Object reference ..." This audio object is attached to another GameObject which is the character of the game. using UnityEngine using System.Collections using UnityEngine.UI RequireComponent(typeof(BoxCollider2D)) public class carController MonoBehaviour public float carSpeed public float maxPos 4.17f Vector3 position public ParticleHit pr public AudioManager cr public Blast cb audioObj GameObject.FindGameObjectWithTag("policeAuTag") audioObj.SetActive (true) cr.carSound.Play () What am I doing wrong.? I have closed and reopened unity but nothing. I have changed the tag name but same error. I have tried also "FindWithTag" and doesn't work. What is causing the code to throw errors?
|
0 |
My bullet changes the velocity depending on where I click I want to build a little 2D Sidescrolling shooter and I'm now at the shooting script. I already figured out how to shoot a bullet towards my mouse pointer. I got something like this Vector3 shootDirection shootDirection Input.mousePosition shootDirection.z 0.0f shootDirection Camera.main.ScreenToWorldPoint (shootDirection) shootDirection shootDirection transform.position shootDirection.Normalize () Rigidbody2D bulletInstance Instantiate (rocket, transform.position, Quaternion.identity) as Rigidbody2D bulletInstance.velocity new Vector2 (shootDirection.x speed, shootDirection.y speed) Now obviously the bullet goes faster if my Direction coordinates are big and slower if they are smaller. Have you some better code for me or how can I fix that issue? I added now some loop like this, which brings a horrible performance, but kinda works out for the problem, but I'm still looking for a better solution. while (((shootDirection.x speed) (shootDirection.y speed)) lt 20) speed 0.1f So the loop makes sure that the overall speed is always almost the same, but this solution ends in an infinity loop if the values get too small.
|
0 |
Instances in the Unity Profiler Timeline What do Instances mean when you click on an operation in the Timeline section of Unity Profiler? In this example Total 11.90 ms (10 Instances)
|
0 |
Alternate Answer for collision problem? I am building a top down game in unity which works well. In this game, I have a 3D object (red cube) which a player has to control and there are other cubes like white, yellow and black cubes which spawns in the interval of 5 seconds. In each 5 seconds, prefabs of these three villain cubes instantiates and follows the player. There is also a text that says yellow, black and white and changes constantly. For instance, the text is now white and it changes to black within certain interval of time and changes to white in certain interval of time (this is random) So, the player has to collide with the cube same as the the text otherwise the player will die. Now, the problem is I have built the game just fine and can't get to deactivate player when the player hits the unrelated cube. The script is(for instantiating ) public class ColorChecker MonoBehaviour public GameObject text public int hold public float startTime public float startTimebtwSpawn Use this for initialization void Start () Update is called once per frame void Update () startTimebtwSpawn Time.deltaTime if (startTimebtwSpawn lt 0) startTimebtwSpawn startTime hold Random.Range (1, 4) if (hold 1) text 0 .SetActive (true) text 1 .SetActive (false) text 2 .SetActive (false) else if (hold 2) text 1 .SetActive (true) text 0 .SetActive (false) text 2 .SetActive (false) else if (hold 3) text 2 .SetActive (true) text 0 .SetActive (false) text 1 .SetActive (false) The script for destroying the object is public class DestroyCubes MonoBehaviour public ColorChecker colorchecker Use this for initialization void Start () void OnCollisionEnter (Collision col) if (colorchecker.hold 1 amp amp col.gameObject.tag "CubicMonster1") Destroy (col.gameObject) else if (colorchecker.hold 2 amp amp col.gameObject.tag "CubicMonster2") Destroy (col.gameObject) else if (col.gameObject.tag "CubicMonster3" amp amp colorchecker.hold 3) Destroy (col.gameObject) Now, I can obviously check if it is unrelated by a long code like if (colorchecker.hold 1 amp amp col.gameObject.tag "CubicMonster2" amp amp so on) Destroy (gameObject) Rather than writing a long if statement like this, Is there a better way that I can handle this ?
|
0 |
Actions abstraction in Goal Oriented AI I am back with another question about Goal Oriented AIs. To explain my problem, I will use a specific example. In my game, population nodes are spawned on a world map, and important characters called "Migration leaders" can spawn, take in migrants, lead them to a good spot, and then establish a new population node there and finally despawn as they have served their one time purpose. What I want to achieve is having only one action called "MoveToTarget" which has no pre conditions apart from having a target location, and has the effect of setting the fact "Reached target location" to true, which itself is the precondition for other actions. Not sure this is the right way to structure that in the GOAP but that's not exactly my problem, at least I do not think so. My problem is that, since you can't work with actions that take in an argument, I have little notion of how the AI should determine the location which it will move to when the "MoveToTarget" action triggers, for the following reasons Depending on the character type and generally what is happening, each character will think differently about where they're interested in going. Furthermore, what happens when I have to interrupt the AI's "plan" for some reason ? The original target location for, say, transporting migrants is lost ! I do not which to make different actions like "MoveToMigrationTarget" because then I'll have to make many MANY more actions, like "MoveToCombatTarget" or "MoveToRessources" and I do not think that will work as that will make me have to keep a "Migration target", a "Combat target".. in memory even for characters that have nothing to do with either of those. So my question exactly is, where is the AI supposed to do the "practical thinking" in a GOAP ? The Actions themselves must be abstract, and can't take in any argument so I have to somehow have target location(s) in memory and have the GOAP planner know which target corresponds to which action. I could also extend that question to basically any action that need a specific target object to work.
|
0 |
Unity2D Horizontal Scaling to Support Various Aspect Ratios? I am trying to work out how to support various resolutions for my Android game. I have come up with a solution, but do not know how to implement it. Automatically, I am told that Unity vertically scales the screen to match the screen, leaving more room at the sides. How can I change this behaviour? I am hoping to shrunk the game down till it fits horizontally, and filling it the background above and below with more decorative features. How can I achieve this? I'm sorry if there is an obvious answer, I'm quite new working with the Unity UI system. If it makes it any easier, my game is heavily based on UI, and is locked in landscape. BIG EDIT I completely rephrased this question because it was so broad and messy.
|
0 |
Unity2D Frost Effect Time scale I downloaded this package ("Frost Effect by Steven Craeynest") on Unity Asset Store and altered it into making the effect happen once I click on a button (button 1), I first disabled the frost button (button 1) in my inspector before playing the game and created another button (button 2) to activate the frost button(button1). However I'm having issues with the frost effect. You see when I click on button 2 to activate the frost button (button 1) frost effect works for a bit but then stops at delayBeforeUnfreeze like time.timescale is equaled to 0 and the only way of making time.timescale is equaled to 1 is by pressing my pause button and clicking the resume button. Anyway this is my script private FrostEffect frost float duration 0.2f float delayBeforeUnfreeze 0.34f private float previousTimeScale public GameObject frostbutton public int buttonCount 0 int timesActivated 0 public void Check() buttonCount Use this for initialization void Start () previousTimeScale Time.timeScale public void Activate () frostbutton.SetActive (true) public void CreateFrost () if(timesActivated lt buttonCount) timesActivated GameObject.Find ("Main Camera").GetComponent lt FrostEffect gt ().enabled true Slow timescale Time.timeScale 0.06f Freeze time effect DOTween.To (x gt FrostEffect.FrostAmount x, 0.0f, 0.34f, duration) .OnComplete (() gt Unfreeze tween effect DOTween.To (x gt FrostEffect.FrostAmount x, 0.34f, 0f, duration) .SetDelay (delayBeforeUnfreeze) Set timescale back to previous. Time.timeScale previousTimeScale ) Thank you. ) Second Edit This is my panel animation script public void DisableBoolAnimator(Animator anim) anim.SetBool ("Shown", false) public void EnableBoolAnimator(Animator anim) anim.SetBool ("Shown", true) This Youtube link will show you what my panel animation looks like 31 47. Thank you. )
|
0 |
Unity WebGL Build Why it shows only Empty Folder? i'm trying to built my game, made in Unity 2018.3, and i'm trying to built it in WebGL, but the problem is this built was succeeded, but the Folder is still Empty, and here is the problem occured This was never happened to me before. anybody know how to fix it?
|
0 |
How to make one material on object with many parts inside? I have a weapon witch have many parts, it also have many materials. Do I really need to make it like that? It's like about 8 mats! (
|
0 |
Simulate parallel dimensions subspaces in Unity without colliding coordinate systems I've built an online game with Unity with a very large open world. The server (which can be a local player, or run as a standalone application without a local player) simulates everything around players so for example if there is an object or NPC at coordinates (100,34,20) but there aren't any players nearby then the object is not simulated. Objects are streamed dynamically from a database or generated procedurally depending on the object. Problem I want to enable players to go to other worlds. Of course it is impractical if not impossible to have global coordinates shared across all of these different worlds due to floating point limitations. I'll have to share the limited coordinate system for each simulated world. The issue is the server would still need to render and handle physics of multiple worlds but could now potentially have conflicts with objects and or people on one world appearing in other worlds. Essentially I need a way to divide up these "worlds" into parallel dimensions that are executed simultaneously on the same server (in one Unity scene). Parallel Dimensions A partial solution would be to have some sort of indicator, such as an integer (I'll call it "worldIndex") on each object to indicate which "world" that object exists in. This would work for clients since the server would be able to tell the clients only about objects that are on their world. There would still be a problem on the server itself. Every world needs to be simulated in the same coordinate space. For a local player I could use the "worldIndex" to hide objects that aren't in the local player's current "world". But I still need to simulate physics for every world. Unity's Layers could be used to mask physics interactions between objects. However I would then need to have at least one layer per world and I already use multiple layers for various different interactions. My thoughts are I would need something like a layer I could specify on each GameObject or some way to group a bunch of GameObjects together and instruct the physics system to only allow interactions within the group. But as far as I know no such mechanism exists within Unity. Subspace Pockets Another thought I've had is rather than using the Unity coordinate space directly, I could slice it up into "subspaces" or pockets. Each player would be in their own subspace, unless a player physically enters the same space that is already being simulated by another player, in which case that player would join the same subspace. But then I would have shift around the coordinate systems and it would increase complexity of merging players into and out of these subspaces. I would also have to generate subspaces dynamically as players enter new areas that are not currently being simulated. Even if each world is extremely large, it is not necessary to use the entire Unity coordinate system around each player a few thousand kilometers is more than enough. Overall I think something along these lines is probably the best solution. Multiple Servers I could run one server per "world" and have a hand off process to make it transparent to players. But then I'd have to run multiple server instances and players would not be able to host their own server at least not without a lot of additional overhead. Question So my question is what is the best method for essentially running multiple, parallel simulations within a single Unity scene?
|
0 |
Orthographic Camera settings for a 2D game I'm starting out a 2D wrestling game in Unity 5 and i need some help. The default resolution of game needs to be 320x240. The background sprite that i would be using is 640x480. The camera would move over the background to give it a hovering look. I want the Camera to cover exactly 320x240 resolution. I tried setting the Camera size to 1.2 and it looks approximate but i wanna be sure that the camera is exactly 320x240. By default all the images are set to 100 Pixels per Unit. So my question is How to set the camera to cover exactly 320x240
|
0 |
Simple Car Animation Acceleration Too Slow I am trying to make a very simple car animation where using the arrow keys, I can make a car move around. I am using wheel colliders and some code that goes like this using System.Collections using System.Collections.Generic using UnityEngine public class Car My MonoBehaviour public float Motorforce, Steerforce, Brakeforce public WheelCollider FR L Wheel, FR R Wheel, RE L Wheel, RE R Wheel Start is called before the first frame update void Start() Update is called once per frame void Update() float v Input.GetAxis( quot Vertical quot ) Motorforce float h Input.GetAxis( quot Horizontal quot ) Steerforce print(Input.GetAxis( quot Horizontal quot )) RE L Wheel.motorTorque v RE R Wheel.motorTorque v FR L Wheel.steerAngle h FR R Wheel.steerAngle h if(Input.GetKey(KeyCode.Space)) RE L Wheel.brakeTorque Brakeforce RE R Wheel.brakeTorque Brakeforce if(Input.GetKeyUp(KeyCode.Space)) RE R Wheel.brakeTorque 0 RE L Wheel.brakeTorque 0 if(Input.GetAxis( quot Vertical quot ) 0) RE L Wheel.brakeTorque Brakeforce RE R Wheel.brakeTorque Brakeforce else RE R Wheel.brakeTorque 0 RE L Wheel.brakeTorque 0 When I do this, the car moves but it accelerates too slowly. I changed all the values but I cannot get it to start at a faster speed. Any help is highly appreciated.
|
0 |
Controlling resolution in Unity 3D. Beginner's problems i started working on developing games one month ago. I really like it, although it isnt easy. The problem i have now, is with display resolution after i build game. So far i have been working with 2D Space Shooter game (getting help from the tutorial), everything is working smoothly. The only thing that i hardly understand is the resolution, aspect ratio thing. I have made a game that looks like this I have drawn a gizmos around the allien formation, and written a script with some calculations that everytime formation hits the edge, it goes to the other edge, hits the other edge, and goes to the other edge, and so on and on. In the free aspect movement looks great, but however, then i change the resolution to any other, movement is stuck, or it barely moves. Now here is my question. What should i do, to make the game look and work smoothly on every resolution like it works on the free aspect display? I tried to change formation height and width and so on, but i assume this is not an option. I will add my formation controller script as well(it contains several other things so i printscreened only the code that helps formation to move) Thank you for your time, and sorry if you can't understand everything or something is unclear to you, i'm beginner at game development and English is not my first language.
|
0 |
Character stuck on box collider 2.5D I'm having trouble with my character on a 2.5D platformer. The character get stuck if it collides without reaching the platform's top. Here is a gif showing it http i.imgur.com jmZ6O1K.gifv Both colliders (platform and character) has a physics material with no friction (or minimum). So I don't know why is this happening. Character Collider Physic Material
|
0 |
Why this if logic isnot short circuiting? I've this script in UNITY to check if the hit RayCastHid2D variable has some gameobject with hole tag or a parent gameobject with hole tag when I Raycast... if (hit.collider ! null amp amp (hit.collider.gameObject.tag "hole" (hit.collider.gameObject.transform.parent.gameObject ! null amp amp hit.collider.gameObject.transform.parent.tag "hole"))) Everything is fine until if (hit.collider ! null amp amp (hit.collider.gameObject.tag "hole" but when I enter (hit.collider.gameObject.transform.parent.gameObject ! null amp amp hit.collider.gameObject.transform.parent.tag "hole") it throws a NullReferenceException.... But why? It supposed to short circuit here hit.collider.gameObject.transform.parent.gameObject ! null amp amp if there's no parent gameobject!
|
0 |
Random.range giving me the same value at the same time I created a random direction in x and y axis at where to move, then my problem is when I tried to randomize it sometimes I get the same value at the same time on both x and y axis. How do I not let this happen, I only want one axis to have a value, not both? ERROR HOW I WANT IT TO HAPPEN CODE public Vector2 randomDirection void Awake() void Update() randomDirection new Vector2(Random.Range( 1, 2), Random.Range( 1, 2))
|
0 |
Resize rigidbody in runtime, Box collider OnTriggerEnter not work Scene setting Object A Rigidbody, kinmeatic Box collider, is trigger true. Object B Box collider, is trigger true. Script is on Object A void FixedUpdate() if(increaseScale) transform.localScale transform.forward speed when to stop if ((AEForward transform.localScale.z).sqrMagnitude gt range range) increaseScale false void OnTriggerEnter(Collider other) Debug.Log(other.transform) No log message when part of object A is inside B. And the funny part is if I use it on a sphere collider, it works. (use transform.localScale new vector3(1,1,1) speed instead )
|
0 |
How can I start a new row when instantiating UI elements in a grid? using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() int counter 0 imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.Find( quot Slots quot ).transform slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) NOW INSIDE THE FOR LOOP string fileName imagesToLoad i byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName GameObject ChildGameObject go.transform.GetChild(1).gameObject ChildGameObject.GetComponent lt RawImage gt ().texture thisTexture var raw go.GetComponent lt RectTransform gt () if (counter 3) raw.anchoredPosition new Vector3(1 , 0.3f, 0) counter 0 else raw.anchoredPosition new Vector3(1 counter gap, 6, 0) counter Update is called once per frame void Update() Now it's creating a line of 3 objects but then when it's filled with 3 objects in a line I want it to move one step down and start a new line of 3 and so on. The problem is I can't make it automatic move one step down with the right gap on the Y and start a new line. I'm doing the new line with this raw.anchoredPosition new Vector3(1 , 0.3f, 0) but the result is that the fourth object is too much down And it should be like this
|
0 |
Building an Octree for terrain generation I've previously implemented marching cubes tetrahedra to render an IsoSurface. It worked (YouTube), but the performance was dire as I never got around to implementing variable Level of Detail based on view distance (or even removing old, distant chunks). I decided to have another go and do it properly this time. I've started by creating an OctreeNode that works as follows when Build() is called. If the chunk is too small to build, return immediately. Work out if the surface passes through this chunk's volume. If so, then decide if we want to raise the LOD (because the camera is close) If so, then spawn 8 children and call the same process on them If not, build the mesh using the current node's dimensions Some PseudoCode OctNode Build() if(this.ChunkSize lt minChunkSize) return null densityRange densitySource .GetDensityRange(this.bounds) if(densityRange.min lt surface lt densityRange.max) if(loDProvider.DesiredLod(bounds) gt currentLoD) for(i 1 to 8) if(children i null) children i new OctNode(...) children i children i .Build() else BuildMesh() return this As well as returning density at a point, the density source can determine the possible density range for a given volume. The LoD provider takes a bounding box and returns the max desired LoD based on camera position frustum, user settings, etc... So... This all works fairly well. Using a simple sphere as the Density source, and showing all nodes And just the leaves However, there are a couple of issues I have to define the initial bounding volume (and the larger it is, the more processing I need to do) At the root of the tree, I have no idea how deep the leaves will be, so my LoD numbering starts at lowest quality (root) and increases as chunks get smaller. Because LoD is now relative to initial volume, it's not much use when I want to do things at specific sizes qualities. I've thought of a couple of options but both seem flawed Maintain a collection of Octrees and add remove depending on distance. Can't see how I'd mesh across nicely , plus I'd need a list of known empty nodes, especially if I want arbitrary 3D surfaces (to avoid re calculating empty volumes repeatedly) Add a parent Node to the current root, then add seven siblings for the original node. This would work and be on demand but it seems complex to shrink back down sensibly as the player moves through the landscape. It would also make LoD numbers even less meaningful. In clarification to Q below At present, if 2 physically adjacent nodes in the tree are at different LODs, I have some code to coerce the verts such that there's no seam when the meshes are generated. I'm able to do this by knowing the the density for multiple of surrounding nodes. In a scenario where I have 2 independent octrees side by side, I'd have no easy way to retrieve this information, resulting in seams. What's an optimal way to approach this?
|
0 |
How to make UI text longer? I'm working on a menu that needs a wordy description, but I've noticed that it only shows 4 letters, then cuts off and this doesn't seem right. I right click, select UI text and again, it only displays 4 words, even though I can write a lot more there. Am I doing something wrong here? I'm not sure how to get past this and I want to ask if anyone knows how to get past this? It seems like such a strange limit to put on the UI canvas.
|
0 |
How to get Unity's 4.6 UI images to layer over each other perfectly? I've been noticing that if I have two images, lets say squares. I have A as the parent of triangle B. Triangle A and B both have their offsets at their anchors, which are on the 4 corners of it's "box". Triangle A should be behind triangle B, since it renders from top to bottom in the hierarchy (the last item being on top). However as I re size my screen, sometimes triangle A will poke out from behind triangle B. Even if they both are using the same image, and have the exact same dimensions. Whats causing this, and how do I fix it? Additionally, I noticed that while the anchors and offsets can be finely adjusted, the image is not. You have to adjust by certain interval sizes and the image will just snap to that new size rather than adjusting finely as you change the offset or anchors.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.