_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
No intellisense on my classes I've been using Monodevelop's current version and Unity 4. I don't get intellisense on the classes I've created but I do have intellisense on classes that are in Unity's framework. Bug or its just as it is? I use UnityScript class SomeClass extends ScriptableObject public function Test() return "" In another class, when I use a variable typed as this class I get no intellisense.
|
0 |
Get object length and width divided by two? I have googled and found a script for the following task Make the camera move to touched position. However, this script will jump to x and y positions on an object, while i would like for it to move to the middle of the object, and then only be able to jump to others. using UnityEngine using System.Collections public class TapToMove MonoBehaviour flag to check if the user has tapped clicked. Set to true on click. Reset to false on reaching destination private bool flagTouchCoords false destination point private Vector3 cameraDestination alter this to change the speed of the movement of player gameobject public float duration 100.0f vertical position of the gameobject private float yAxis void Start() save the y axis value of gameobject yAxis gameObject.transform.position.z Update is called once per frame void Update() check if the screen is touched clicked if ((Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Began) (Input.GetMouseButtonDown(0))) declare a variable of RaycastHit struct RaycastHit hit Create a Ray on the tapped clicked position Ray ray for unity editor if UNITY EDITOR ray Camera.main.ScreenPointToRay(Input.mousePosition) for touch device elif (UNITY ANDROID UNITY IPHONE UNITY WP8) ray Camera.main.ScreenPointToRay(Input.GetTouch(0).position) endif Check if the ray hits any collider if (Physics.Raycast(ray, out hit)) set a flag to indicate to move the gameobject flagTouchCoords true save the click tap position cameraDestination hit.point as we do not want to change the y axis value based on touch position, reset it to original y axis value cameraDestination.z yAxis Debug.Log(cameraDestination) check if the flag for movement is true and the current gameobject position is not same as the clicked tapped position if (flagTouchCoords amp amp !Mathf.Approximately(gameObject.transform.position.magnitude, cameraDestination.magnitude)) amp amp !(V3Equal(transform.position, endPoint))) move the gameobject to the desired position gameObject.transform.position Vector3.Lerp(gameObject.transform.position, cameraDestination, 1 (duration (Vector3.Distance(gameObject.transform.position, cameraDestination)))) So this is how the game looks. The script moves correctly, but will jump at different positions when it hits the collider on the lily pads. I could reduce the collider, but I feel like there should be an easy way to get length and width of a collider, and reduce it by 2 to make the camera move directly in the middle. Anyone care to help? Thanks in advance. )
|
0 |
Strange I'm getting exception but the scripts in the exception message are not exist on my pc. What should I do? I'm using unity version 2019.2.5f1 personal I searched on my hard disks the entire pc and none of the scripts in the exception message are exist. And the exception is happens only sometimes. When I stop the game in the editor by pressing the play button the exception is show sometimes and sometimes not. I tried to close and open over agai the unity editor and the project. Still strange. MissingReferenceException The object of type 'ReflectionProbe' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEditor.ReflectionProbeEditor.OnPreSceneGUICallback (UnityEditor.SceneView sceneView) (at C buildslave unity build Editor Mono Inspector ReflectionProbeEditor.cs 651) UnityEditor.SceneView.CallOnPreSceneGUI () (at C buildslave unity build Editor Mono SceneView SceneView.cs 3359) UnityEditor.SceneView.DoOnPreSceneGUICallbacks (UnityEngine.Rect cameraRect) (at C buildslave unity build Editor Mono SceneView SceneView.cs 1935) UnityEditor.SceneView.OnGUI () (at C buildslave unity build Editor Mono SceneView SceneView.cs 2320) System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object parameters, System.Globalization.CultureInfo culture) (at lt 599589bf4ce248909b8a14cbe4a2034e 0) Rethrow as TargetInvocationException Exception has been thrown by the target of an invocation. UnityEngine.UIElements.UIR.RenderChain.Render (UnityEngine.Rect topRect, UnityEngine.Matrix4x4 projection) (at C buildslave unity build Modules UIElements Renderer UIRChainBuilder.cs 238) UnityEngine.UIElements.UIRRepaintUpdater.DrawChain (UnityEngine.Rect topRect, UnityEngine.Matrix4x4 projection) (at C buildslave unity build Modules UIElements Renderer UIRRepaintUpdater.cs 66) UnityEngine.UIElements.UIRRepaintUpdater.Update () (at C buildslave unity build Modules UIElements Renderer UIRRepaintUpdater.cs 54) UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTree () (at C buildslave unity build Modules UIElements VisualTreeUpdater.cs 72) UnityEngine.UIElements.Panel.Repaint (UnityEngine.Event e) (at C buildslave unity build Modules UIElements Panel.cs 637) UnityEngine.UIElements.UIElementsUtility.DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel panel) (at C buildslave unity build Modules UIElements UIElementsUtility.cs 240) UnityEngine.UIElements.UIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C buildslave unity build Modules UIElements UIElementsUtility.cs 78) UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C buildslave unity build Modules IMGUI GUIUtility.cs 179)
|
0 |
Player must places the object in the preset position I want to know how to do like this video https youtu.be 6gouxqSxeG8 At the minute 3 09, the player can put the street vendor in the predetermined location (with the green arrow show that place). Please tell me some keyword about this or video tutorial about how to implement it in unity 2d. Thanks.
|
0 |
I want to clamp each instance of the same prefab to the y axis only I instantiated the prefab "paddle" twice then I tried clamping it to the y axis only using Mathf.Clamp, however, the min and max values end up being applied to both instances of "paddle" and hence they can move in the x axis ok so I'm trying to make a 2d mobile pong game, I have a prefab "paddle" which are the rackets bats which the balls collide with. I instantiated the same prefab twice one on each side of the screen Paddle paddle1 Instantiate(Paddle) as Paddle Paddle paddle2 Instantiate(Paddle) as Paddle paddle2.Init(true) right paddle paddle1.Init(false) left paddle Now i want each of the paddles to only be able to move in the y axis (UP And DOWN). So I tried clamping them with var poss transform.position poss.x Mathf.Clamp(transform.position.x, 1.0f, 1.0f) transform.position poss However, this caused the left paddle to still be able to move to the right and the right paddle to be able to the left( I don't want them to move in the axis at all). This is the file GameManager.cs using System.Collections using System.Collections.Generic using UnityEngine public class GameManager MonoBehaviour public Ball Ball public Paddle Paddle public static Vector2 topRight public static Vector2 bottomLeft Start is called before the first frame update void Start() bottomLeft Camera.main.ScreenToWorldPoint(new Vector2 (0,0)) topRight Camera.main.ScreenToWorldPoint(new Vector2 (Screen.width,Screen.height)) Instantiate(Ball) Paddle paddle1 Instantiate(Paddle) as Paddle Paddle paddle1 Instantiate(Paddle) as Paddle Paddle paddle2 Instantiate(Paddle) as Paddle paddle2.Init(true) right paddle paddle1.Init(false) left paddle void Update() This is the file paddle.cs using System.Collections using System.Collections.Generic using UnityEngine public class Paddle MonoBehaviour Rigidbody2D rb float directionY float speed float height float distance string input bool isRight Start is called before the first frame update void Start() height transform.localScale.y speed 5f public void Init(bool isRightPaddle) isRight isRightPaddle Vector2 pos Vector2.zero if(isRightPaddle) Place paddle on the right of the screen pos new Vector2(GameManager.topRight.x, 0) pos Vector2.right transform.localScale.x Move a bit to the left else Place paddle on the left of the screen pos new Vector2(GameManager.bottomLeft.x, 0) pos Vector2.right transform.localScale.x Move a bit to the right Update this paddle's position transform.position pos void Update() var poss transform.position poss.x Mathf.Clamp(transform.position.x, 8.0f, 8.0f) transform.position poss I expect each paddle to not be able to move in the x axis. Only in the y axis c unity3d mobile
|
0 |
Inventory View Screen Looking to create an inventory screen in Unity, and trying to think of the best way to do it. My current line of thinking is having a few rows of squares for inventory items that are drag and droppable onto a paperdoll, a la Diablo. When dragging and dropping on the items, it would update a 3D model of your current playable object with the items. The menu itself would be easy enough to do with a simple square and a hierarchy of game objects for the items, each responding to mouse hovering over. The problem I am trying to figure out is being able to render the 3D model on the side. Granted, this is a nice to have, and not necessarily a need, but browsing the documentation, the only way I can think of accomplishing this is using a render to texture which requires Unity Pro with a separate camera completely out of bounds of the current space. Anyone have suggestions on how to accomplish this?
|
0 |
How can I disallow the changing of a parent? I want to disable transform.SetParent(Transform) for a particular GameObject. I am not sure where to start, so it is really difficult to show what I have tried. Is this even possible?
|
0 |
surface.Bake() no such command Regarding the code shown in this video at 13 50 When I try surface GetComponent () surface.Bake() I am getting the following error message UnityEngine.AI.NavMeshSurface does not contain a definition for bake and no extension method Bake of type UnityEngine.AI.NavMeshSurface could not be found quot are you missing an assembly reference I am struggling to get the dynamic navmesh working with Unity 2017.1.
|
0 |
Transform components in ECS Many game engines I've seen which are based on an Entity Component System. It has some kind of a Transform Component as a necessary component attached to all of their entities. While this does seem to make kind of sense considering an entity is only some kind of property bag and a collection of components and transformations are world space behavior (hence just part of the composition). I've noticed two other things which are very weird Transform components are used to build up the hierarchy between entities as they have a parent entity as well as child entities Transform components are specialized for only a single kind of world space, e.g. 2D or 3D. Examples The Unity3D engine. Entity children and parents seem to be accessed through the Transform Component of each entity. Also, the Transform Component features coordinates in 3D vectors. The Xenko Game Engine (previously Paradox3D), which can bee seen on GitHub. So, is this a common practice? Best worst practice? What's the reason behind having a fixed Transform component, making the Transform component only suitable for one world space using the Transform component as an hierarchy graph?
|
0 |
Can ARToolKit be used for color detection? I'm trying to make an app that will show an object from different sides, but the target will be too small for any real marker detection. Think of a cube with one or two centimeter sides. The camera distance is not a problem but it has to be at least ten centimeters out or what I'm trying to do won't work. I was wondering whether it was possible to color one side of the cube differently than others and make ARToolKit recognize the color to know which side it's looking at. Is this possible or just not in the range of things ARToolKit can do? If so, is there any kind of AR that can do this.
|
0 |
How do I properly change the value of a prefab'd instance variable? I am currently following a tutorial on how to make a 2D platformer in Unity. The tutorial explains how to make an enemy wave spawner, but it doesn't explain how to make enemies stronger after I have completed a certain amount of waves. So, to explain I have an Enemy class, which has an EnemyStats class in it public class Enemy MonoBehaviour System.Serializable public class EnemyStats public int damage 20 public int maxHealth 100 public int CurrentHealth get return currentHealth set currentHealth Mathf.Clamp(value, 0, maxHealth) private int currentHealth public void Init() CurrentHealth maxHealth public EnemyStats stats new EnemyStats() private StatusIndicator statusIndicator void Awake() stats.Init() statusIndicator transform.Find("StatusIndicator").GetComponent lt StatusIndicator gt () if (statusIndicator ! null) statusIndicator.SetHealth(stats.CurrentHealth, stats.maxHealth) And in the WaveSpawner class I have the method to spawn the enemy private void SpawnEnemy(Enemy enemy) Transform sp spawnPoints UnityEngine.Random.Range(0, spawnPoints.Length) if (CurrentWave 5 0) enemy.stats.maxHealth 20 Instantiate(enemy.transform, sp.position, sp.rotation) In the WaveSpawner you can set a certain number of waves (let's say 5), and after you complete all of the waves I've set them to repeat. So after I beat the 5 waves, I want the 5 waves to repeat and the enemies to be stronger (for example to have their max hp increased by 20). I do that with the line enemy.stats.maxHealth 20 But the problem here is that after this line is executed and I Instantiate the enemy prefab, the prefab changes its value in the inspector. So let's say that the initial value of the prefab was 120, after I beat the 5 enemy waves, the value of the prefab is set to 140. Then, after I reset the game, the initial value of the prefab is 140 and the max health of the first enemies is 140 and not 120. I have tried to not change the maxHealth variable of the EnemyStats class, but instead to have another variable tempMaxHealth and do the changes on it. This doesn't resolve my problem, as other problems arise and I don't know what to do anymore. I hope that you have an answer for me, I would be grateful if that's the case.
|
0 |
Unity Error within Tree Editor I've been making a tree in with the Tree Editor in Unity, and for a realistic effect, I need to make all the leaves face a general direction, the problem is that most of them don't face that direction and are upside down or sideways. So you further understand, i'll add some images. I'd like all the leaves to face in this direction. (Image 1) In here you can see that some leaves are upside down or sideways and i'd like to make all the leaves face the same way. (Image 2) In here you can see the leaf is facing up and this is the way I would like all the leafs to face. Any help is appreciated, thank you.
|
0 |
Load character animation on button press Unity3D I am new to Unity3D and I am going to develop a simple animation application. There is a human character and there are three button Eg "jump", "down" , "roll", I want to bind the animation files with the human character once the player presses the corresponding button. I need your help to know that what are the steps that I need to follow...let me know if anyone has good reference, thank you very much...
|
0 |
Help in 2d platform script Now I finished my 2d game but when I set up it in my mobile it becomes like this so I change some scripts in Maincamera but it's still the same How can I change the screen to become horizontal in my mobile like this? what I need that how can I make it fit my mobile screen.
|
0 |
ReorderableList in Unity with Enums I'm trying to setup a simple ReorderableList in Unity 2017.3 for a list of enums. Adding items workes fine but selecting, dragging and deleting items from the list does not (see gif). Here is my code Serializable public enum RoofType HIP, GABLE, FLAT, NONE UnityEditorInternal.ReorderableList roofTypeList new UnityEditorInternal.ReorderableList(roofTypes, typeof(RoofType), true, true, true, true) roofTypeList.drawHeaderCallback (Rect rect) gt EditorGUI.LabelField(rect, "Roof types") roofTypeList.drawElementCallback (Rect rect, int index, bool isActive, bool isFocused) gt roofTypes index (RoofType)EditorGUI.EnumPopup(rect, roofTypes index ) roofTypeList.DoLayoutList() Any ideas why this does not work? My guess it is because I use enums and not classes but it is not documented anywhere.
|
0 |
Unity3D behaves differently in scene and game view We are having AI being able to shoot. Everything works fine when having them play in Scene view, but when going into Game view the position they are shooting from is different. Does anyone know what could cause this? That the Unity "Scene view" behaves other than "Game view"? Hope there's anyone there to help us out, thanks in advance.
|
0 |
How can I iterate over all entities with a particular component? I'm currently designing a game engine and want to implement my own ECS implementation, so I decided to look around for ideas. Unity has recently updated their engine and seems to be pushing towards using ECS, instead of their original components are systems design. I noticed that Unity has a method called "GetEntities", a generic method which can do something like this public struct SomeComponent IEntityComponent public string Message "Hello, World!" public struct Filter SomeComponent someComponent public MovementSystem EntitySystem public override Process() How can I accomplish something like this? foreach(var entity in GetEntities lt Filter gt ()) Console.WriteLine(entity.someComponent.Message) I like this style of iterating over entities, given a filter for a specific component they need to include. But I'm not sure how to accomplish something like this. If someone could shed some light on how something like this is even possible in C that would be great!
|
0 |
How to add scene after build and deployed in Unity? I want to be able to make new levels after build. I could use a map tool and script but I rather just add scene with all the resource packed with it. But what is the best practice forward?
|
0 |
More loosely coupled way to design this attack and target concept? In my 2d game in unity and c sharp, my friendly units are squares. Each square has a grid on it. Each cell of the grid can have one enemy attached to it at a time. This means that my enemy's targets are not just the friendly game object, but the cell as well. Because of this, I've created a Target class for this (just contains a gameobject and cell). Enemies carry their Target reference so they know where to move to and who to attack. However, my friendlies do not need the cell to target an enemy. Enemies are small and don't have grids on them. I cannot figure out a nice way to make this polymorphic(?) Target concept work without doing checks for quot if cell is not null quot in all of my targeting code. For example, code in my behavior tree for checks like quot HasTarget quot are tightly coupled to check for existence of a gameobject and cell. It just feels wrong. Am I stuck using custom checks and code for an enemy vs friendly target? I tried interfaces but they require the same return types. That differs depending on if they are an enemy or friendly. Something like unit.Itargettable.GetTarget() won't work. Help!
|
0 |
What takes up more processing power between whole character models or models that are pieced together in Unity? In terms of performance when it comes to animation what takes up more processing power Whole character models or models that are pieced together? (1 object vs multiple objects). I also wonder if animating multiple objects allows us to get a better overall animation quality instead of working with one object (especially if we deal with action packed scenes).
|
0 |
A trigger collider in Unity doesn't allow the player to pass through It's my understanding that checking "Is Trigger" on a collider should allow rigid bodies to pass through without collision prevention, but my trigger isn't doing that consistently. The player cannot pass through, but other objects can. The trigger is a cube primitive with "mesh rendered" unchecked so that the cube won't be visible. The cube has a box collider with "is trigger" checked, and also a script. The script currently doesn't do anything except output from Debug.Log in OnTriggerEnter() as a test. Primitives are able to pass through. The test is just a basic Unity sphere with all the default settings, including a sphere collider. The only change was that I added a RigidBody. Imported models also pass through. I have a simple .blend model with a rigid body and box collider. The player does not pass through. The main difference between the player's object and the other imported model is that the player is using a custom mesh collider which is different than the player's rendered mesh. The rendered mesh is the game object and the low poly collision mesh is a child of that object. I've tried several variations, including switching the player from a mesh collider to a box collider, and also moving the box collider to the main mesh rather than a child mesh, but the results are the same. The player stops moving as soon as he hits the location of the trigger's box collider. Any ideas are appreciated. Thanks in advance. MORE INFO Here's a screenshot of the scene layout, with the invisible trigger collider selected. Also pictured is the hierarchy showing that the trigger collider ("Jump Pad Trigger") has no children. On the right is displayed every component that the trigger object has. I've also moved the collider from its original location several times to prove that it's not another object in the scene that the player is colliding with.
|
0 |
Need help with rotating sword around player (Unity 2D) I'm having an issue with rotating an object around another object in my top down roguelike in Unity 2D. My goal is to rotate a sword around a player based on joystick input from a controller (as shown in this image). I have looked around online for any answers, but nothing has helped. All I have so far that is remotely close to what I want is code that keeps the sword attached to the box even when the box moves. void Update() transform.localPosition new Vector3(0, 1.5f, 0) It might be necessary to note that the sword object is a child of the box object. I would appreciate it if anyone could point me in the right direction. Thanks!
|
0 |
How to set the force applied to RigidBody2D depending on the time user holds touch on screen? I trying to make an object jump from 1 point to another point. How far it jumps depends on how long the player holds the touch anywhere on the screen. It jumps when player releases his touch. At the code below,I able to detect the moment player release his finger. if (Input.touchCount gt 0) Touch touch Input.GetTouch(0) Handle finger movements based on touch phase. switch (touch.phase) Finger start touching the screen case TouchPhase.Began print("Start tapping") break Finger leaving the screen case TouchPhase.Ended when finger release, the object jump float rightForce Time.deltaTime 10000 2 float jumpForce Time.deltaTime 30000 2 box2D.AddForce(new Vector2(rightForce, jumpForce), ForceMode2D.Force) break As you can see I able to get the Time.deltaTime which is I assume is how long the player hold the screen. What I want to do is calculate the rightForce and jumpForce added to the object depending on the Time user hold the touch. float rightForce Time.deltaTime 10000 2 float jumpForce Time.deltaTime 30000 2 Because if I use the 2 line of code above, the result will be almost the same everytime. So what is the correct way to determine the rightForce and jumpForce depending the time user hold touch?
|
0 |
Objects aren't rotating in sync This is a follow up question to How to reapply force applied to one object to another object I want to make two objects move, react to collisions and other stuff as if they were one. For example, Objects A and B are entangled. When Object C rams into Object A and starts moving with it, Object B should start moving with it. When Object B hits a wall, Object A should act like it also hit a wall. I tried changing position speed every frame, but this only works when done in one direction. Now, I want all forces applied to any of the objects to also apply to the other objects entangled to it. Edit This is the new code which only fails when multiple collisions happen at once using System.Collections using System.Collections.Generic using UnityEngine RequireComponent(typeof(Rigidbody)) public class EEScript MonoBehaviour public List lt EEScript gt activeObjects public new Rigidbody rigidbody public Vector3 lastPosition Start is called before the first frame update void Start() rigidbody gameObject.GetComponent lt Rigidbody gt () Update is called once per frame void Update() lastPosition transform.position private void OnCollisionEnter(Collision collision) foreach (EEScript entangled in activeObjects) if (entangled this) continue Rigidbody rb entangled.rigidbody if (rb is null) continue rb.velocity rigidbody.velocity rb.angularVelocity rigidbody.angularVelocity entangled.transform.position entangled.lastPosition transform.position lastPosition
|
0 |
Unity3D free in game purchase solution Am making an android game with unity and i want to add an in game purchase feature, i looked around and all the suggestion lead to non free plugins (mainly prime31 plugin) but in the current moment i cannot afford to invest in some of these plugins, does anyone of you have a free solution for this "problem" ? thank you
|
0 |
NullReferenceException until tile is spawned I have a tile and tile has enemies spawn positions, and spawner script in it. Everything works fine when tile is spawned, my ray hits the collider in tile and enemies get spawned, but my spawn script is in tile my ray script is in my player so im reaching from my PlayerMove script to spawner script, but until my tile is spawned i get this error NullReferenceException Object reference not set to an instance of an object because tile is not spawned yet after its spawned error stops, but after tile is deleted it starts again how can i get rid of this error. PlayerScript private Spawner spawner private RaycastHit hit private void Update() spawner GameObject.FindGameObjectWithTag("Spawner").GetComponent lt Spawner gt () DrawRay() private void DrawRay() Ray ray Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)) if(Physics.Raycast(ray,out hit)) if(hit.collider.tag "SpawnerCollider") if(hit.distance lt 5) Destroy(hit.collider) spawner.Spawn() SpawnerScript public Transform spawnPos public GameObject fireBall public void Spawn() for (int i 0 i lt spawnPos.Length i ) Instantiate(fireBall, spawnPos i .position, Quaternion.identity)
|
0 |
Why is my player not giving a knock back when it stays at the right side of the enemy? So, I have this problem I am facing, for some reason my player does not get a knockback when it stays at the right side of the enemy but when it stays at the left side it gives a knockback. What's the problem? PLAYER MOVEMENT void Movement() THIS IS FOR WALKING if (isControlesEnabled) moveInput Input.GetAxisRaw("Horizontal") runSpeed myBody.velocity new Vector2(moveInput, myBody.velocity.y) PLAYER KNOCKBACK private void OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.CompareTag("Enemy")) health 0 if (health lt 0) gameObject.SetActive(false) else ContactPoint2D contactPoint collision.GetContact(0) Vector2 playerPosition transform.position Vector2 dir contactPoint.point playerPosition dir dir.normalized myBody.velocity new Vector2(0, 0) myBody.inertia 0 isControlesEnabled false Invoke("EnablePlayerControles", controlesDisablePeriod) myBody.AddForce(dir knockBackForce, knockBackForceMode) private void EnablePlayerControles() isControlesEnabled true
|
0 |
How can the player select his weapon among many? I'm working on the prototype of my game, I want one of the options to have a very large amount of weapons. I have searched for tutorials, but I have only found weapons changes where the weapons have already been loaded in the scene from the inspector, like this https youtu.be Dn BUIVdAPg where they are only activated and deactivated. But I want a game like dofus where there are hundreds of weapons, I think I have a data file of the weapons and so, I can load the correct model of the weapon. How can I get the model loaded? I have read other tutorials regarding the AssetBundle, but I think that is when you need to download the models from a server for example, but I just want to load them from the same project. sorry for the bad english
|
0 |
Recognize that user has traced a path of vector points with mouse How can I check if a player has traced a closed vector shape from an arbitrary starting point all the way around to the beginning? Setup Given are the vector points A through E, which form a closed path. The created shape can be convex or concave and even have sharp elongated corners. P1 is the point where the player decides to start tracing. The point can be anywhere on the path and will be set as soon as the mouse or touch is first close to the path. Requirements The player starts moving along a visual representation and traces the entire shape until he reaches P1 again. If his mouse path differs too greatly, misses a point or goes outside of a given margin, I want to start over. The player may either have to trace around in the direction from which he first starts without backtracking or just have to fill the entire path even if going back and forth on the path. How can I approach this problem? Ideally, I would like to implement a vector math solution. I don't have any pixel data to sample from and it would be rather cumbersome in my real world implementation to generate a suitable image and map world space coordinates to it. My Attempt Consider each corner a waypoint with a collision area. Track each entered collider and when all were hit, solve. While valid colliders are pending, project mouse position onto the closest point on the path. If the distance between projected point and mouse is too great, abort. This approach however doesn't give me perfect results. Firstly, it's not entirely what I want, since in my ideal case the user "draws" or traces the path with the mouse, not just hits the corners. Also, when moving around a sharp corner, the project point will snap from one line segment to the next, giving me ugly visuals, when showing progress. Possibly Better Solution As soon as player comes close to path start sampling points from mouse. Build up a user drawn vector path every time step or distance step. Check if the draw vectors are similar to the given path. Problem user drawn path needs some sort of processing or more complex algorithm until it is comparable to given path. Thank you for any suggestions! I will post some of my own code as soon as my implementation gives me good results.
|
0 |
Unity third person controller and hills So I've been building a game and using the out of the box unity third person controller demo stuff. I found that even the tiniest of slopes seems to stop the "dude" dead in his tracks. Is there an easy way to adjust the sensitivity on the scripts somewhere? I tried messing with the sensitivity options in the input options setup thinking that it might help but it didn't and I don't really want to go messing about in the scripts unless I really have to because i end up complicating my life when I do that.
|
0 |
How to get direction and velocity of movement of an object dragged with the mouse in Unty (C ) I have an object that is dragged by the mouse (X and Z positions) over a table, with the following simple code Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) if(Physics.Raycast(ray, out hit)) pos new Vector3(hit.point.x,myobject.transform.localScale.y 2,hit.point.z) myobject.GetComponent lt Rigidbody gt ().MovePosition(pos) The dragging works as expected. What I am struggling with is how can one retrieve the direction and velocity of such a movement, i.e. the direction and the velocity of that object when moved by being dragged by the mouse (I use Unity, C ). I have searched online, but only found the common ways to retrieve velocity and movement when using standard Rigidbody movement, not when dragged by the mouse.
|
0 |
Performance problem when multiple enemies are grouped up I have enemy with simple behavior Reach the player's current position. In game are increasing waves, which are increasing the number of enemies. But when are more enemies (like 14), and they got too close to each other, there is big physics spike in profiler. There are significant drop of performance... And as Profiler says, it's because of Physics... Now I am little lost, I tried turn of the ignore collision on layer (which was turned on), so they don't overlap, but there is still little touch of course, when they group up, so still so much to process... What is the best solution here? I build it around rigidbodies for the use of Velocity, and detection of collisions with walls (edge collider), so when the object reaches there, it is easily stopped... But for this cases it seems now like not the best solution.
|
0 |
Raycast does not detect child layer if parent layer is set to ignore I have a LineRenderer that ignores certain Layers based on a Raycast using LayerMask. I have a cube with a collider on a Layer which is ignored because of the LayerMask. I have a smaller object inside the cube that is a child object of the cube and is on a layer that is not set to be ignored. I need the Raycast to hit the smaller object. When this smaller object is un parented from the larger cube, the LineRenderer behaves like I want it to the hit data informs me it is being hit by the Raycast, but this does not hold true if the smaller object is a child of the cube. Is there a way of having this behaviour without having to un parent the smaller object? It's like the smaller object is inheriting the parent's Layer, despite being on it's own Layer does this sound like what is happening?
|
0 |
Modifying z axis position of a canvas and adapting it to camera I have a camera with y rotation of 0. And i have a canvas with position value of (0f,76.29f,41.82f). The size value of the canvas is (194.1f,307.8f). I want to modify the z value of the canvas to 10. public Canvas textcanvas void Start () textcanvas.anchoredPosition new Vector3 (0f, 24.5f, 10f) But i get an error "error CS1061 Type UnityEngine.Canvas' does not contain a definition foranchoredPosition' and no extension method anchoredPosition' of typeUnityEngine.Canvas' could be found. Are you missing an assembly reference?" Also, when i succeed moving the canvas, does the size of it adapting to the camera automatically?
|
0 |
How do I download audio resources and save them in cache? I am developing a game in Unity3d 2019, the instructions of the game must be translated into several languages. Right now, they are part of the compilation, but this makes the compilation very large. I would like, according to the selected language, to be able to download the corresponding audio and save it in the cache.
|
0 |
How to trigger OnMouseX events on Kinematic Rigidbody2D object with a different collider than one used for collisions? I have a use case where I have an object with a Collider2D and a Kinematic RigidBody2D in order to do Kinematic movement. However, I also want to be able to select hover that object with a OnMouseDown OnMouseEnter etc, using a larger collider than I would use for the kinematic movement. My current attempt at a solution is to have Physics related scripts rigidbody2d collider2d as the top level game object, and to have a child object, with a larger collider2D which will respond to OnMouseX events. In order to ignore OnMouseX events on the parent, I'm putting it into its own user ignore raycasts layer (I need it as its own layer for the layer collision matrix). I'm also putting the child in its own user use raycasts layer. I'm passing that into a script that sets MainCamera's event mask using UnityEngine RequireComponent(typeof(Camera)) public class CameraEventMasker MonoBehaviour SerializeField private LayerMask cameraEventMask Start is called before the first frame update void Awake() GetComponent lt Camera gt ().eventMask cameraEventMask What I notice is that OnMouseX events on the child will work IF the RigidBody2D on the parent is deleted...however, if the RigidBody2D is there, I won't receive any events. Anyone know why this is the case, and if there are other workarounds or solutions?
|
0 |
Importing code from unityscripts To encourage code reuse i want to import methods and classes defined in my core unityscripts to be imported into other unityscripts. How do i go about this? Note An answer here seems too complicated for such a simple thing (i come from Python).
|
0 |
Optimizing file size of a sprite sheet for a 2D game I have a question regarding the method of creating a sprite sheet so that it will not consume to much disk space and still preserve graphics quality. I was researching about this topic and found that my sprite sheets should have sizes that are a power of two. So valid sizes would be 512x512, 1024x1024, 2048x2048 etc. Then I created two sprite sheets (one is 1024x1024 and the other is 2048x2048), they are exported as 16bit but they still use too much disk space. How can I optimize my sprite sheet to use the least amount of disk space possible? This is one of my sprites
|
0 |
Enable SteamVR hand collision for when holding objects Just getting started on a game project with SteamVR in Unity. I've run into an issue with the collisions though. The hands and the objects that can be held collide with everything in the scene as they should. But when an object is picked up, the hand and the object stop colliding with everything. How would I go about fixing this? I could leave it as is, but if an object is let go of inside another, it gets flung out of the object it was inside. The other odd behavior happens after you let an item go. The hand that was holding it continues to not collide with anything until you move the hand away. After that it'll collide with everything normally again.
|
0 |
Is the Microsoft recommendation to use C properties applicable to game development? I get that sometimes you need properties, like public int Transitions get set or SerializeField private int m Transitions public int Transitions get return m Transitions set m Transitions value But my impression is that in game development, unless you have a reason to do otherwise, everything should be nearly as fast as possible. My impression from things I've read is that Unity 3D is not sure to inline access via properties, so using a property will result in an extra function call. Am I right to constantly ignore Visual Studio's suggestions to not use public fields? (Note that we do use int Foo get private set where there is an advantage in showing the intended usage.) I'm aware that premature optimization is bad, but as I said, in game development you don't make something slow when a similar effort could make it fast.
|
0 |
How to search for all uGui scripts in scene in the Unity editor? I have many game objects whose properties I need to edit because of a bug error. However, this is very time consuming, because I need to check each game object one by one. Is there any way to search for all game objects that (for example) contain uGui Scripts in a scene?
|
0 |
Power up spawns 2 3 times after a restart, but enemies spawn normally I have two spawning objects that use the same behaviour. They are being called in the same function and in the same situations. The only difference is the variable of time that classifies what's an enemy and what's a power up. The spawning of enemy objects is working fine no matter how many times I restart the game, the behaviour is the same. But with the power up spawning object, it spawns the right way sometimes, but in other times it spawns like 2 or 3 times in the same place. This only happens when I restart the game. How can I fix this bug? I'm not fluent in english. File 1 public float enemySpawnSeconds 2.5f public float powerUpSpawnSeconds 6f public void Start() gameManager GameObject.Find( quot GameManager quot ).GetComponent lt GameManager gt () private void Update() GameSpeed() public void StartSpawnObjects() StartCoroutine(SpawnPowerUps()) StartCoroutine(SpawnEnemies()) public IEnumerator SpawnEnemies() yield return new WaitForSeconds(2f) while (gameManager.startGame false amp amp gameManager.gameOver false) Instantiate(enemies Random.Range(0, 2) , transform.position new Vector3(9.8f, yPosition Random.Range(0, 2) ), Quaternion.identity) yield return new WaitForSeconds(enemySpawnSeconds) public IEnumerator SpawnPowerUps() yield return new WaitForSeconds(2f) while (gameManager.startGame false amp amp gameManager.gameOver false) yield return new WaitForSeconds(powerUpSpawnSeconds) Instantiate(powerups Random.Range(0, 3) , transform.position new Vector3(11.1f, yPosition Random.Range(0, 2) ), Quaternion.identity) File 2 void Update() spawnPlayer() gameTimer() restartGame() public void spawnPlayer() if (startGame true) starting the game if (Input.GetKeyDown(KeyCode.Space)) Instantiate(player, player.transform.position, Quaternion.identity) spawned true startGame false uiManager.HideTitleScreen() spawnManager.StartSpawnObjects() public void gameTimer() if (startGame false) timer 0.0165447f game time public void restartGame() if (gameOver true) restarting the game timer 0f spawnManager.enemySpawnSeconds 2.5f if (Input.GetKeyDown(KeyCode.Space) amp amp uiManager.restart true) gameOver false uiManager.HideTitleScreen() spawnManager.StartSpawnObjects()
|
0 |
How can I achieve area fill in the video? I am trying to clone a game while learning Unity but I am stuck. How can I achieve area fill like shown in this Area Fill Example Video? When I searched for it I found the quot Flood Fill quot algorithm but I am also not sure is it the right solution for this or not. Because in flood fill we have to select a point and check neighbors with same value and convert them, however here how can I decide which point to select and fill? For example at 00 03 in video I close an area and game fills the area with cubes. With flood fill, if I select a starting point above that line, algorithm can travel through all outer tiles and very well can fill them with cubes also but game fills lesser area there. Why does the game pick a smaller area here? How do they decide which portion of the game field they should fill? And in 00.11 when cube hit white wall they completely fill the remaining area because I guess they assume it is fully closed. But again my question is how can you decide that? Which methods provide area fills like this? If someone has an idea or experience about this can points me to the right direction I'd really appreciate. Thanks in advance.
|
0 |
In Unity, how do I dynamically manipulate parts of a mesh? I'm trying to achieve mesh manipulation of any mesh based on user input (mostly sliders). Here's an example of what I want. I am not sure whether to call this "morphing", as I am trying to change one part of the mesh without modifying the other parts. How does this work?
|
0 |
How can I insert a prefab instance programmatically inside the Canvas, in the bottom left corner of the Canvas? I am trying to create the Snake game in Unity, based on this video tutorial. I have also viewed this tutorial. I have created the new project with the 3D template and manually added the Canvas. I created a prefab from an Image which loads a texture from the Assets. I have this code using UnityEngine using UnityEngine.UI public class GameManager MonoBehaviour public GameObject whiteCellPrefab int N 30, M 20, size 16 Start is called before the first frame update void Start() Transform p GameObject.Find("Canvas").transform for (int i 1 i lt N i) for (int j 1 j lt M j) GameObject g Instantiate(whiteCellPrefab, p) g.transform.localPosition new Vector3(i size, j size) Update is called once per frame void Update() If I manually add a prefab instance to the Canvas, it is positioned as I want in the bottom left corner. But the script above, attached to the Main Camera object, creates the Image objects starting from the center point of the Canvas towards the top right corner of the Canvas. In the example shown here, I also added a new prefab instance to the Canvas in the Unity editor. It is positioned correctly even when play testing but the ones added with the script are shown somewhere else. Screenshots Download my example I tried to explain all the steps involved in my problem above, but here is the repo with my problem. Thank you.
|
0 |
Missing UI options in Inspector window when I import FBX files I am missing all the animation options in the Animation tab in the Inspector Window when importing FBX files. In the picture below, there are only 2 checkboxes. I can't see the list of animations, options, animation events etc., but you can see on the lower left window that the animations we're imported. Also, the Materials tab is empty as well. This FBX was exported from Blender. If I directly drag the .blend file to Unity, all those tabs appear normally, but when dragging an FBX, they become empty. I am using Unity 2019.3.0f6.
|
0 |
How do I determine distance of a point within a ProBuilder mesh? As in the title, I have an effect prepped for my game which applies certain derived parameters to a post processing effect after the player enters a boundary I created with ProBuilder. Finding how far inside the bound the player is that is, how far the player would have to travel, at minimum, to leave it would help me scale this effect. It is not an axis aligned boundary, and its sloped shape is fairly important. Having the effect go full on on crossing the boundary would be jarring to the player. I'm tempted to resort to traditional edge testing with this, but I would like to highlight that it will be done at least once per frame on multiple objects, so I would like to keep it as simple, and non home rolled, as possible. The other possibility would be to keep track of time exposed and scale it by that but this isn't ideal and I'm seriously curious as to whether a penetration depth testing method exists out of box. A requested image of my setup It is laterally symmetric, and that is unlikely to ever need to change. However, future volumes are likely to have varying angles and heights. Depth is more or less irrelevant, as while I'm using 3D, this game has the physics of a 2D platformer so you can consider it to have infinite depth if you need to. As you can see on the right, I've added almost nothing to it, other than the MagneticField.cs custom script (which does not even reference the mesh, only whether it's been crossed) and a debug class, TriangleReport.cs, that I'm working on right now. One thought I had was to get triangles for the top, bottom, left, and right edges, use them to define planes, and then determine the distance from those planes but if you've got something better I am all ears!
|
0 |
Help needed, following Unity multiplayer Health Bar tutorial. Only working on Server Host instance of the game was really hoping someone can be good enough to look over my code, I've been trying to fix it for several days. I followed the Unity tutorial which is fairly basic but the bit that confuses me (and potentially where the problem lies) is the if (!server) return part at the top of my TakeDamage() function. The problem im seeing is that once I get to that part of the tutorial, the bullet fired by the Host is registered against the other player and I can see his health has gone down (great so far!) , but when I load the instance in the editor (i did running another standalone on my laptop and connect to internet matchmaking but the same thing occurs) his bullets are not registered (even though my debug log tells me the Ray did hit the player. The tutorial tells me to make it return if not server, it then uses SyncVar and a hook that is supposed to call the method "OnChangeHealth" whenever currentHealth is changed. This DOES NOT appear to be happening, and the TakeDamage code is only happening on the Server Client Host instance. I was trying to adapt the tutorial to my own game, so there are some slight differences in the function and class names, but to me it looks to be exactly the same functionality wise. I will have to just post my full code here as I don't know which part is causing the issue (MANY THANKS FOR READING AND OR HELPING) the Player class public class Player NetworkBehaviour private GameObject startScreen public const int maxHealth 100 SyncVar(hook "OnChangeHealth") public int currentHealth maxHealth private float playerHeight private AudioSource audioSource public AudioClip painBodySound public AudioClip painHeadSound public AudioClip painHeadSound2 public RectTransform healthBar void Start () startScreen GameObject.FindGameObjectWithTag("StartScreen") if (startScreen ! null) startScreen.SetActive(false) playerHeight GetComponent lt Collider gt ().bounds.size.y currentHealth maxHealth audioSource GetComponent lt AudioSource gt () void Update () if (!isLocalPlayer) return if (Input.GetKey(KeyCode.LeftControl)) transform.localScale new Vector3(1, 0.5f, 1) else transform.localScale new Vector3(1, 1f, 1) public void TakeDamage(Vector3 hitPoint, int bulletDamage) check that its Server so that damage only gets applied on the server if (!isServer) return currentHealth bulletDamage audioSource.PlayOneShot(painBodySound) if (currentHealth lt 0) currentHealth 0 Debug.Log("Dead!") private void OnChangeHealth(int health) healthBar.sizeDelta new Vector2(health, healthBar.sizeDelta.y) Inside the bullet class is this function private void CastBulletRay() ray new Ray(bulletSpawnPos, bulletSpawnDirection) if (Physics.Raycast(ray, out hit, bulletRayDistance)) if (hit.collider.tag "Baddie") Debug.Log("ray has hit a baddie") Destroy(gameObject) if (hit.collider.tag "Player") Debug.Log("ray has hit a player") hit.collider.gameObject.GetComponent lt Player gt ().TakeDamage(hit.point, bulletDamage) Destroy(gameObject) and inside The Unity RigidBodyController class I'm using, I added Command void CmdFireBullets() muzzleFlashObject.SetActive(true) audioSource.PlayOneShot(gunFireSound, 0.2f) Create a new bullet GameObject newBullet Instantiate(bulletPrefab, bulletSpawnPoint.transform.position, bulletSpawnPoint.transform.rotation) as GameObject Spawn the bullet on the clients NetworkServer.Spawn(newBullet)
|
0 |
How can I draw a specific GameObject into a texture in Unity? I need to draw only a few specific objects into a texture (with their material) and then use that RenderTexture as a texture for an another object. I think Graphics.DrawMesh() and Graphics.SetRenderTarget() would be helpful, but I'm not sure. Ultimately I'm trying to create refractive water, which will refract only specified GameObjects, not layers. How can I do this?
|
0 |
Convert Rainbow gradient Shader to 3 colors gradient I am attempting to convert this rainbow shader into just using three colors. I thought I would be able to set the three colors in the shader file, but I can't understand how to link them through the shader helper file. shader https hastebin.com uworiduluc.cs Shader helper https hastebin.com kifezufegi.cs fixed4 frag(fragmentInput i) SV TARGET fixed2 lPos i.localPosition Spread half time Time.y Speed Spread half timeWithOffset time TimeOffset fixed sine sin(timeWithOffset) fixed cosine cos(timeWithOffset) fixed hue ( lPos.y) 2.0 hue time while (hue lt 0.0) hue 1.0 while (hue gt 1.0) hue 1.0 fixed4 hsl fixed4(hue, Saturation, Luminosity, 1.0) return HSLtoRGB(hsl) I added these properties at the top Color3 ("Top", Color) (1,1,0,1) Color2 ("Middle", Color) (1,1,0,1) Color1 ("Bottom", Color) (1,1,0,1) But I am not sure where I can add them into the code to have them be the colors that are used.
|
0 |
How can I get the vector3's names to gameobject name? void DrawBox() SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color) SpawnLineGenerator(v3FrontTopRight, v3FrontBottomRight, color) SpawnLineGenerator(v3FrontBottomRight, v3FrontBottomLeft, color) SpawnLineGenerator(v3FrontBottomLeft, v3FrontTopLeft, color) SpawnLineGenerator(v3BackTopLeft, v3BackTopRight, color) SpawnLineGenerator(v3BackTopRight, v3BackBottomRight, color) SpawnLineGenerator(v3BackBottomRight, v3BackBottomLeft, color) SpawnLineGenerator(v3BackBottomLeft, v3BackTopLeft, color) SpawnLineGenerator(v3FrontTopLeft, v3BackTopLeft, color) SpawnLineGenerator(v3FrontTopRight, v3BackTopRight, color) SpawnLineGenerator(v3FrontBottomRight, v3BackBottomRight, color) SpawnLineGenerator(v3FrontBottomLeft, v3BackBottomLeft, color) And the gameobjects name void SpawnLineGenerator(Vector3 start, Vector3 end, Color color) GameObject myLine new GameObject() myLine.name start.ToString() myLine.transform.position start myLine.AddComponent lt LineRenderer gt () LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.material new Material(Shader.Find("Particles Alpha Blended Premultiply")) lr.startColor color lr.endColor color lr.startWidth 0.03f lr.endWidth 0.03f lr.SetPosition(0, start) lr.SetPosition(1, end) The method SpawnLineGenerator get two vector3 and a color SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color) In the SpawnLineGenerator i'm setting a name for each gameobject myLine.name start.ToString() This give me the name for example ( 2.1, 3.4, 4.9) Nut I want it be the name like this format v3FrontTopLeft ( 2.1, 3.4, 4.9) v3FrontTopRight ( 1.1, 3.4, 4.9) The problem is if there is a easy way to get the names v3FrontTopLeft and v3FrontTopRight and the rest from the method DrawBox instead typing each one. I want to know that ( 2.1, 3.4, 4.9) are the coordinates for v3FrontTopLeft
|
0 |
is edit tangent possible in 3dsmax? I have a custom hlsl directx shader, it takes vertex normals for rim light calculation. and vertex tangent(it stores unified normals) for edge render(enlarge model amp cull front). I can export one fbx with auto smooth normals, and one fbx with unify normals, combine them in unity, it works but the process is slow. I just wonder if I can do it directly in 3ds max, so 3d artist can preview the result directly in their tools. I tried storing unify normals data in texture coordinate or vertex color, but the data will be wrong once bone animation is running. So I believe normal tangent is the only way to go if I want to have rim lighting amp edge render together for a animated character model use in Unity3D. I guess FBX SDK will help, but I have no experience in using it. I wish someone could tell me a way to store vertex normals data into tangent. or tell me is it not possible so that I should consider another solution. thanks you.
|
0 |
Initializing Variables, Difference between Awake and in class initialization public class ExampleClass MonoBehaviour int exampleVariable 0 int exampleVariableForAwake void Awake() exampleVariableForAwake 0 What is the difference between initializing a variable at declaration vs. initilize in Awake? Which I understand is to be used in place of constructors in Unity C , welcome to correct me if I'm wrong. Which usage is considered a proper convention by the community, if any? Same question might also be in order for Properties, so I'll leave that open ended.
|
0 |
Moving IK target with Unity's New Input System I'm currently converting our 2D game from the old input system to the new input system in the hopes of making it available to more people in the future. Currently I am using the mouse position to aim a flashlight by moving the IK target of that arm to the mouse position by getting the vector of the mouse cursor and converting it using screentoworldpoint. My question is, how can I implement a similar function using the new input system with a joystick? Currently I am getting a vector2 from the joystick which ranges from ( 1, 1) to (1,1) depending on the position and angle of the joystick. I would like to have the same code for both inputs so I don't have to use an if else statement and determine what input is being used but if that is unavoidable I understand. I would just like to know the best way to go about aiming an IK target using a joystick with the new input system.
|
0 |
Clamping always returns 0 I have a class with three fields StartingAngleOnRotationPlane is 180 MinimumRotatedAngleX is 0 MaximumRotatedAngleX is 140 Here is the offending code public virtual float ClampRotatedDegreesWithinAllowedRange() float rotatedAngle this.transform.GetRotatedAngleOnXPlane() Debug.Log("Rotated " rotatedAngle) float clampedRotatedAngle Mathf.Clamp( AngleNormaliser.BetweenNegativeAndPositive180(this.StartingAngleOnRotationPlane rotatedAngle), this.MinimumRotatedAngleX, this.MaximumRotatedAngleX) return clampedRotatedAngle Here is the debug window As you can see, when the breakpoint was hit, rotatedAngle was 178.9446. To calculate clampedRotatedAngle, rotatedAngle is added to StartingAngleOnRotationPlane, supplied to a method called AngleNormaliser.BetweenNegativeAndPositive180(float input), and then clamped between MinimumRotatedAngleX (0) and MaximumRotatedAngleX (140). Here is the code for AngleNormaliser.BetweenNegativeAndPositive180(float input) public static float BetweenNegativeAndPositive180(float angleBetween0And360) while (angleBetween0And360 gt 180) angleBetween0And360 360 while (angleBetween0And360 lt 180) angleBetween0And360 360 return angleBetween0And360 Here is the debug window when AngleNormaliser.BetweenNegativeAndPositive180(float input) was invoked By the time the return statement was hit, the result 1.055389 should be returned and assigned to the variable clampedRotatedAngle, since 1.055389 is within the clamping range (0 140). However, that was not the case As you can see, clampedRotatedAngle was still zero. In fact, clampedRotatedAngle is always zero, regardless of what I feed into the Mathf.Clamp function How can I fix this?
|
0 |
How to create custom 3D "areas" at runtime I've been puzzled for a few days trying to solve this problem, so far with no results. On a map, currently a Terrain, I'd need to have some "areas" which can be controlled by a specific players. The shape of those areas can arbitrarily change during the course of the game, such as you add a marker in any point, and the area evolves (like a spline, say) to pass through that point too. The problem isn't drawing the boundary itself, of course, but having the GameObjects detecting the area they are in. Currently I have absolutely zero idea on how to make this exactly. I've thought about a nice approximation, which is splitting the terrain in fixed chunks, and having the player control them "chunk by chunk" every chunk can have its own collider, and that should be easy if not trivial. So the question is how to do it "properly", since I already have this workaround.
|
0 |
Auto key bones with controller helpers I have skinned and rigged a human character with IK FK and helper objects to control the position of the IK goals and the rotation of the bones. For example, the characters' left arm IK goal is parented to a point helper, to make it easier to select and move around and the arm IK solves accordingly. I have the skeleton (without the helpers) set up as an avatar in Unity and I want to use this rig to create and export animations to work with the avatar. I create animations by moving the helpers in Auto Key mode in 3DS Max, so that when the helpers move, their new transform details (pos, rot, scale) are recorded in key frames. My questions is this using Auto Key only records the transform of the helpers I'm moving, it does not record the bone transforms, even though they have been changed by moving the linked helpers. Is there any way to record bone positions using Auto Key with this rigging method, or do I have to select the affected bones every time a movement is made and use Set Key?
|
0 |
How to speed up script compilation? Is there a way to speed up script compile time when I change something in VS then click on Unity? It takes 15 seconds. Is this normal?
|
0 |
Why does the code in Unity affect objects differently? There are 2 objects made in a blender and imported into Unity. Eye of the Cyclops.blend Flask.blend The problem is that after using the code, which should create an object in the hand body area (I'm still working on it), one object is created far from the character. Example Everything is OK. It's not ok. Code PlayerInteraction using System.Collections using System.Collections.Generic using UnityEngine public class PlayerInteraction MonoBehaviour public GameObject target null public KeyCode interactKey public GameObject itemHolder private void Update() if (Input.GetKeyDown(interactKey)) if (target null) return FoodBox food target.GetComponent lt FoodBox gt () if (food ! null amp amp itemHolder null) food.Interact(this) TableBox table target.GetComponent lt TableBox gt () if (table ! null) table.Interact(itemHolder, this) public void SetItem(GameObject c) if (c ! null) Debug.Log(" !") itemHolder Instantiate(c, transform.position new Vector3(0f, 2.15f, 0.65f), Quaternion.Euler( 90f, 0f, 180f), transform) else Destroy(itemHolder) private void OnTriggerEnter(Collider col) if (target ! col.gameObject amp amp target ! null) return else target col.gameObject Debug.Log(" " target.name) private void OnTriggerExit(Collider col) if (col.gameObject target) target null TableBox using System.Collections using System.Collections.Generic using UnityEngine public class TableBox MonoBehaviour public GameObject itemHolder private void Start() if (itemHolder ! null) itemHolder Instantiate(itemHolder, transform.position new Vector3(0f, 1.9f, 0f), Quaternion.Euler( 90f, 45f, 0f),transform) Debug.Log(" !!") public void Interact(GameObject i, PlayerInteraction player) if ((i null itemHolder null)) player.SetItem(this.itemHolder) Destroy(this.itemHolder) Debug.Log(itemHolder) this.itemHolder i if (this.itemHolder ! null) this.itemHolder Instantiate(this.itemHolder, transform.position new Vector3(0f, 1.9f, 0f), Quaternion.Euler( 90f, 0f, 135f),transform) Debug.Log(" !") else return FoodBox using System.Collections using System.Collections.Generic using UnityEngine public class FoodBox MonoBehaviour public GameObject ingredient private Animator anim Use this for initialization void Start() anim GetComponent lt Animator gt () anim.SetBool("openFoodBox",false) public void Interact(PlayerInteraction player) anim.SetBool("openFoodBox", true) if (anim.GetBool("openFoodBox")) anim.Play("Opening") player.SetItem(ingredient) Debug.Log(" !") anim.SetBool("openFoodBox",false) There is also an assumption that this is due to the initial position of the models. Because for me, some models are stored normally vertically, and some lie horizontally. I also add the prefab inspector Eye of the Cyclops Flask
|
0 |
Lerp UI Color outside update method? I'm able to Lerp the color of a UI panel within the Update method. However I'd like to trigger behavior a single time when needed. If I put it in a method and call it it only changes for a brief time and doesn't fully complete. I could probably set a bool flag within the update method but that seems sloppy.
|
0 |
What's wrong with my food generating code? This script is intended to produce amount of (food) objects for the players over the network. What should happen is that when a player eats one food, another food object gets created in another random place. Somehow it doesn't do that. Here's the script. public class FoodManager Photon.MonoBehaviour SerializeField GameObject smallCirclePrefab SerializeField float widthOfBoard 100 SerializeField float heightOfBoard 100 SerializeField int amtOfSmallCircle 100 SerializeField int sizeOfCircle 5 Use this for initialization void Start() if(PhotonNetwork.isMasterClient) produceSmallCircle(amtOfSmallCircle) Update is called once per frame void Update() void produceSmallCircle(int n) Vector2 position GameObject circle float positionX, positionY int ratioOfSize 5 for (int i 0 i lt n i ) positionX Random.Range( widthOfBoard 2, widthOfBoard 2) positionY Random.Range( heightOfBoard 2, heightOfBoard 2) position new Vector3(positionX, positionY,0) circle PhotonNetwork.InstantiateSceneObject(smallCirclePrefab.name, position, transform.rotation, 0,null) as GameObject circle.transform.localScale new Vector3((float)sizeOfCircle ratioOfSize, (float)sizeOfCircle ratioOfSize, (float)sizeOfCircle ratioOfSize) and here's the other script using UnityEngine using System.Collections public class FoodCollision Photon.MonoBehaviour public static float amtOfIncreaseSpeed 1f public static float amtOfIncreaseHealth 1f public static float ratioOfSpeed 150.0f public static float increaseSize 0.001f PhotonView photonView BoxCollider2D boxCollider SpriteRenderer sp void Awake() photonView PhotonView.Get(this) boxCollider GetComponent lt BoxCollider2D gt () sp GetComponent lt SpriteRenderer gt () Use this for initialization void Start() Update is called once per frame void Update() public void DestroyGO() photonView.ownerId PhotonNetwork.player.ID boxCollider.enabled false sp.enabled false photonView.RPC("DestroyRPC", PhotonTargets.MasterClient) PunRPC void DestroyRPC() PhotonNetwork.Destroy(gameObject)
|
0 |
Unity 2D Current object force I'm working on a game with an entity firing a shot. This shot could destroy other entities as well as the entity who generated the shot. My first step was to apply a force to the rigidbody2D of the shot, but when my entity is too fast the shot destroy it (the speed does not match). I tried adding the speed to the force but the values mismatch by far (the force is a vector of like 150 magnitude, whereas the speed as a magnitude of 1). I wonder how one can achieve this, to add the current speed of the entity to the shot fired, and i wonder if there's any litterature concerning the way physics is actually handled in Unity, i find very little documentation on the Physics. Thanks.
|
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 |
Overriding the sprites in a Animation clip Right now we are in the process of adding seasonal content to our game. I would like to know of a way to override animation clips. Specifically I want to change the sprites being show at each key frame. Looking from the text of a animation clip I found the following m PPtrCurves curve time 0 value fileID 21300000, guid 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type 3 time 0.6 value fileID 21300000, guid ae9111d826eb24442b21523b30b748bd, type 3 time 0.6666667 value fileID 21300000, guid 88840e4f59c4a6040922d9b6eed3dec3, type 3 time 1.2333333 value fileID 21300000, guid 88840e4f59c4a6040922d9b6eed3dec3, type 3 time 2.0001667 value fileID 21300000, guid ae9111d826eb24442b21523b30b748bd, type 3 time 2.05 value fileID 21300000, guid 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type 3 time 3.1166666 value fileID 21300000, guid 502fc97a961e4424ea008c0e546c83ef, type 3 time 3.45 value fileID 21300000, guid 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type 3 attribute m Sprite This corresponds to the key frames and amount of sprites in the animation clip but I have no idea from where to get the data for the new sprites. I'm guessing the guid is a hashed path to the png files. can someone explain where to find this data so I can write myself a neat little parser to do the job?
|
0 |
Why does Unity use HLSL instead of GLSL? I am beginner in shader programming. I got my introduction (few minutes ago) to shader programming via Unity. I didn't know what HLSL was. So, I Googled and found this post Difference b w HLSL amp GLSL I can't understand one thing. Unity was initially developed for OSX amp introduced at WWDC. Also DirectX is windows only API amp HLSL is the shader programming language for DirectX. However, Unity3D for OSX is written in OpenGL. OpenGL uses a standard shader programming language called "GLSL". So, I'm confused how Unity3D uses HLSL on OSX amp why Unity didn't pick GLSL instead of HLSL. NOTE I might be wrong somewhere. So please correct if something is wrong as I told I'm a beginner
|
0 |
Smooth Camera Follow I am using a fixed static background. I have a gameobject(Current ref. image) which is moving with the help of waypoints. I have made camera to follow the Current. The camera is stuttering while moving. Can anyone help me to solve the camera stuttering and make it follow the Current smoothly? This is my code attached to camera following the star public class CameraController MonoBehaviour void Start () GameObject.FindGameObjectWithTag("OptionCamera").GetComponent lt Camera gt ().orthographicSize (20.0f Screen.width Screen.height 2.0f) void LateUpdate() if (GameObject.FindGameObjectWithTag ("Current") ! null) if (GameObject.FindGameObjectWithTag ("Current").GetComponent lt CurrentController gt ().Greenblast false amp amp GameObject.FindGameObjectWithTag ("Current").GetComponent lt CurrentController gt ().Redblast false) Vector3 pos GameObject.FindGameObjectWithTag ("Current").transform.position transform.position new Vector3 (transform.position.x, pos.y, transform.position.z)
|
0 |
Help with OnTriggerEntered Canvas UI This seems like it should be incredibly easy and I know there are other posts out there with a similar title, but I promise you I have looked at all of them. All I want is for my canvas that simply says "you win" to appear when I enter an invisible box collider that I have . My canvas is by default set to disabled. public class YouWin MonoBehaviour public Canvas myCanvas private void Start() myCanvas GetComponent lt Canvas gt () void OnTriggerEnter (Collision Collider) myCanvas.gameObject.SetActive(true) This script seems incredibly simple and straightforward, but for whatever reason, when I enter my box, nothing at all happens. Why might this be? What am I missing? As per an answer I also tried public class YouWin MonoBehaviour public GameObject canvas void OnTriggerEnter (Collider Collider) canvas.gameObject.SetActive(true) But had no luck with this either. I've been tinkering to no avail, can you please give me some suggestions?
|
0 |
Raycasting to AddForceAtPosition goes to the wrong direction I'm trying to get my coin object's Rigidbody to move whichever way it was swiped on by the user through RayCast void Awake() coinRigidBody coin.GetComponent lt Rigidbody gt () void Update() foreach (Touch touch in Input.touches) if (touch.phase TouchPhase.Began) firstTouchPos new Vector3(touch.position.x, touch.position.y, Camera.main.nearClipPlane) if (touch.phase TouchPhase.Moved) lastTouchPos new Vector3(touch.position.x, touch.position.y, Camera.main.farClipPlane) if (touch.phase TouchPhase.Ended) Vector3 firstTouchWorldPos Camera.main.ScreenToWorldPoint(firstTouchPos) Vector3 lastTouchWorldPos Camera.main.ScreenToWorldPoint(lastTouchPos) Vector3 diffWorldPos lastTouchWorldPos firstTouchWorldPos direction3D diffWorldPos.normalized power diffWorldPos.magnitude (force Time.deltaTime) Ray firstTouchRay Camera.main.ScreenPointToRay(firstTouchPos) Ray lastTouchRay Camera.main.ScreenPointToRay(lastTouchPos) RaycastHit hit Debug.DrawRay(firstTouchRay.origin, lastTouchRay.direction firstTouchRay.direction, Color.red, 50.0f) if (Physics.Raycast(firstTouchRay.origin, lastTouchRay.direction 100, out hit)) Vector3 hitLocation hit.point if (hit.collider.tag "Coin") projectedVector Vector3.ProjectOnPlane(direction3D, plane.normal) coinRigidBody.AddForceAtPosition(projectedVector power, hitLocation 5) throwCoinObject.throwWithForce(power, hitLocation, direction3D) The Code is working but my only problem is that it goes only in a certain direction? And it seems that direction is manipulated by how the camera is facing the objects. I just want it to hit the first touch origin then move to the direction the swipe was made. Help would be really appreciated
|
0 |
Why can't I use the operator ' ' with Vector3s? I am trying to get a rectangle to move between two positions which I refer to as positionA and positionB. Both are of type Vector3. The rectangle moves just fine. However, when it reaches positionB it does not move in the opposite direction, like it should. I went back into the code to take a look. I came to the conclusion that as the object moved, the if statements in the code missed the frame in which the rects position was equal to positionB. I decided to modify the code to reverse direction if the rects position is greater than or equal to positionB. My code is not too long, so I will display it below using UnityEngine using System.Collections public class Rectangle MonoBehaviour private Vector3 positionA new Vector3( 0.97f, 4.28f) Start position private Vector3 positionB new Vector3(11.87f, 4.28f) End position private Transform rect tfm private bool atPosA false, atPosB false public Vector2 speed new Vector2(1f, 0f) private void Start() rect tfm gameObject.GetComponent lt Transform gt () rect tfm.position positionA atPosA true private void Update() NOTE Infinite loops can cause Unity to crash Move() private void Move() if ( atPosA) rect tfm.Translate(speed Time.deltaTime) if ( rect tfm.position positionB) atPosA false atPosB true if ( atPosB) rect tfm.Translate( speed Time.deltaTime) if ( rect tfm.position positionA) atPosA true atPosB false When I changed it, however, it warned me of the following error message Operator cannot be applied to operands of type Vector3 and Vector3. This confuses me for two reasons first, both values are of the same data type. Second, using the comparison operator( ) on the two values works without error. Why can't I use the operator gt with Vector3s?
|
0 |
Corgi Engine Character glitches with "jump" animation on top of a ladder I'm new to Corgi Engine and Unity in general. I have an issue that I could find a way to resolve. I'm using CorgiEngine's quot RetroLadder quot prefab and extended quot Rectangle quot character with custom animations from quot MinimalLevel quot The problem is that when character finishes climbing the ladder, for a very short amount of time, jump animation appears. As in my case jump animation is very different from idle animation, this feels like an unpleasant glitch to me, so that's why I want to fix it. You can see it on the GIF below (at first I jump near the ladder to show how animation looks and then start climbing the ladder and on the top jump glitches) I checked some other demos (e.g. RetroVania, which uses some ladders there) and they also have this quot glitch quot with Corgi demo character, but as the character's idle and jump animations are not very different, it doesn't seem wrong (GIF below) I suspect that this glitch happens because quot CharacterLadder.cs quot script disables gravity during ladder climbing and then enables it back which triggers fall of the character Do you think it's possible to workaround it somehow? Thanks!
|
0 |
All Materials are pink (Unity URP) Version Unity 2020.2.0f1 I started my project with Universal render pipeline template but I don't know why all materials are pink. i even tried to upgrading but nothing happened. This error was coming after upgrading And when I am creating new materials then I still getting pink materials and I am also not able to upgrade them
|
0 |
Match 3 should pieces store their location in the matrix? I'm making a match 3 game. I have a TileManager script which stores all the tiles in a matrix, it's a singleton and it handles tile swapping and basicly everything regarding the management of tiles. I have a variable called selectedTile. I have a method called SwapSelected which swaps the currently selected tile with the one you just clicked on. As pieces don't know their location in the matrix I can only loop through the whole thing to find them but it feels extremly stupid I just feel like there's gotta be a better way. If pieces stored their location and I kept that updated all the time that'd feel stupid too. What could I do to make this method work nicer and more optimalized? Is there a way or there is no problem with how I do it? public void SwapSelected(Tile tileToSwap) Vector3 tempPos selectedTile.transform.position selectedTile.transform.position tileToSwap.transform.position tileToSwap.transform.position tempPos Vector2Int tileToSwapPosition new Vector2Int( 1, 1) Vector2Int selectedTilePosition new Vector2Int( 1, 1) OPTIMALIZE!!!!!!!!!!!!!!!!!!!!!!!!!!!!! for (int x 0 x lt tileMap.GetLength(0) x ) for (int y 0 y lt tileMap.GetLength(1) y ) if ( tileMap x, y tileToSwap) tileToSwapPosition new Vector2Int(x, y) if ( tileMap x, y selectedTile) selectedTilePosition new Vector2Int(x, y) tileMap selectedTilePosition.x, selectedTilePosition.y tileToSwap tileMap tileToSwapPosition.x, tileToSwapPosition.y selectedTile UpdateTileName(tileToSwap) UpdateTileName(selectedTile)
|
0 |
The more appropriate way to find GameObject in the scene Which way is the more appropriate to find GameObject in the scene. I know that GameObject.FindGameObjectWithTag is faster than GameObject.Find but i wondering whether FindGameObjectWithTag is better solution than this public GameObject someObject public void SelectObject() someObject.SetActive(true) or whatever i want
|
0 |
In Unity, how can I render borders of provinces from a colored province map in a grand strategy game? I am kind of a beginner of Unity and I am trying do work on a grand strategy game. I already have a province map, colored by unique rgba for each province, looks like something below I know that the province map is kind of a look up map for province id. But when I obverse the paradox strategy games, I notice that they have render borders differently for the provinces and nations. For example, in the CK3, the Baron collars are separated with dotted lines, and the kingdoms are separated with enhanced yellow lines. I thought they have some other maps or files containing those information, so I went to read their dev diary, and I find that all province shape information are stored in the province map. So, my question is Is there any way in Unity3D to create those different borders with some shader and some province map such those given above? I think what I wish to accomplish is something as this link Render border on 3D map Which is
|
0 |
Translating object from y to y smoothly in Unity 2D I am trying to make a game that has an object on screen, which moves from one Y coordinate to another. Right now, I do it through translations, but that does it instantly. I want to do this as a kind of animation, where it transitions smoothly from one Y coordinate to another. What should I do? Here is an image of what I'm talking about
|
0 |
Bold black bar on right side of game in Unity (Android) I am trying to create an endless runner. I have already created a system to generate infinite backgrounds from an array of some. However, on running the game, I get huge black bar on the right side of the screen, both on PC and on Android phone. Here are the screenshots One more thing, on Android, it doesn't even display the left side of the game, i.e, where the character is. It looks like the things are displaced towards left. Also, the game is a scrolling on and everything is scrolling but behind that bar. It just doesn't go. I hope I can get some help. Ask me if you need any piece of code. EDIT "CameraFollow" script using UnityEngine using System.Collections public class CameraFollow MonoBehaviour public GameObject targetObject private float distanceToTarget Use this for initialization void Start () distanceToTarget transform.position.x targetObject.transform.position.x Update is called once per frame void Update () float targetObjectX targetObject.transform.position.x Vector3 newCameraPosition transform.position newCameraPosition.x targetObjectX distanceToTarget transform.position newCameraPosition My "GeneratorScript" using UnityEngine using System.Collections using System.Collections.Generic public class GeneratorScript MonoBehaviour public GameObject availableRooms public List lt GameObject gt currentRooms private float screenWidthInPoints Use this for initialization void Start () float height 0.0f Camera.main.orthographicSize screenWidthInPoints height (Camera.main.targetDisplay) Update is called once per frame void Update () void FixedUpdate() GenerateRoomIfRequred () void AddRoom(float farhtestRoomEndX) int randomRoomIndex Random.Range (0, availableRooms.Length) GameObject room (GameObject)Instantiate (availableRooms randomRoomIndex ) float roomWidth room.transform.FindChild ("floor").localScale.x float roomCenter farhtestRoomEndX roomWidth 3.0f room.transform.position new Vector3 (roomCenter, 0, 0) currentRooms.Add (room) void GenerateRoomIfRequred() 1 List lt GameObject gt roomsToRemove new List lt GameObject gt () 2 bool addRooms true 3 float playerX transform.position.x 4 float removeRoomX playerX screenWidthInPoints 5 float addRoomX playerX screenWidthInPoints 6 float farhtestRoomEndX 0 foreach(var room in currentRooms) 7 float roomWidth room.transform.FindChild("floor").localScale.x float roomStartX room.transform.position.x roomWidth 6.0f float roomEndX roomStartX (roomWidth 13.0f) 8 if (roomStartX gt addRoomX) addRooms false 9 if (roomEndX lt removeRoomX) roomsToRemove.Add(room) 10 farhtestRoomEndX Mathf.Max(farhtestRoomEndX, roomEndX) 11 foreach(var room in roomsToRemove) currentRooms.Remove(room) Destroy(room) 12 if (addRooms) AddRoom(farhtestRoomEndX) (I tried playing with the numbers on GeneratorScript, but nothing seemed to help.
|
0 |
What is the purpose of the Allocation Callstacks button in Unity's Profile window? I have an idea of what this button does, but I cannot find any specific information in the documentation. What information does this button add to the profiling data? How can I see this extra information?
|
0 |
Make a glass cup look like it's full of water I've been struggling to figure out a way to make a glass cup full of water, and since the cup is made of glass a plane on the top of the glasse won't really do it, so how can i go around making the glass looks like it's full of water?
|
0 |
CrossPlatformInput Prefabs Button handler to move? I am currently trying to put two buttons on my UI that move a character left and right if touched down (Held). I would like to use the cross platform input, and would like the buttons to change the value of the Horizontal axis as my "A" and "D" keys would... And my code for moving my character is as follows private void Update() isGrounded Physics2D.OverlapCircle(groundChecker.position, .15f, groundLayer) float move CrossPlatformInputManager.GetAxis("Horizontal") moveSpeed playerRB.velocity new Vector2(move, playerRB.velocity.y)
|
0 |
I'm trying to write a randomly patrolling AI for my 2D Platformer I'm trying to write a randomly patrolling AI for my 2D Platformer. The AI already has a ground checker function which checks if there are tiles nearby or not. What I want to do is randomize its actions and create an illusion of a somewhat quot sentient quot enemy. What I tried to create below is using the built in RNG to make the enemy either jump, change direction, or keep moving. The problem is, it doesn't seem to work properly. The enemy just jumps every second I want it to change behaviour. The change direction functions, however, don't occur as frequently. I need to know what I've done wrong here. Thanks. void Update() RNG behaviour Random.Range(0,3) jumpSpeed Random.Range(1,5) clock timer Time.deltaTime time private float waitTime 2.0f private float timer 0.0f void MoveRandomizer() if((Mathf.Round(timer waitTime)) 0) if(behaviour 0) movingRight false if(behaviour 1) movingRight true if(behaviour 2) rb.velocity new Vector2(rb.velocity.x, jumpSpeed)
|
0 |
How can I use different fonts for different objects in Unity? In Unity 3.5, I have a font that is strangely linked to four game objects. I want to put separate fonts on each object. In the Inspector, when I click on the circle icon next to the "Text" attribute, I can select a font. But, then it changes the font on the other three objects as well. I was hoping Unity would have something like a material ID from 3DS Max. If I could put a new material ID on the other objects, hopefully I could assign a new font to the text mesh. Regardless, is there a way to assign a different font to each of my objects?
|
0 |
How to automatically scroll vertical text? I've a GUI, and a panel with a Text control. I simply want to do an automatic vertical scroll effect (circular). Problems I've to solve How to identify if text on my textbox is "too much" and overflow vertical How to move Text and not textbox transform Y Can you help me find the correct solution ? Thanks
|
0 |
Unity3D Sudden lighting change in a scene Sorry if this is a duplicate question, but I have no idea what this would be considered. Hello, I have recently been creating an FPS game, but while researching some things on the internet, the lighting changes within only one scene. I actually want to keep this change, but I am not sure what changed to make it look like this. It unusually changed from this To this I want to keep the new one, but have this same lighting effect on a different scene, however, I am not sure what can cause this change. I have searched high and low for anything that could've changed, but I couldn't find anything. Any help is greatly appreciated. Thanks!
|
0 |
How can I make all the objects to move between the waypoints? using System.Collections using System.Collections.Generic using UnityEngine public class MovementSpeedController MonoBehaviour public List lt Transform gt objectsToMove new List lt Transform gt () public List lt Vector3 gt positions new List lt Vector3 gt () public int amountOfPositions 30 public int minRandRange, maxRandRange public bool randomPositions false public bool generateNewPositions false public float duration 5f public bool pingPong false private void Start() if (generateNewPositions (positions.Count 0 amp amp amountOfPositions gt 0)) GeneratePositions() StartCoroutine(MoveBetweenPositions(duration)) private void GeneratePositions() for (int i 0 i lt amountOfPositions i ) if (randomPositions) var randPosX UnityEngine.Random.Range(minRandRange, maxRandRange) var randPosY UnityEngine.Random.Range(minRandRange, maxRandRange) var randPosZ UnityEngine.Random.Range(minRandRange, maxRandRange) positions.Add(new Vector3(randPosX, randPosY, randPosZ)) else positions.Add(new Vector3(i, i, i)) IEnumerator MoveBetweenPositions(float duration) for (int i 0 i lt positions.Count i ) float time 0 Vector3 startPosition objectsToMove 0 .position while (time lt duration) objectsToMove 0 .position Vector3.Lerp(startPosition, positions i , time duration) time Time.deltaTime yield return null objectsToMove 0 .position positions i Now only the first object in objectsToMove is moving between the waypoints but I need all of the elements of objectsToMove to move between the waypoints. If I try this objectsToMove i .position Vector3.Lerp(startPosition, positions i , time duration) I will let out of bound index exception because the size of objectsToMove is not the same the size of positions i
|
0 |
Unity Texture huge areas with decals I'm using 1024 textures for smaller buildings and 2048 for larger one's. Basic workflow 1) Unwrap in Blender 2) Smack a concrete texture on it 3) paint some dirt here and there. Result This only works for small buildings. Here is an example from Battlefield 2, they put a small 128x128 brick texture and tiled it across the entire building and added Dirt on top of that. Is there a way to do this using Unity or do I have to create my own custom shaders? (God forbid)
|
0 |
How does layer based collision affect performance In Unity3D, and others, there are Layer Based Collision System which makes collisions only happen between specified Layers. It defaults to all layers colliding with all others. Does making use of these setting decrease performance, or increase performance? I could imagine it decreases it if every potential collision had to be checked for it's layer. Or are those collisions completely bypassed?
|
0 |
What is the cause of this lighting artifact on my dynamic terrain mesh? I am generating my own terrain mesh in Unity, using pseudo random noise to determine the height. I construct the mesh using quads, each quad is composed of two triangles. All seems to be going well, except the terrain does not look right the quads are very visible. You can see the outline of them on the surface, but I haven't seen this effect before elsewhere. I feel that something is wrong with either my normals or my UV's. I am using just one white directional light. Dynamic Terrain http www.spannerworx.com images terrain.png I thought the issue was with the normals, so I stopped calling RecalculateNormals and manually calculated the normal for every vertex using the averaged normal of the sum of each triangle touching that vertex. This was a lot of effort, but made no effect and ended up looking just the same. Has anyone else seen this dynamic mesh effect before and maybe make some suggestions as to how I could try resolve this? Just to clarify, I am already generating the triangles myself, two per quad. I do it like this for (int t 0 t lt quadCount t ) int x t (Samples 1) int z t (Samples 1) Calculate quad corner indexes int indexBR CalculateIndex(x 1, z) int indexBL CalculateIndex(x, z) int indexTL CalculateIndex(x, z 1) int indexTR CalculateIndex(x 1, z 1) Assign indexes for triangles Triangle 1 triangles 6 t 0 indexBR triangles 6 t 1 indexBL triangles 6 t 2 indexTL Triangle 2 triangles 6 t 3 indexBR triangles 6 t 4 indexTL triangles 6 t 5 indexTR Normals stuff...
|
0 |
Quality deterioration on a device I am using Unity. When I try the game out in the IDE everything looks pretty good But when I am trying to play the same game on a device the quality becomes a great deal worse and you can see it for yourself I am using Xiame Redmi 4X and I do not think that it is because of device. So, how can I fix it? How can I preserve the quality? I would like to try out this solution, but there is no Android settings in my Inspector for quality I would like to preserve at least colors. And here are setting for my player sprites
|
0 |
Unity plane that is normal to Z axis I want to create a plane that will be normal to the Z axis, but I am having difficulty visualizing what rotation it needs to have. I want to have a top down view upon the plane such that I can use the X and Y coordinate system for position, and the Z axis for height. It seems intuitive for me to point the camera in the same rotation as this plane, and give it an orthogonal view and a positive Z value (and set gravity to have a negative Z value), but I seem to be fighting against the grain and running into more issues than I should be, so I would like to ask what rotations I should be using for this. What rotation should I use for the plane? can the camera share the same rotation? (assuming I want the top to be y and the right to be x as seen from the camera.
|
0 |
Dynamic rigidbody and kinetic with simplectic integration for trajectories 2d Okay, I have the following situation I want to launch a GameObject into orbit of a planet and using the dynamic rigidbody everything is working as I want. I simulate gravity and as it hits the surface again it bounces around nicely using the Box2D system. However, I want to calculate the trajectory and visualise it on screen. I thought about it and came up with two solutions, but I run into some problems 1 Simplectic integration for the trajectory I simulate the trajectory using simplectic integration. However, as can be expected, the results are different for the dynamic rigidbody movement and the simplectic integration. This became very obvious when I launched two identical objects and simulated one dynamically and the other one simplectic. The code is as follows (all in FixedUpdate) if (rb.isKinematic) velocity forces mass Time.fixedDeltaTime Vector2 newPosition (Vector2)transform.position velocity Time.fixedDeltaTime rb.MovePosition(newPosition) else rb.AddForce(forces) The simplectic kinematic one is slower than the dynamic one. Weird. 2 Use Physics2D.simulate According to https docs.unity3d.com ScriptReference Physics2D.Simulate.html I can simulate it via code. However, this means that I have to set everything that is not to be simulated as disabled and simulate it for a given amount of time to calculate the trajectory. Not really what I was looking for, because I want to have a live trajectory update 3 Full simplectic That seems to be easy, but I want to have realistic collisions and bounces. Don't want to reinvent the wheel when Box2D should be sufficient. 4 Simplectic for simple movement, dynamic at collision This seems to be the logical candidate, but don't know if it is clever. Had no time to implement this yet, but should not be that difficult. Feels a bit icky... So, question? My questions are Can I reduce or eliminate the offset from solution 1? If not, what whould be the most logical solution and or am I missing one? EDIT It was asked how I calculate the forces. This is simply Newton's law with squared distance public Vector2 CalculateForce(GameObject a, GameObject b) AUComponent is an interface type I have... not very special in itself. float mA a.GetComponent lt AUComponent gt ().Mass float mB b.GetComponent lt AUComponent gt ().Mass Vector2 r b.transform.position a.transform.position return gravityConstant mA mB r.sqrMagnitude r.normalized However, the ever increasing offset is also happening with a constant force applied in a direction. The masses of the AUComponent are equal to those of the RigidBody.
|
0 |
How can i make fade in out of the alpha color of a material from black to none black? This is script is attached to a black plane. I have a plane and i added to it a material and the plane is in black. When running the game the alpha color of the plane material is changing slowly. The script is working it's getting slowly from dark black to none black. But i want to make some changes It's not my script i took it from the youtube and did some changes the first one converted from js to c second added the fade bool variable. First of all i don't see any meaning setting the variable timer to 10 at the top. Any ideas what is the point ? Second is how can i check when the alpha color value is high enough to do some stuff Enabled true the fpc again. Once it's not black again the fpc is still enabled false. If i want when the alpha color value reached it's max to make automatic fade back to black Now i'm using manual fade bool variable but i wonder how to do it automatic fade in out. using System.Collections using System.Collections.Generic using UnityEngine using UnityStandardAssets.Characters.FirstPerson public class FadeScript MonoBehaviour public float timer 10.0f public FirstPersonController fpc public bool fade true Use this for initialization void Start() Color tempcolor GetComponent lt Renderer gt ().material.color tempcolor.a 1f GetComponent lt Renderer gt ().material.color tempcolor fpc.enabled false Update is called once per frame void Update() timer Time.deltaTime if (timer gt 0) Color tempcolor GetComponent lt Renderer gt ().material.color if (fade true) tempcolor.a 0.1f Time.deltaTime else tempcolor.a 0.1f Time.deltaTime GetComponent lt Renderer gt ().material.color tempcolor
|
0 |
Raycast only specific layer and ignore other collider I am willing to raycast specific layer and ignore other layers no matters its colider is above to my navPoint layer object? int specificLayerMask LayerMask.GetMask("NavPoint") raycast only this layer ignore others if (Physics.Raycast(raycastObject.transform.position, fwd, out objectHit, specificLayerMask)) 50 the above code raycasting to navpoint layer but unable to bypass other layers colliders. is there any way available to ignore all other collider and raycast to desired layer only no matter colliders are behind any other collider
|
0 |
Clipping speed when turning without using aggressive drag I have a Unity project in which I want to control a player in a similar way to Source games, and so far I am clipping each input to the speed in the player's coordinates, by using transform.InverseTransformDirection( GetComponent lt Rigidbody gt ().velocity ) after which I pass each of the player's input vector direction through this function private float FLSMF ( float aInputVelocity, float aMaximumVelocityOnAxis, float aSpeedOnAxis ) if ( Mod( aSpeedOnAxis ) gt aMaximumVelocityOnAxis ) if( Sign( aSpeedOnAxis ) ! Sign ( aInputVelocity ) ) if ( Mod( aSpeedOnAxis aInputVelocity ) gt aMaximumVelocityOnAxis ) return Sign ( aInputVelocity ) ( aMaximumVelocityOnAxis Mod( aSpeedOnAxis ) ) return aInputVelocity return 0 if( Mod( aSpeedOnAxis aInputVelocity ) gt aMaximumVelocityOnAxis ) return Sign( aInputVelocity ) ( aMaximumVelocityOnAxis Mod( aSpeedOnAxis ) ) return aInputVelocity There is only one problem whenever I turn and strafe and walk forwards or backwards, the speed increases dramatically. I tried solving it by comparing each processed velocity axis to the velocity rotated by the difference in the rotations between the last 2 FixedUpdate's. So far nothing worked, aside from driving the drag factor through the roof. My best guess is that when turning, the unclipped X axis of the vector bleeds into the Z axis when turning, which can't add anything, but cant stop the X axis from interfering because the forward key is pressed. There is no issue when only one of the input axis are used, the speed remaining consistent when turning. I tried to implement this function especially so I don't have to use any drag, to allow the player to be flung by other things, like grapples and explosions (this issue is present irrespective of said external factors). If you want to, I will share the entire code, but it's messy and I don't think it would help. Any ideas how to solve it? Edit yes, I have normalized the input vector. The speed increases to more than triple of the maximum, in as few as 2 turns.
|
0 |
How can I find a bounding box for a bezier curve I am using the code from the question Adding functionality to make individual anchor points of bezier continuous or non continuous to create bezier curves (I added a line renderer). How can I find the center of the curve for multiple cubic B zier segments, where the centre of a bounding box is the centre of the curve (as in the image below)?
|
0 |
Moving object along X and Z plane relative to camera Using keys, I'm trying to move a cursor object across the X and Z plane, keeping it relative to a camera that I can orbit around the playfield. This is my code so far, and apologies...I'm about 2 days into learning Unity. This code is on my cursor object. if (Input.GetAxis("Horizontal") gt 0f) transform.position transform.position Camera.main.transform.right moveSpd Time.deltaTime if (Input.GetAxis("Horizontal") lt 0f) transform.position transform.position Camera.main.transform.right moveSpd Time.deltaTime if (Input.GetAxis("Vertical") lt 0f) Vector3 dir Camera.main.transform.forward dir.y 0.01f dir.Normalize() transform.position transform.position dir (moveSpd 1.5f) Time.deltaTime if (Input.GetAxis("Vertical") gt 0f) Vector3 dir Camera.main.transform.forward dir.y 0.01f dir.Normalize() transform.position transform.position dir (moveSpd 1.5f) Time.deltaTime transform.position new Vector3(transform.position.x, 0.01f, transform.position.z) It works, but the vertical axis affects the Y plane so I had to do another transform at the end. What is the best way of doing this? I'd also like the cursor to snap to grid co ords. I've tried turning them to int but it doesn't do what I want.
|
0 |
Convert Minimap render texture to 3d space position I am using Render Texture to make a Mini Map it is working fine. Now I want world space position from render texture click point. Is there any way available that I get the world space position from the render texture's specific click point? If I click somewhere in render texture then, how can I get that point in 3D world space? For example, I click a car object on render texture How can I highlight or get it in 3D world space.? Update Actual Scenario is One Main Camera Rendering the Scene. NGUI Camera Rendering the GUI. That GUI contains the Render Texture(minimap) which rendering the scene on texture using GUI Camera. Now how can I get 3D position from 2D render texture!
|
0 |
Google Admob GDPR compliance Unity I have created a unity game that uses admob to show only rewarded video ads and there are no banner interstitial ads in my game. Is it mandatory to take user consent (for EU countries) for showing the rewarded ads and if so how do I go about implementing it. I followed some online tutorials to implement admob ads but there was no mention of gdpr in any of those. Can someone please help?
|
0 |
Drawing a 1 pixel thick line in Unity I'm trying to get a cross at the center of the screen (Two lines will do as well). I have a 2048x2048 Texture which I have thrown into a canvas. Filtering is set to point. The image is set to be in the middle of the screen no matter the resolution. The image is set to 2048x2048 no matter the screen resolution which works as well. However when I change the Screen Resolution I get results like the following, no matter what I do, the line refuses to stay at the same thickness. When I enable Bilinear filtering the lines constantly fade and thicken. This is what I get when I use a 16x16 image EDIT i tried using a black square and setting its width to 1 and height to 2048, and another one with width to 2048 and height to 1. The result i got is not what i expected Can someone help me to fix this please?
|
0 |
Most efficient way to get the world position of the 8 vertexes of a Box Collider (C ) What I am looking for is the most efficient way to get the world position of the 8 vertexes of the Box Collider of a freely rotated Gameobject. I cannot use collider.bounds since object is rotated, not axis aligned. As for the framework I am working within, it's Unity 5 with C . Would you know how could I achieve that? Thanks in advance.
|
0 |
The camera does not capture movements in z axis I want to make a simple drag and drop card in Unity, where the card pops up a bit towards the screen when the drag begins (lifting effect), and then drops down back on the table when the drag ends. My script looks like this public class Draggable MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler void IBeginDragHandler.OnBeginDrag(PointerEventData eventData) this.transform.position new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z 10) public void OnDrag(PointerEventData eventData) this.transform.position new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10) public void OnEndDrag(PointerEventData eventData) this.transform.position new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z 10) The card is an image, and it is child of the canvas. The render mode for the canvas is Screen Space Overlay. The drag works correctly, but I cannot capture the movements in the z axis. It does capture the movements in the z axis when I change the render mode. However, then the card is too far away in the z axis, and it moves with an offset with respect to the mouse pointer. As far as I understood, I need to do something about realtive distances, but I how can I force the mouse pointer to be on z 0 plane.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.