_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Moving character controller on twisted track I am trying to move a ball using Unity's character controller component. I want to move the ball along the twisted track so that it can go upside down. Below is the video of the problem when moving using Unity's Character Controller https gfycat.com dismalaridjoey I want the ball to move upside down along the twisted track. I have the following questions What kind of modifications are required to achieve this using a character controller? Which other methods (physics or splines) can be used to implement such ball movement? I am flexible to switch the appraoch. I would appreciate any suggestions and thoughts on this topic. Thank you.
|
0 |
pause Menu only working in one scene and not in others Hi I'm working on a game for a school project but I'm still pretty new at game dev, I decided to add a pause menu to my game but for some reason, it only works in one of the scenes in unity, and I can't tell why it won't work on any of the other ones Here is a video showing the problem https youtu.be 28fD9UEtfpg and here is my script just in case using System.Collections using System.Collections.Generic using UnityEngine public class PauseMenu MonoBehaviour public static bool GameIsPaused false public GameObject PauseMenuUI Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.Escape)) if (GameIsPaused) Resume() else Pause() public void Resume() PauseMenuUI.SetActive(false) Time.timeScale 1f GameIsPaused false Cursor.lockState CursorLockMode.Locked Cursor.visible false void Pause() PauseMenuUI.SetActive(true) Time.timeScale 0f GameIsPaused true Cursor.lockState CursorLockMode.None Cursor.visible true
|
0 |
Better way of handling the relation between Bullet and Enemy I was wondering how should I design this relation in terms of "better OOP"? Should I have a Singleton EnemyManager which contains a list of enemies (EnemyList) then Bullets can access the EnemyList to check for collision? Or should I just pass EnemyManager as a reference to each Bullet so Bullets can still access the EnemyList but not in a Singleton way? Or is there any other better ways of doing? Please advise.
|
0 |
Alternative solutions to applying an overly large and detailed texture to a mesh I have a very large spherical mesh in my Unity scene (the earth), to which one very large texture is applied (a map of the earth). Now it just so happens that Unity's max texture size (8192 pixels I believe) is not enough to capture the details I need on this huge mesh. What's the proper way to deal with this situation in Unity? That is, not only overriding the 8192 pixels limitations (although that would be nice as a temporary solution), but also making sure the overhead won't become unbearable... Is there a way to dynamically stream higher quality sections of textures as the camera gets closer to that specific part of the mesh? Additionally, I see the Granite add on (http graphinesoftware.com products granite for unity) seems to do just this (if I understood it well), but it's only for Windows, and I'm developing on a Mac. Is there any other adding out there?
|
0 |
Data structure for objects in a galaxy of star systems I'm having some difficulty coming up with the appropriate data structure to use for a game. I'm aiming for a galaxy view with tens of thousands of visitable star systems. Structure Hierarchically, each star system can contain one or more of the following Planets and their moons Asteroid Belts Megastructures and their moons sub structures All of the above can have quot points of interest quot POI eg a station in low orbit, a surface resource node, a docking bay. Usage I don't particularly care about physical location within a system beyond knowing its order in the hierarchy (I'll be showing a list of locations, rather than trying to render them in 3D space). So I can treat all objects within a system as located at the star for the pursposes of calculation. I do, however, need a way to specify routes from any Planet AsteroidBelt Moon Megastructure POI to any other. I also need to be able to search for other locations meeting certain criteria both to offer as destinations in the UI and to handle rendering . Each type of location will have some unique properties (Asteroid belts have resource distributions, for example whereas planets ave atmospheres) but they also have lots of common properties (inventory, owner, comms network node id, etc). Ideas so far Obviously, with the numbers I'm considering I need to take a sparse lazy generated approach. Currently the galaxy is built entirely in the GPU and stars are only presented to the CPU when the user first clicks on them. That lends itself nicely to a hierarchical data structure with a load on first access approach. Click on a star and it's added to the list, so the name is saved. Scan visit it and I'll generate the system contents. Unfortunately, I also need to be able to search across all generated locations efficiently (given an ID, find the star system coordinates, find planets with an atmosphere like X, find any location with X in its inventory) in a potentially huge search space. That doesn't align with recursively walking up down trees. I considered using a heirarchy and manually maintaining a number of separate indices to speed up searching. It's doable but a pain and error prone. It also feels like one of those solutions where I'm going to keep finding one more type of query I need to support and before long I'm trying to implement a minimal database. Speaking of which I also need to persist this data at some point. Currently I'm serializing to a densely packed binary blob. So... I took a step back and wondered whether I should actually use a database. I can see the benefits of using something like SQLite which I could bundle with the game and would handle persistence, indices, and the rest. Db? After spending a couple of days implementing the basics, I can see this is going to be quite a long and involved process. None of the friendly tooling works well in Unity, so I can't take advantage of entity framework w code first, nor nice Linq To Sqlite predicate handling. Even worse, most of the libraries to work with EF are tightly coupled to windows. EF Core seems like an option but I haven't been able to get it working in Unity (I need to do some assembly version mapping but as Unity overwrites the project file regularly and doesn't seem to support this itself, I think it's a losing battle). So I've headed down the route of implementing a data layer that generates SQL as needed. I can do that, but it opens up a huge can of worms in terms of manually maintaining the DB schema. I'm going to have to start tracking a DB version and bundling migration scripts with any update patch. It's a whole new maintenance burden. Question So... What am I missing? What's the elegant way to store a sparse hierarchy of data whilst still supporting flexible search across disparate object types that just happen to have a lot of common properties?
|
0 |
How to make an object covers a specific distance before moving in other direction for same distance? Suppose there is a small tile and I want an object to move on x axis on that tile back and forth. How can I make that object in that specific tile. My code is Rigidbody2D rb Start is called before the first frame update void Start() rb GetComponent lt Rigidbody2D gt () Update is called once per frame void Update() rb.velocity new Vector2( 3f, 0) As of now object moves left but I want it to start moving right and not go of the tile.
|
0 |
One side of every object is black I'm trying to make a driving game in Unity, but recently have been having lighting issues. When I was first building it, the lighting worked fine. However, recently, one side of everything (the indirect lighting side) has turned black. Here's an image of the issue. I've tried changing my lighting settings, but can't seem to fix it. Here are my lighting settings. What can I do to fix this? (I am using Unity 2017.2.0f3)
|
0 |
IndexOutOfRangeException on array of transform prefabs in Unity I have a public array of length 9 containing prefabs I'm using as position references for a moving object. The start function finds the transform.position of the appropriate transform in the array and makes it the target for a Vector3.MoveTowards() function that is called every update. I have an exception for the start function, but the object moves fine. If I print the length of the array on every update, It shows zero every other frame, and 9 otherwise. There's nothing in the script changing the array, how is this happening? I'm using the Linux build of Unity.
|
0 |
What determines the hit detection ordering for graphic elements in Unity (2d game)? I have a bunch of overlapping buttons spread across several UI Canvases. The default mouse behaviour only registers hover click events with one of the overlapping buttons, which is ideal for my project. The problem is the order of which button gets activated, is not tied to the Layer it is on or the Sorting Layer the item is on. I cannot seem to control which button is the top button that gets activated. Using a RaycastAll() function returns the name of all buttons on any given point, and reflects the problem that for some reason, the buttons are arbitrarily ordered. How do you control the order in which buttons are registered by the mouse?
|
0 |
How do I account for the velocity difference between a ship and it's fired projectile? In my project, I have a ship that moves and increases it's movement speed with respect to time and how long the acceleration button is being pushed(just like the way a real life car works), now as expected, the ship fires projectiles when I press the fire button. The problem here, is that at a point in the game, the ship reaches it's highest speed terminal velocity, and now it's faster than the projectile it fired which is not what I want, so, how do I create a realistic projectile movement based on the ship's velocity? This is so that if the projectile is fired when the ship is moving slowly through the game scene, it doesn't move so fast that we can't see it travelling in the forward direction, and at the same time if it is fired when the ship is moving at top speeds, the ship is not seen to be faster than or as fast as the projectile's speed. I want to keep the code as optimized as possible, so I am using this line for the projectile's movement public float velocity 100f void Update() transform.position transform.forward Time.deltaTime velocity
|
0 |
Elastically Object movement in unity3d I want to move an object towards the destination elastically. Currently I am using Vector3.Lerp it working to move the object, start with high speed and reached at destination with low speed but missing elastic effects. float i 50, t 0 while (t lt 1) t Time.deltaTime i transform.position Vector3.Lerp(transform.position, newPostionAtDistance, t) transform.LookAt(targetFollow.transform) if (transform.position.ToString() newPostionAtDistance.ToString()) StartCoroutine(CamElasticMoveBackEffetcts()) Debug.LogWarning("Object reached to the point.") yield break smoothTime Time.deltaTime yield return 0 i
|
0 |
Reverse Movie in Unity 5 guys! Is it possible to reverse video or apply a rewind in Unity 5? I searched in the web but could not find the solution.
|
0 |
Raycasting from an object to the center of the screen (crosshair) without clipping through objects Am trying to learn about Raycasting, and I thought I would start with something simple, and that was a laser that would come out of an object (think laser pointer in your hand) and always go to the crosshair. Using ViewportToWorldPoint I found it easy to cast a ray from the center of the camera, but this had an issue as you can see in this GIF below. The line would clip through because the ray was coming from the center, not off to the side where the laser pointer would be. Am not sure how to solve this. void Update() Vector3 ray Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0f)) line.SetPosition(0, transform.position) RaycastHit hit if(Physics.Raycast(ray, Camera.main.transform.forward, out hit, raylength)) if(hit.collider ! null) line.SetPosition(1, hit.point) else Vector3 pos line.GetPosition(0) line.SetPosition(1, ray (Camera.main.transform.forward raylength)) The closest thing I could find that I am trying to replicate for this exercise is the No Man's Sky mining tool
|
0 |
Roatating a Game Object downward In my game I have a rocket which is traveling horizontally across the screen. What I am trying to do is when the player runs out of fuel, the rockets engine stops (already coded) and then the rocket will slowly rotate to point at an almost 45 degree angle and fall down off the screen as gravity takes its affect. How do I do this?
|
0 |
How to approach debugging of java.lang.NullPointerException in android build of unity app? We are getting an obscure java.lang.NullPointerException when building a Unity app for android. There's not much information here that I can trace back to our code. Does anyone have advice about how to approach debug this? All I have to go on at the moment are logCat logs Uncaught exception thrown by finalizer java.lang.NullPointerException Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference at java.lang.reflect.Proxy.getInvocationHandler(Proxy.java 891) at bitter.jnibridge.JNIBridge.disableInterfaceProxy(Unknown Source 0) at bitter.jnibridge.JNIBridge.delete(Native Method) at bitter.jnibridge.JNIBridge a.finalize(Unknown Source 15) at java.lang.Daemons FinalizerDaemon.doFinalize(Daemons.java 250) at java.lang.Daemons FinalizerDaemon.runInternal(Daemons.java 237) at java.lang.Daemons Daemon.run(Daemons.java 103) at java.lang.Thread.run(Thread.java 764) (Unity version 2018.1.0b10)
|
0 |
Box collider rigid body eventually moves through static collider I found this question, but I'm not sure if it applies to my problem. I'm hacking together a Pong style game, and my problem is with the walls (box collider, no rigid body) not completely stopping movement of the player paddle (box collider, yes rigid body.) Sufficiently fast mouse movement eventually moves the paddle through the wall. There is initial resistance, but I would expect Player Paddle to stop moving abruptly at the wall. How can I make this happen? I'm new to Unity colliders game dev. My player paddle simply moves up and down (Z axis) with up down mouse movement public class MouseMovement MonoBehaviour public float speed 10f Update is called once per frame void Update () var translation Input.GetAxis("Mouse Y") speed translation Time.deltaTime transform.Translate(0, 0, translation) I exported an asset package that reproduces the problem. My problem objects are Player Paddle, Upper, and Lower https www.dropbox.com s yx9svb51nywdvgg pong export.unitypackage?dl 0
|
0 |
Unity SceneView Positionning object with mouse position in Editor script I would like to create an editor tool who can change the position of an object in the scene view into other object in the world, based on mouse position, like in the picture bellow (the red pyramid is my object to positionnate rotate) I would like to do a raycast from the scene view camera to the mouse position (or something like that), to get the gameObject over the mouse, and then get the position of the verticle normal for position and rotation of my gameObject For now, I have tryed some code who didn't work, I have my object named "preview", and inside the methode OnSceneGUI() in a editor script i have managed to move my preview object, but now I have to know where to put it... Thanks ! EDIT here some of my try Transform previewPoint here my transform void OnSceneGUI() PointCreator() private void PointCreator() test 1 Camera sceneCam SceneView.GetAllSceneCameras() 0 Vector3 spawnPos sceneCam.ViewportToWorldPoint(Event.current.mousePosition) previewPoint.position spawnPos test 2 Vector3 mousePosition Event.current.mousePosition mousePosition.y SceneView.currentDrawingSceneView.camera.pixelHeight mousePosition.y mousePosition SceneView.currentDrawingSceneView.camera.ScreenToWorldPoint(mousePosition) mousePosition.y mousePosition.y previewPoint.position mousePosition
|
0 |
How do game engines like Unity and Game Maker exports to other platforms? From what I understand, if you want to export a Unity or GameMaker game from the editor, the game needs to be compiled to create an executable. I thought that to produce a Windows executable, you needed to be on Windows. How does Unity and GameMaker compile to Mac and Linux, if the engine is running on Windows? Likewise, How do they export to Android and iOS? Do they use the NDK for Android? What about WebGL? How does the export actually work? Do they use a cross platform framework written in some programming language, and when you do things with the editor it generates code using that programming language and framework, so that when you export, that code gets compiled? For WebGL, since the UnityScript code doesn't get compiled, can we see the .js files with the code?
|
0 |
I need help with Admob in Unity this is my first Unity project and I'm getting desperate for answers. I've been trying to get Admob to work using the official plugin. It's been giving me a ton of problems as I can't get the banner to show, despite me using nearly verbatim code as tutorials. Here's my code using System.Collections using System.Collections.Generic using UnityEngine using GoogleMobileAds.Api public class AdMobTest MonoBehaviour BannerView banner InterstitialAd fullAdmob Use this for initialization void Start () RequestBanner() ShowBanner() void RequestBanner() string bannerID "Hiding my banner ID" banner new BannerView(bannerID,AdSize.SmartBanner,AdPosition.Bottom) AdRequest adRequest new AdRequest.Builder().Build() banner.LoadAd(adRequest) public void ShowBanner() banner.Show() public void RequestFull() string idFull "hiding my banner ID" fullAdmob new InterstitialAd(idFull) AdRequest adRequest new AdRequest.Builder().Build() fullAdmob.LoadAd(adRequest) public void ShowfullAds() if (fullAdmob.IsLoaded()) fullAdmob.Show() RequestFull() else RequestFull() Update is called once per frame void Update () I have a new 2D project setup with an empty scene and an "ad" game object, and a script added to that game object. I'm expecting something to show up on my phone's screen, but nothing is showing up. I know this may be a stupid question, but I've spent a ton of time on this, and I'm pretty new to this stuff. So please help me out!
|
0 |
Is Godot's NavMesh viable for dynamic pathfinding (e.g. avoiding moving enemies)? I am a novice (read low budget) designer looking at moving from Pygame to a real engine, and between Unity and Godot it looks like the latter has a much better 2D engine 1, 2, 3 . I would be happy to support Godot's open source model except that, as far as I can tell, its built in navigation mesh is purely static i.e. it can't update its path to account for dynamic obstacles 4, 5 while Unity's pathfinding system can 6 . So my question is Am I "stuck" with Unity? Or is there functionality that I haven't yet been able to find? Or, alternatively, is GDScript significantly faster than Python such that basic algorithms like fixed grid A would do the job? Edit By "stuck" with Unity I don't mean that it's a bad option or that there aren't good options I mean, 'if I need good pathfinding, do I have to give up on Godot and use what would otherwise be a second choice engine?'
|
0 |
Load 3D model from external directory I am developing a desktop application that want to load the 3D model from desktop. Using file explorer user wants to choose the 3d model then it want to show in the application scene.I tried to find the object, the path is detecting but if i tried to Instantiate it on unity it showing this error. ArgumentException The Object you want to instantiate is null. here the code is used public class ReadData MonoBehaviour string path GameObject go public void OpenExplorer() path EditorUtility.OpenFilePanel("Overright with model", "", "dae") Debug.Log(path) GetObj() void GetObj() if(path! null) UpdateObject() void UpdateObject() WWW www new WWW("file " path) go GameObject.Find(path) Instantiate(go) Anybody please help me to do this. Thanks in Advance.
|
0 |
My Raycast2D doesn't go where I want and it doesn't return a GameObject I want my Objects to teleport when they hit a wall. For that, I want to shoot a Ray backwards and teleport it to where the ray hits the wall, but whatever I try, it always teleports to the centre of the scene and the ray hit doesn't return a GameObject. This version I tried runs on OnTriggerEnter2D RaycastHit2D hit Physics2D.Raycast(transform.position, transform.up, 300) Debug.DrawLine(transform.position, hit.point) transform.position hit.point I tried some other variations too. If you have any idea, please let me know.
|
0 |
How do I generate a random map with islands (like the Earth), using Perlin Noise, on a tilemap in Unity? EDIT I've tried this with Perlin Noise with no success, then with Voronoi diagrams, and now I'm editing the question to reflect the issues I had with Perlin Noise, trying again. I'm developing a game in Unity and trying to build a map generator that is capable of creating random maps like the Earth, on a 2D tilemap. The map should contain 2 types of tiles (let's call them grass and ground), while the grass should be the "main" tile, and there should be islands of ground on top of the grass. This was already asked here. My purpose is to create something like the second picture in the question (that picture is showing water and grass, but it doesn't really matter). This blog post suggested a simple way to fill a map (2d array) with Perlin Noise values (float numbers between 0 1), which I did. Eventually each value was rounded to 0 or 1 to present a grass or ground tile. What I can control now is the frequency of the noise, but it's not enough. The map generated by the code below (frequency of 0.3) The problems with this method No randomness. I know Perlin Noise is NOT a random function, so how can I add random factors to generate a different map each time? How can I control the number of islands (e.g. with a factor that can determine "more islands" or "less islands", not an approx. number)? How can I control the size of each island (again, with a factor. I don't care about exact size)? My code (C ) using System using UnityEngine using UnityEngine.Tilemaps using Random UnityEngine.Random namespace TankMayhem public class GroundTilemapGenerator MonoBehaviour private const string TilesPath "Tiles" private Tilemap tilemap private TileBase possibleTiles new TileBase 2 private void Awake() tilemap GetComponent lt Tilemap gt () var tiles Resources.LoadAll lt Tile gt (TilesPath) possibleTiles 0 Array.Find(tiles, tile gt tile.name "ground") possibleTiles 1 Array.Find(tiles, tile gt tile.name "grass") int i int j int , map new int tilemap.size.x, tilemap.size.y const float Frequency 0.3f PerlinNoiseCave(map, Frequency) float probabilities new float 2 foreach (var position in tilemap.cellBounds.allPositionsWithin) i position.x j position.y var tile possibleTiles map i, j tilemap.SetTile(position, tile) private static int , PerlinNoiseCave(int , map, float frequency) for (int i 0 i lt map.GetUpperBound(0) i ) for (int j 0 j lt map.GetUpperBound(1) j ) Generate a new point using Perlin noise, then round it to a value of either 0 or 1 map i, j Mathf.RoundToInt(Mathf.PerlinNoise(i frequency, j frequency)) return map
|
0 |
Trying to convert Unreal shader graph to Unity, what nodes are a close equivalent in the Unity shader graph? I am trying to convert an Unreal shader graph to a Unity Shader Graph. https api.unrealengine.com udk Three VolumetricLightbeamTutorial.html I am struggling with understanding which nodes to use in the Unity Shader Graph while trying to replicate it. I managed to get something looking Ok using the fresnel node, but if you enter inside the geometry, you lose the effect. I found the above article which is perfect for what I need to do. Here is the first node setup I tried to follow along but a lot of the nodes I don't understand what the equivalent would be in the Unity shader graph. Combine looks to be the equivalent of the Append node I think. Mask node I am not sure about as there are 3 mask nodes in Unity shader graph. Edit Spent most of the weekend trying to learn which nodes to use. Still not sure on what the "Reflection Vector" should be. I think it's something to do with the camera. Here is the graph currently.
|
0 |
How can I make the object when rotating to keep looking on the character camera? Not to look the character camera direction but to look to the character camera. This is a screenshot of the object I'm rotating. And this is the face of the object and he is look at the camera(Looking at me). The object is a child of a Camera and the Camera is child of a RigidBodyFPSController (1) In the top of the script public float rotationSpeed private float x private int damping 2 In Update void Update() if (Input.GetKey(KeyCode.R)) x Time.deltaTime rotationSpeed objectToScale.transform.rotation Quaternion.Euler(0, 0, x) var lookPos transform.position objectToScale.transform.position lookPos.y 0 var rotation Quaternion.LookRotation(lookPos) objectToScale.transform.rotation Quaternion.Slerp(objectToScale.transform.rotation, rotation, Time.deltaTime damping) Now when I press on R the object name NAVI is rotating but when I move the MainCamera around the NAVI object is not facing to me. This is a screenshot when running the game first time the object is facing to me But when I'm pressing on R and the object is rotating it looks like the object is facing to the left and I see the object side Then I move the camera to the right he is rotating like I wanted facing to me And if I move the camera to the left when the object is rotating I see the object back But I want that each time the object is rotating that he will be facing to me. The last screenshot showing the Hierarchy the RigidBodyFPSController (1) and the MainCamera as child and the NAVI as child of the MainCamera. The script Change Scale is attached to the MainCamera and with this I'm rotating the NAVI. The main goal what I want is simple. When I press on R rotate the object and always make the object facing to me. I tried now in the Update when pressing R to do if (Input.GetKey(KeyCode.R)) x Time.deltaTime rotationSpeed objectToScale.transform.rotation Quaternion.Euler(0, 0, x) objectToScale.transform.LookAt(Vector3.forward) But now it's not rotating at all.
|
0 |
Unity Duck volume of audio source inside a boxed area I'm trying to lower the volume of an outside ambient wind sound while the player is inside a building or room. Is there any way in Unity to do this without scripting? Or would I have to script this to check whether the player is in a certain collider to duck (or lowpass filter) the sound? The room is seamlessly in the scene's outside environment. Any ideas on this?
|
0 |
How many directional lights in Unity In Unity, how many directional lights can be active at once? 1, 2, 4, or 8? I thought 2, but I have searched and cannot confirm.
|
0 |
How can I programmatically change a sprite's pivot without it affecting a game objects current position and rotation? Because of the complexity of positions, I am using the centre pivot for my game objects sprite. Can I possibly change the pivot without it affecting the game objects current position and rotation? or in other words, can I change the pivot while the sprite remains unchanged visibly? I would preferably like to do this using c script.
|
0 |
Unity3d Detect a collision between an image and a sphere So, I just realized, an image with BoxCollider2D wont detect any collision with Sphere with SphereCollider. I tried adding a BoxCollider to my image, but it behaves in a weird manner (The Canvas position keeps shifting) So, I can see the only way for it to work is adding a 2D Collider to the sphere? Is there any other better way to solve it? Adding a 2D Collider to the sphere wont cover the whole area
|
0 |
Particle System is not Playing I made a simple spaceship that has a particlesystem. When I press quot space quot button, spaceship should fly and particle system should instantiate and play. But it's not playing. It seems in hierarchy as clone but not playing. As you see, particle effect is instantiating but not playing. It should play at bottom of spaceship Those are codes void FlyShip() if (Input.GetKey(KeyCode.Space)) rb.AddForce(Vector3.up jumpForce) if (!takeoffSound.isPlaying) rocketJetParticle is gameobject. rocketJetParticle Instantiate(rocketJetParticle, new Vector3(transform.position.x, transform.position.y 4, transform.position.z), transform.rotation) takeoffSound.Play() else Destroy( rocketJetParticle) takeoffSound.Stop()
|
0 |
Handling an item database with procedurally generated items? Let's say you have an item database which has every item in your game. This works fine for regular items like a Health Potion, a normal Iron Sword etc, because these items have ItemID's so we can get an exact copy of this item. But what if we have an Iron Sword with an enchantment ' 5 Fire Damage'? (or whatever) If you were to save that item to a player's inventory, exit the game and load the game, the item will load as a regular Iron Sword, because it still has that ID. Specifically, how would you save that item to a file? I'm using Unity, so to save the Player's inventory, I use PlayerPrefs.SetInt("Inventory " i, inventory i .ItemId ) Would you create a custom item ID for every item with enchantments or is there a better way around this?
|
0 |
My colliders keep going through one another? So, I have some platform with colliders and a character with a collider (everything in 2D). The problem is, while there is some noticeable effects (a certain push back) when the colliders collide, they actually intersect each other and can go through each other.. How can I actually put a collider that doesn't let anything pass, it just stands there like a brick wall against anything? By the way, any enlightenment on the inner workings of the colliders behavior will be appreciative as I cannot understand how this could even happen. Demonstration video Demonstration video 2 Bellow I have the images showing the inspector of both the character and platforms wall respectively. 4 Also I'm moving the character using transform.position Vector3.right speed Time.deltaTime
|
0 |
NavMeshAgent is not calculating a new path I have the following code that gets run when a game object collides with a trigger. When the object is created, it is created within an initial trigger which fires the SetNextWaypoint code below and it works fine. protected NavMeshPath path protected NavMeshAgent agent null void Start () path new NavMeshPath() agent GetComponent lt NavMeshAgent gt () public void SetNextWaypoint(Vector3 location) agent.ResetPath() path.ClearCorners() agent.CalculatePath(nextWayPoint, path) agent.SetPath(path) Once the agent enters a new waypoint (it may not have reached its destination yet) SetNextWaypoint is called again and when it does the agent just stops where it is, and doesn't move anywhere.
|
0 |
(Unity) Physics based movement vs Straight position change Unity provides a cool physics engine for game development and I want to utilize it in my game. Shorter version I want to use physics engine for everything else other than character movement because trying to use physics engine for player movement doesn't yield the perfectmovement speed that I want move x units per second. If I use physics engine for character movement, it gets complicated. I would rather just add "moved distance" to the position to have things done simple. Is doing something like this wrong? All the learning sources I read recommend to use physics engine for movement if the game incorporates physics engine. I am nervous am I wrong? Longer version The following description is where I use "physics", why I need physics engine. In my game a player fires a bullet. When enemies collide with bullet, they get pushed back slightly. A strong blast can push enemies far back so that they even bounce back from hitting wall. A recommend, a proper way, I was told, to utilize this physics engine for character movement is to add force to the direction I want to move. But doing so(adding force to the direction I want to move) will result in truck like slowly warming up by adding velocity. To avoid "truck like movement" I was told to apply greater force at the beginning. Doing so result in change in velocity like the below picture. However problem is not over yet, you must consider a situation where you change direction of movement while the character is running. If you started to move backward, all of the sudden while running forward, you will need to slow down forward movement burn velocity by adding backward force. Thus rotation burns velocity. So a solution is to find out perpendicular velocity to your desired direction, then find out needed amount of force to "burn off" the undesired velocity. This seems way too complicated for a character to simply move around. I would rather just move character to desired direction by simply adding "constant X distance" to the character's position. But I can't find a source of example where it utilizes both "simple movement by directly adding moved distance to the position" and "using physics engine for the game". All the sources of learning(using Unity physics) I find say use this complicated way of having character to move around. I wonder is there a reason why people don't just add moved distance to the position?
|
0 |
How i can play movie in unity by script(android platform)? my script is correct in pc platform but when i switch on android platform i have compiler error cs0246, why i can not export my apk file. how i can play movie in unity android platform by other way? public class NewBehaviourScript MonoBehaviour public MovieTexture myMovie void Start() myMovie.Play() void OnGUI() GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), myMovie)
|
0 |
Using Standard Asset RBFP Controller for Universal Windows Platform I was using the rigidbodyfirstperson controller, and it stopped working when I changed the build settings to UWP. Any body know the reason for this or how to solve it? Thanks... Rik
|
0 |
3D visual effects on videos I'm trying to get some hands on experience with 3D visual effects on videos. Similar to those AR apps, I want to add a 3D model with effects, say a dragon, to a video. Something like this famous demo https youtu.be u5hQpRbHERg But I don't really want to make it this fancy with camera tracking. I like to start with the simplest approach probably just placing a dragon on the field (like its last scenes) with fixed camera. What's the best way to do it? Some tutorials would be very helpful.
|
0 |
Why would a property be returning null? I'm working on learning how pass data from one script to the other in Unity and I'm getting a little confused. I have two scripts, PlayerData and CreateCharacter. PlayerData is used to pass persistent data from one scene to another, so it's not going to be attached to any GameObject or Transform. CreateCharacter, however, is attached to a button which gets the information from user input. Here are the two scripts PlayerData public class PlayerData private string playerName public string PlayerName get return playerName set playerName value CreateCharacter public class CreateCharacter MonoBehaviour public InputField playerName public PlayerData playerData new PlayerData() public void AddStats() public void SubtractStats() public void CreateCharacterOnClick() playerData.PlayerName playerName.text Debug.Log(playerData.PlayerName) What's happening is, when I click the button I'm getting a null reference error on playerData.PlayerName but if I just log playerData I actually get the object to return. What I'm trying to see is that the character name(playerName) is logged when the button is clicked. Can anyone explain to me what I'm doing wrong and how to fix it?
|
0 |
Moving spilling water inside a cup of glass I made a glass of water but there are somethings i didnt know how to do well, what i did is i put a mesh on the top of the glass to represent the surface of the water but it doesnt really work well with glass because if you look from the sides you wont really see that there is water in there, this is what i did the glass from the side as you can see it doesnt really work well in my case. I also tried putting an object that has the same shape as the cup inside to represent water but that would make it difficult for what i want to do next, because my next step would be to make the water rotate in the opposite rotation of the cup and make it spill if it reaches the top of the cup, and that is my second question how do i make the water spill from the cup? Any help is very much appreciated.
|
0 |
How To Fix Strange White Edges With DOF and Fog in Unity? I'm using global fog and the standard assets Depth Of Field script but it has a strange effect on the edges of far away objects. How can I make the white edges along the trees blend smoothly into the fog?
|
0 |
How can I reduce a bezier curve using a slider till all points converge to it's original midpoint I am using the code from the question here to create bezier curves (I didn't think it was necessary to repost the code here since I haven't made any significant changes to it yet). I have a symmetric bezier curve (please see image) that I want to reduce till all points converge at the midpoint of the original curve. I would like to preserve it's symmetry while it moves. I would like achieve this using a float slider (with values from 0 to 1) in editor mode.
|
0 |
How to get characters to be aware that their path is obstructed? I'm using Unity with Arongranberg's A pathfinding project to move my characters. However, it appears that my characters are contending for a position on the terrain when they are told to move together to a same position. For example, I have 5 characters being told to move to PositionA. They will move together based on their waypoints to PositionA. One of the characters, call it CharacterA, will reach PositionA before the rest. Now, the other 4 characters who arrived later will continue to keep walking and "sliding" around CharacterA. They seem to stop only when CharacterA moves away from PositionA so that they could reach their destination to break out of the loop. Even so, only one character can be in PositionA while the rest will continue to contend for the place. So, how can I get the characters and objects to know that they have reached their destination and should stop beside the other characters instead of contending for the same place? A naive method could be I get the characters to detect if they are blocked by something straight ahead of them. If they are, break out of the loop and stop the walking state. But at times when the character hasn't reached his destination yet and is blocked by an object, say another character, breaking out of the waypoint loop will stop him at the wrong destination. I can't recalculate for a new path from his current position either since the blocking object is another character, which the initial pathfinding grid scanning did not take into account. One way is I re scan the whole terrain for a new grid of nodes with the characters in the scene taken into account. But this wouldn't be efficient and will lag a whole ton.
|
0 |
Can't correct perspective of Main Camera in Unity 3D without losing field of view I have been trying to create a space based rails shooter game following a particular online course and I find a tilt(roll) on my spaceship as I move it towards the left and right ends of the screen. https imgur.com Kkg8hp2 (A normal screenshot of my spaceship at default position) This is due to perspective of the camera as I have been told and apparently dragging the camera farther behind the spaceship and decreasing its field of view helps. https imgur.com 0oXJff7 (The tilted spaceship when it's at an end of the game window) But, doing that neutralizes the illusion of speed caused by a greater field of view. I have found a middle point between the two to balance both aspects of the game but I would like to know if there is any way to get higher field of view without making the ship look like it's tilted. Things I have considered doing Added a positionRollFactor which gives the ship some additional roll in the opposite direction of the tilt. (This still doesn't fix the perspective issue in which one half of the ship is more enlarged than the other). Tweaking the field of view by trading off a little of each feature.
|
0 |
OnTriggerExit2D called multiple times when two triggers touch I have two GameObjects tagged "Point", each with a Collider 2D set to Is Trigger. I have another GameObject, "pencil", which also has a Collider2D set to Is Trigger I want to move the pencil the first point to the start drawing a line, and then stop drawing when it hits the second point. My problem is that when the pencil hits a point, it calls OnTriggerExit2D multiple times. How can I only detect first contact with the point? Pencil script private void OnTriggerExit2D(Collider2D collision) if (!collision.isTrigger) if (collision.gameObject.tag "Point") writing !writing
|
0 |
Why are assets (images) in Unity build reported as 28 times larger I'm trying to reduce a Unity WebGL build size which, for the data asset, is currently at 30 Mb. I installed the Build report inspector. On clicking the "Source assets" tab and choosing "Size" it showed the top entries were images. Fine. But all the sizes reported were between 4 and almost 30 times the size of the file on disk. Is this just a bug artifact of the build reporter or a genuine problem which I need to address to reduce the build sizes? Edit Two of the files are text files. Their size in unity build report is the same as that on disk. Why? Edit 2 after Ed Marty's answer Using low quality with crunch compression at 70 results in slightly lower image quality but it went from 10 Mb to 300 kb, i.e. 30 times smaller size (and about 10x smaller than actual file size on disk).
|
0 |
Problem with Rotation clamping in Unity I'm trying to get a simple cannon to rotate to point at the mouse, but I only want it to follow the mouse for 180 degrees and then stop following the mouse, and pick up again when the player re enters the 180 degree area. I got the cannon to follow the user's mouse but when I tried to camp it to the 180 degree area I found it worked for one side, but when I went to the other it "teleported" to the other side. I video to explain my issue https imgur.com a DZYA305 Sorry about the crude graphics, frame rate, and the software doesn't show my mouse making things more difficult, but as you can see, the clamp works fine when I move my mouse to the right, but when I move it to the left it "teleports" or instantly moves to teh right no matter where my mouse is. Here is my code public int rotationOffset 90 Update is called once per frame void Update() var mouse Input.mousePosition var screenPoint Camera.main.WorldToScreenPoint(transform.localPosition) var offset new Vector2(mouse.x screenPoint.x, mouse.y screenPoint.y) var angle Mathf.Atan2(offset.y, offset.x) Mathf.Rad2Deg float finalRotation angle rotationOffset I have tried both the normal Mathf.Clamp and the if statments below and I get the exact same result. finalRotation Mathf.Clamp(180, 0, finalRotation) if (finalRotation gt 89f) finalRotation 89f Debug.Log("Left") else if(finalRotation lt 89f) finalRotation 89f Debug.Log("Right") transform.rotation Quaternion.Euler(0, 0, finalRotation) I don't know if this might be a bug in Unity, But I've spent days trying to fix it, I'm tired, I'm stressed, I don't know how to fix it.
|
0 |
Unity UI Input Field suddenly malfunctioned I'm using Unity 5.0.1f1, and my UI Input Fields are not working as they are supposed to. I have an Input Field that is placed in a Panel and inside a Canvas. It has a Text component in which I can set text that the Input Field will display. When I change value of this Text component, the changes are not reflected on the Input Field, it seems to be reset to the value of Input Field (Script) Text of the Input Field. If I enter Play mode, I can input text normally but when I build and run on my Android phone, I cannot input anything. Has anyone encountered this problem? How can I solve this?
|
0 |
Unity3D object fill shader I've been researching this for a while, and had no luck yet. I figured I'd ask here to see if anyone had any good ideas. Essentially what I want is a shader that can make only part of an object transparent based on a slider. Similar to fill effects on 2D sprites, the object would fill from the bottom up, when the slider was set to 0 the whole object would be transparent, when it was set to 50 just the bottom half would be visible, and when it was set to 100 the whole object would be visible. I've tried various masking effects, but it would be best if I could build this in to existing shaders or have a separate mask. Is there perhaps a way to adjust the alpha on individual pixels used for the diffuse texture without incurring great performance loss?
|
0 |
Selected enemy off camera I'm facing a problem with a game I'm making. Currently I can select an enemy and mark it as shown on the image But now I want to show the position of the selected enemy on the screen when it's off camera. So my questions are How do I know when an enemy is off camera. How can I show in GUI an arrow on the edge of the screen that points to the position of that enemy. Perhaps something related to what I did to point towards the crosshair? Vector3 positionOnScreen Camera.main.ScreenToWorldPoint(mousePos Vector3.forward range) Vector3 targetDir positionOnScreen transform.position Thanks!
|
0 |
Change color of selected polygons I have a "low poly" surface, where the color palette for polygons is low (e.g. 20 distinct colors). Is there a way to change the color (with a smooth transition) for all polygons painted with a certain color? Maybe an analogy would be to smoothly make all polygons of a certain color transparent.. Background I have managed to get a 2D variant working load a bitmap on a canvas and use a shader to change the color.
|
0 |
How to use uv mapping in Unity 2017 I want to create a game with a Minecraft style world. Now I need uv mapping for some cubes in my game. But I could not find any good tutorial in the internet. I want to use the following texture with an uv map Each side of the cube has a texture with 64x64 pixels. The dirt texture on the right side has to be the top of the cube. Can anyone tell me how to use uv mapping in my case?
|
0 |
Why can't I change the size of my spheres in Unity? I started to learn Unity. Now I make something like a solar system. I have one problem. What are the min and max sizes of the sphere? E.g. I have a radius of the Sun 1.5 but it shows like the Sun has radius 1, I can't make bigger. But also I have the Earth with 0.01 size and the Moon with 0.009. But I can't make the Mercury with 0.03 radius. So why when I'm creating a new sphere now I have only radius 1 and can't change it in Scene window?
|
0 |
Materials aren't loading correctly from SketchUp into Unity I imported a SketchUp COLLADA (.dae) file from 2017 SketchUp Make, and imported it into Unity. I then clicked quot Use External Materials quot and the colors began to load. But I noticed quickly that one of the wings of my imported B 29 was Dark Gray, while the other way a proper color. Random parts, such as the front engine housing piece, were also dark gray. Parts of my advanced dials were also dark gray, and I immediately decided that there is now ay that I am going to manually go in and fix every single dark gray material, but at the moment, I found no alternative. I began with the wing. I went to assign the material that I used for the other wing, which was white, to the dark gray wing, but I found out that the other wing already had that material in use. And when I went to assign a different white color, absolutely nothing changed, aside from the fact that the wing now claimed that it had that color in use. Is there a fix for this problem? I could try importing as a .SKP file, if the reason for the issue is something to do with the COLLADA (.dae) file. What I had was 2 wings. they were both components in SketchUp, so whatever I did to one applied to the other, Then I made them unique before importing to Unity. The Wing that won't work right is the one wing that had the USAF Insignia on it. But I doubt this is the problem, because all engines on that wing were also not colored correctly, whereas the other wing was fine. Those engines were also components, but were also made unique before the import. Each wing has 9 groups inside of it. The other wing is identical in this sense. I imported the file from file explorer by dragging the file from file explorer and dropping it into unity. This is what the plane looks like in Unity My apologies for the crude handwriting, it is difficult to draw with a touchpad. In the image, I numbered the incorrectly colored parts visible in the image (Right Left references are perspective to image) 1. Left Wing. Color Dark gray. Color intended White. 2. Propeller blade hub. This is the part that all propeller blades are connected to. Both hubs on the two propellers on the Left Wing are colored incorrectly. Color white. Color Intended Grey. 3. Pistons. All piston components, such as the pistons, securing poles, and piston heads are not colored correctly same on the other engine on the Left Wing. Color White. Color Intended Grey pistons, darkish grey piston heads, and copper orange securing poles. 4. Cowl Flaps. In the image, this appears to be a stripe in the engine. Same with the other cowl flaps on the other engine on the Left Wing. Color Dark gray. Color Intended White. 5. Propeller blades. All 4 propeller blades on both engines on the left wing are not colored correctly. Color White. Color Intended Black, with yellow tips. 6. Right Wing Pistons. Most piston components, such as the pistons heads and securing poles are not colored correctly. Same with the other engine on the Right Wing. Color White Piston Heads, Grey Pistons, Almost Black Gray in the lines on the pistons, white securing poles. Color Intended Grey pistons, darkish grey piston heads, and copper orange securing poles. 7. Front Engine Casing. The same error is in the other engine's front engine casing on the Right Wing. Color Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). Color Intended White. 8. Rear Engine Casing. The same error is in the other engine's rear engine casing on the Right Wing. Color Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). Color Intended White.
|
0 |
Google Play Games Signs Out Automatically without Internet Unity I am using this in my game to implement games saving and loading. I have also tried the basic sign in process by using the following start function PlayGamesClientConfiguration config new PlayGamesClientConfiguration.Builder () enables saving game progress. .EnableSavedGames () .Build () PlayGamesPlatform.InitializeInstance (config) recommended for debugging PlayGamesPlatform.DebugLogEnabled true Activate the Google Play Games platform PlayGamesPlatform.Activate () Social.localUser.Authenticate ((bool success) gt if (success) MyAutoSave.isLoaded false ) I can sign in on google play games without any issues. Soon after that if I quit the game and start again without data connection, it gets authenticated without any issue. If my data connection remains off for say more than an hour, and I start the game without Internet connection, there is no authentication whatsoever. If I close the game and start again soon after that, it gives me that google play games sign in popup. So what i can conclude is that it signs out automatically after some time if there is no Internet available. Is there any fix for this.? Thanks
|
0 |
jumping and movement with rigidbody2d.velocity, gravity problem i'm making a 2d platformer and i move my character with rigidbody2d.velocity swiping up to jump and moving while holding the left or right side of the screen. the problem is that when i jump and i try to move left or right in the air, my character falls very slowly. i've read that the reason why that happens is because rb.velocity overrides gravity at every frame, is there a way to move left or right in the air with normal gravity? my full code is Rigidbody2D rb public float speed 1f public float jumpforce 3.5f private Vector3 mouseDownPos private float startTime 0f public float holdTime 0.15f void Start() rb GetComponent lt Rigidbody2D gt () void Update() if (Input.GetMouseButtonDown(0)) mouseDownPos Input.mousePosition startTime Time.time if (Input.GetMouseButtonUp(0)) if ( startTime holdTime gt Time.time amp Input.mousePosition mouseDownPos) tap Debug.Log("T A P") if (Input.mousePosition.y gt mouseDownPos.y 100 ) jump rb.velocity new Vector2(rb.velocity.x, jumpforce) if (Input.GetMouseButton(0) amp startTime holdTime lt Time.time) move while grounded if (Input.mousePosition.x lt Screen.width 2) Debug.Log("Left click") rb.velocity transform.right speed else if (Input.mousePosition.x gt Screen.width 2) Debug.Log("Right click") rb.velocity transform.right speed if (Input.mousePosition.x lt Screen.width 2) move while in the air Debug.Log("Left click") rb.velocity new Vector2( speed, rb.velocity.y) else if (Input.mousePosition.x gt Screen.width 2) Debug.Log("Right click") rb.velocity new Vector2(speed, rb.velocity.y) the rigidbody2d of my character is
|
0 |
Unity's Quaternion.Lerp slows down when target is directly behind turret Software Unity v5.2.1f1 Personal I am trying to achieve the effect of a turret in Unity. For this I have a turret consisting of 3 parts as well as a target. The problem is that whenever the target my turret is targeting has a z of lt 0, the lerp speed is extremely slow. However, the further away the target is from x 0 (both positive and negative), the faster it will move. This effect only occurs when my target has a transform.position.z of lt 0. When z 0 the transform.position.x has no effect on the lerp speed. My setup is as follows The 3 turret parts are the base, turret and barrel. The base is nothing more than a block for the turret to rest on. The turret is a block holding the barrel in place with base as his parent. The turret rotates around its y axis to always face the target. The barrel has turret as his parent. The barrel rotates around its x axis to always face the target. See the picture below for the end result. Base Blue Turret Red Barrel Green The turret has the following code public class turretRotation MonoBehaviour public Transform target void Update() Vector3 relativePosition target.position transform.position relativePosition.y 0 Quaternion rotation Quaternion.LookRotation(relativePosition, new Vector3(0, 1, 0)) transform.localRotation Quaternion.Lerp(transform.localRotation, rotation, Time.deltaTime) The barrel has the following code public class barrelRotation MonoBehaviour public Transform target public float speed 1 Vector3 relPos Quaternion rot void Update () Position of target relative to my position relPos (target.position transform.position).normalized rot Quaternion.LookRotation(relPos, new Vector3(0,1,0)) Lerping localRotatiot gt rot with speed Time.deltaTime speed (set to 1 by default) transform.localRotation Quaternion.Lerp(transform.localRotation, rot, Time.deltaTime speed) Resetting y and z EulerAngles to 0 This way only the x EulerAngle will be affected. The y rotation is inherited from the parent (turret turret) transform.localEulerAngles new Vector3(transform.localEulerAngles.x, 0, 0) In this picture the Lerp is working as intended Note target.transform.z 0 In this picture the target has a z 5 and x 0 pay particular attention to the Lerp speed It eventually gets there, but it takes a very long time. For some reason, the further away the target is from x 0, the faster the Lerp speed. Note Still slower than intended In this picture the target has a z 5 and x 10 So for some reason when target.transform.z has a negative value, the higher the distance from target.transform.x to x 0 the higher the Lerp speed. I've done a fair bit of searching and came across a post on answers.unity.com describing a similair problem Unfortunately, no reply. http answers.unity3d.com questions 1084067 lerp problem when target is behind.html So my question is "Why is this happening and more importantly, how can I fix this?" Any help would be much appreciated!
|
0 |
Unity3d turn based navmesh algorithm I am developing a game in Unity3d. In this game, 2 teams will fight without any human interaction. The fight results must be always the same, if the same teams are the same. This way, I must reproduce the same fight in many devices, getting the same results in each device. The map where the fight happens is a 3d environment, so, my soldiers can move in any direction. And the soldiers cannot walk in the same space of another soldier, so I need an agent avoidance algorithm. I am having some trouble to find a solution to the problem above. To achieve the 'always the same results' I am treating this fight as Turn Based Strategy game, with little fixed time intervals between the turns. To calculate the pathfind of the soldiers, I am using the Unity3d navmesh framework. And then I move manually my agents according to the 'NavMeshAgent' 'steeringTarget' property. But this method doesn't cover the obstacle avoidance algorithm, and my agents overlaps. So, I am looking for a solution to my problems, It should be a manual obstacle avoidance algorithm, or a way to unity navmesh work in fixed time intervals, or a completely new approach to my path finding problems.
|
0 |
How can I set up a 2D circular boundary in Unity? I wanted to create a virtual analogue stick on Unity. I figured a very simple, 2 part method setting up a tether to the middle of a doughnut container and a boundary would work. While the tether was quickly solved just by using Vector2.MoveTowards, the boundaries would be much harder to solve. I initially tried to create a 2D circle collider around the doughnut container but I didn't know how to reverse its collisions to keep the cursor inside. Later, I tried to set up a square shaped boundary by setting up the limits of the x and y coordinates the cursor cannot exceed (these limits were also made according to the doughnut container). Thus was done with multiple if statements if (currentPoint.y gt 2.7f) currentPoint.y 2.7f if (currentPoint.x gt 2.5f) currentPoint.x 2.5f if (currentPoint.y lt 2.7f) currentPoint.y 2.7f if (currentPoint.x lt 2.5f) currentPoint.x 2.5f However, when testing the code out, the cursor still exceeded the boundaries given Minimum reproducible code for the cursor public class menuScript MonoBehaviour public float speed public Vector2 originPoint private Vector2 currentPoint Start is called before the first frame update void Start() Vector2 originPoint transform.position Update is called once per frame void Update() currentPoint transform.position float step 50 Time.deltaTime float vertical Input.GetAxis( quot Vertical quot ) Time.deltaTime speed float horizontal Input.GetAxis( quot Horizontal quot ) Time.deltaTime speed if (horizontal ! 0 vertical ! 0) transform.Translate(horizontal, vertical, 0) if (currentPoint.y gt 2.7f) currentPoint.y 2.7f if (currentPoint.x gt 2.5f) currentPoint.x 2.5f if (currentPoint.y lt 2.7f) currentPoint.y 2.7f if (currentPoint.x lt 2.5f) currentPoint.x 2.5f else transform.position Vector2.MoveTowards(transform.position, originPoint, step)
|
0 |
How can I set up a 2D circular boundary in Unity? I wanted to create a virtual analogue stick on Unity. I figured a very simple, 2 part method setting up a tether to the middle of a doughnut container and a boundary would work. While the tether was quickly solved just by using Vector2.MoveTowards, the boundaries would be much harder to solve. I initially tried to create a 2D circle collider around the doughnut container but I didn't know how to reverse its collisions to keep the cursor inside. Later, I tried to set up a square shaped boundary by setting up the limits of the x and y coordinates the cursor cannot exceed (these limits were also made according to the doughnut container). Thus was done with multiple if statements if (currentPoint.y gt 2.7f) currentPoint.y 2.7f if (currentPoint.x gt 2.5f) currentPoint.x 2.5f if (currentPoint.y lt 2.7f) currentPoint.y 2.7f if (currentPoint.x lt 2.5f) currentPoint.x 2.5f However, when testing the code out, the cursor still exceeded the boundaries given Minimum reproducible code for the cursor public class menuScript MonoBehaviour public float speed public Vector2 originPoint private Vector2 currentPoint Start is called before the first frame update void Start() Vector2 originPoint transform.position Update is called once per frame void Update() currentPoint transform.position float step 50 Time.deltaTime float vertical Input.GetAxis( quot Vertical quot ) Time.deltaTime speed float horizontal Input.GetAxis( quot Horizontal quot ) Time.deltaTime speed if (horizontal ! 0 vertical ! 0) transform.Translate(horizontal, vertical, 0) if (currentPoint.y gt 2.7f) currentPoint.y 2.7f if (currentPoint.x gt 2.5f) currentPoint.x 2.5f if (currentPoint.y lt 2.7f) currentPoint.y 2.7f if (currentPoint.x lt 2.5f) currentPoint.x 2.5f else transform.position Vector2.MoveTowards(transform.position, originPoint, step)
|
0 |
How to select light as sun source I tried to add a sun in the lighting setting. I have a directional light in my scene, but i can't select it as sun source in lighting setting. The light does not appear in the list. Does anyone know what is wrong ?
|
0 |
VSCode doesn't open the specified Unity script I have downloaded Visual Studio Code to edit Unity scripts. When I double click on a script in Unity, VSCode opens but it doesn't open the script, only an empty file called Unity appears. Anyone knows how to solve this?
|
0 |
"lerp" returning value (Shader)? I don't understand the lerp example in this code if(dot(WorldNormalVector(IN, o.Normal), SnowDirection.xyz) gt lerp(1, 1, Snow)) o.Albedo SnowColor.rgb else (Snow is in the range 0..1) The article says We then compare the dot value with a lerp if our Snow level is 0 (no snow) this returns 1 and if the Snow level is 1 it will return 1 (the entire rock is covered). It's quite normal to only vary the snow level between 0..0.5 when we use this shader so that we only have snow on surfaces that actually face the snow direction. Why does it return 1 (with Snow at 0) and 1 (with Snow at 1) ? (source http unitygems.com noobs guide shaders 2 ) Thanks
|
0 |
Why is clicking too fast giving me a missingReferenceException in Unity? I made a small method that will quickly give the player a "flashlike" display when a sheep is killed. However clicking too fast will trigger a missingReferenceException. Because it registers the raycast a second time. Is this due to the delay on the DestroyObject() or something else? private IEnumerator startFlashing(GameObject sheep) sheep.gameObject.GetComponent lt Rigidbody gt ().freezeRotation true sheep.gameObject.GetComponent lt Rigidbody gt ().velocity Vector3.zero sheep.SetActive(false) yield return new WaitForSeconds(theTimeBetweenFlashes) sheep.SetActive(true) DestroyObject(sheep.gameObject, 0.1f)
|
0 |
how can i fix my code in order to get rid of the error that says that the object I want to instantiate is null? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class replicate MonoBehaviour public void replicateCube(InputField T) int H int.Parse(T.text) for (int i 0 i lt H i ) GameObject prefab Resources.Load("Cube") as GameObject GameObject go Instantiate(prefab) as GameObject go.transform.position new Vector3(0, i 5, 0)
|
0 |
Custom shadowmapping in Unity not working properly To experiment with a certain technique, I'm implementing my own shadow mapping in Unity. I'm using a camera for the light "view", which is rendered to a RenderTexture after being post processed with the following shader Shader "Custom DepthGrayscale" SubShader Tags "RenderType" "Opaque" Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D CameraDepthTexture struct v2f float4 pos SV POSITION float4 scrPos TEXCOORD1 Vertex Shader v2f vert (appdata base v) v2f o o.pos mul (UNITY MATRIX MVP, v.vertex) o.scrPos ComputeScreenPos(o.pos) for some reason, the y position of the depth texture comes out inverted o.scrPos.y 1 o.scrPos.y return o Fragment Shader half4 frag (v2f i) COLOR float depthValue tex2Dproj( CameraDepthTexture, UNITY PROJ COORD(i.scrPos)).r return fixed4(depthValue, 0.0, 0.0, 0.0) ENDCG FallBack "Diffuse" With a width and height of 2048 for the Render Texture and the color format R Float for 32 bit precision. The objects in the scene then have the following shader that takes the projection view matrix of the light and "depth" texture as input. (Basic shadow mapping with bias) Shader "Tutorial Display Normals" Properties CameraTex ("Camera texture", 2D) "white" SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" uniform float4x4 lightMatrix struct v2f float4 pos SV POSITION float3 worldPos COLOR0 fixed3 color COLOR1 v2f vert (appdata base v) v2f o o.pos mul (UNITY MATRIX MVP, v.vertex) o.worldPos v.vertex.xyz o.color v.normal 0.5 0.5 return o uniform sampler2D CameraTex fixed4 frag (v2f i) SV Target fixed4 coords mul(lightMatrix, fixed4(i.worldPos, 1.0)) coords coords.w coords.x (coords.x 1.0) 2.0 coords.y (coords.y 1.0) 2.0 coords.z (coords.z 1.0) 2.0 return fixed4(coords.z, 0.0, 0.0, 1) float lightDepth tex2D( CameraTex, fixed2(coords.x, 1.0 coords.y)).r float depth coords.z if (depth lt lightDepth 0.005) return fixed4(1.0, 1.0, 1.0, 1.0) else return fixed4(0.1, 0.1, 0.1, 1.0) ENDCG The result of this is perfect with a plane and cube The red plane displays the shadow map and the camera represents the light. However, when using a more complex model like Sibenik, the following happens When I move it slightly, the shadow on the plane is suddenly correct, but the shadow on the church model itself is still wrong What could be the problem?
|
0 |
GUIText size on 4 3 and 16 9 is different I have a text (guiText) on the screen. It shows correctly when viewed on 16 9 resolution. But it scales up when viewed on 4 3 (e.g iPhone4). I am using following ObjectLabel script to place it on the same position regardless of screen resolution. Which is working fine for 16 9 and 16 10. Object Label
|
0 |
How do I set the exact local position of a RectTransform? I have a game object that creates a keyboard in side of my world canvas. I am working out the offset positions for each key, and appear to be doing that correctly. However, when I set the positions in the actual keys, the values are being offset by anything from 100 1000. This is the basic method I am currently using to set the position public void SetDimensions(Vector2 position) GetComponent lt RectTransform gt ().localPosition position Debug.Log(key " " position) I have also tried using .position and .anchoredPosition, as per the somewhat confusing API reference. I have also tried simply referencing transform.localPosition and transform.position. No matter what, the output is exactly the same. The debug output confirms that I am working out the correct local position, but no matter what I do, that is not the value being set to my transform. As you can see, I have my pivot set to the center though I think this may have an impact, it certainly should not cause an offset of 400 500. As per request, this is my main canvas What am I doing wrong, or more specifically, how do I set the exact local position of a game object using a RectTransform?
|
0 |
Still having problems using Json data in Unity I have the following classes and json file, i thought id followed the documentation exactly but I am clearly wrong. Can anyone see why I get an error just saying INVALID VALUE in my unity console using System.Collections using System.Collections.Generic using UnityEngine using System Serializable public class DataReader public float x public float y public float z GameController public class GameController MonoBehaviour public static GameController instance DataReader dataReader private string gameDataFileName "level1.json" private void Awake() dataReader JsonUtility.FromJson lt DataReader gt (gameDataFileName) instance this void Start () create level print("DATA " dataReader.x 0 ) and the json is stored in StreamingAssets folder (I also tried a copy in Resources folder) "x" 1 , 1 , 1 , 1 , "y" 1 , 1 , 1 , 1 , "z" 1 , 2 , 3 , 4
|
0 |
How can I expose a property to Unity that should be treated like an asset path? I want to be able to do something like this public FileInfo XmlBehaviourFile And then use the asset browser in the Unity editor to select an asset. Ideally, I would like to limit it to XML files but that isn't too important. I am aware of TextAsset but I can only access either a string or byte array of the contents. I can probably make this work, but at the moment, my library takes a FileInfo and handles the reading itself. Is there a Type I can use that will make Unity let me choose a file in the editor and then simply store the path (ideally, it would handle making sure the path is relative and including the asset in the build). Alternatively, would it be possible to write such a type that would work, I've not extended Unity, but I am aware it is possible.
|
0 |
Start timer when button pressed (what is wrong with my code?) I want a timer to start when my rocket takes off and stop when it lands. Stopping works fine (using a collider and state switching) but I can't get the timer to start when I press the boost button. Currently the timer text is displayed at the moment I pressed the button but clearly has been counting from the moment the scene started, not the moment the button is pressed. Any help will be greatly appreciated. If there is a better way to start the timer rather than when I press the boost button then I am open to ideas! Here is the all relevant code (I think). It appears as though it should be working to me, but it isn't. Timer public Text timerText private float startTime private bool started false private bool finished false void Start () startTime Time.time get time since scene started void Update () if (currentState State.Alive) ProcessBoostInput() ProcessRotationInput() ProcessFiringInput() if (started) RunTimer() private void ProcessBoostInput() if (Input.GetKey(KeyCode.A) (CrossPlatformInputManager.GetButton("Fire1"))) BoostShip() PlayBoostSound() if (started ! true) started true private void RunTimer() if (finished) return else if (started) float timeSinceTimerStart Time.time startTime string minutes ((int)timeSinceTimerStart 60).ToString() string seconds (timeSinceTimerStart 60).ToString("f3") timerText.text minutes " " seconds private void StopTimer() finished true timerText.color Color.green
|
0 |
Create a normal map using a script? Unity I don't have a software that can create normal maps from an image so I usually make a grayscale image and then let unity make the normal map from that image. But I can't save the image to use for later, Instead I have to convert it to a normal map every time I use it. So how would I make a normal map from a greyscale using a script? i prefer c but js works fine.
|
0 |
Player losing alignment with tilemap after moving I'm using an isometric tilemap(2 1) and I can't figure out how to make grid based movement on it's surface. I managed to get a code working for the grid based movement, moving my character with 0.5 along the Y axis and 0.86 ( sqrt(3) 2 ) along the X axis since I imagine it should work as if they are diamonds with the side of 1 unit, but it doesn't align with the center of the next tile. Here is my movement code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Assertions.Must public class Movement MonoBehaviour Vector3 pos For movement float speed 5f Speed of movement public float x 0.86f public float y 0.5f void Start() pos transform.position Take the initial position void FixedUpdate() if (Input.GetKey(KeyCode.A) amp amp transform.position pos) Left pos Vector3.left pos new Vector3( 0.86f, 0.5f, 0) if (Input.GetKey(KeyCode.D) amp amp transform.position pos) Right pos Vector3.right pos new Vector3(0.86f, 0.5f, 0) miscare in diagonala if (Input.GetKey(KeyCode.W) amp amp transform.position pos) Up pos Vector3.up pos new Vector3(0.86f, 0.5f, 0) if (Input.GetKey(KeyCode.S) amp amp transform.position pos) Down pos Vector3.down pos new Vector3( 0.86f, 0.5f, 0) transform.position Vector3.MoveTowards(transform.position, pos, Time.fixedDeltaTime speed) Move there
|
0 |
Help with transform.lookat and camera? Vector3 mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.LookAt(mousePos) This will actually make the camera follow the mouse, but it goes crazy, the camera seems to spin in circles rapidly here is actually a gif of what is happening. https gyazo.com 952da6c28e644b7b0e6500a597b6804e preview Could anyone help me figure how how to fix it?
|
0 |
Implementing moving animation I faced the problem of attaching animation to the enemy. In the Animator window I added a "moveSpeed" (float) condition, so moving animation should turn on when moveSpeed is greater than 0.001. But after prescribing a reference to an Animator in the code, whatever I write further, a message pops up about the presence of compiler errors. Here's my script public int health public GameObject explosion public float playerRange public Rigidbody2D theRB public float moveSpeed public Animator anim Use this for initialization void Start () Update is called once per frame void Update () if(Vector3.Distance(transform.position, PlayerController.instance.transform.position) lt playerRange) Vector3 playerDirection PlayerController.instance.transform.position transform.position theRB.velocity playerDirection.normalized moveSpeed anim.SetFloat("moveSpeed") theRB.velocity public void TakeDamage() health if(health lt 0) Destroy(gameObject) Instantiate(explosion, transform.position, transform.rotation) What exactly do I need to write for the condition to work and the animation to play? Thanks for any help!
|
0 |
How to calculate the distance from the camera to make a GameObject fill the screen? How do you calculate the distance from the camera so that a GameObject fills the screen? I.e. Without reaching out of the view and regardless of screen orientation.
|
0 |
Why does my model render differently than its preview? I've been importing .fbx files that I made with 3DS Max 2012 into Unity, and it's quite neat to see my models running around in game. However, I can't help but notice that the models, as they're rendered in game, vary substantially from what they look like in the preview (and also what they looked like in 3DS Max). Observe In Game Unity Preview 3DS Max My gut tells me that I'm not setting up Unity's lighting system properly. What, then, do I need to do, to either my scene or my model, in order to get the left most picture to look like the middle one?
|
0 |
Replacing all objects in scene with another object I have around 100 objects (prefab A) in my scene, all in different positions. Is it possible to replace all of these objects with another object (prefab B), so that the prefab B objects are placed in the same position as the prefab A objects were? I want this done in the editor, not in game.
|
0 |
Update android game with new levels without replacing database So I've published a game for android users containing 400 levels and 2k users have completed or are playing it since. Now I'm going to update the game with 600 levels, but I don't want current users to lose their info in database. I just want to add more levels to the database if it exists in their phone. I'm using this code not to let database get replaced if it exists. public DataService() const string databaseName Constants.DbName if UNITY EDITOR var dbPath string.Format( "Assets StreamingAssets 0 ", databaseName) else check if file exists in Application.persistentDataPath var filepath string.Format(" 0 1 ", Application.persistentDataPath, databaseName) if (!File.Exists(filepath)) Debug.Log("Database not in Persistent path") if it doesn't gt open StreamingAssets directory and load the db gt if UNITY ANDROID var loadDb new WWW("jar file " Application.dataPath "! assets " databaseName) this is the path to your StreamingAssets in android while (!loadDb.isDone) CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check then save to Application.persistentDataPath File.WriteAllBytes(filepath, loadDb.bytes) elif UNITY IOS var loadDb Application.dataPath " Raw " databaseName this is the path to your StreamingAssets in iOS then save to Application.persistentDataPath File.Copy(loadDb, filepath) elif UNITY WP8 var loadDb Application.dataPath " StreamingAssets " databaseName this is the path to your StreamingAssets in iOS then save to Application.persistentDataPath File.Copy(loadDb, filepath) elif UNITY WINRT var loadDb Application.dataPath " StreamingAssets " databaseName this is the path to your StreamingAssets in iOS then save to Application.persistentDataPath File.Copy(loadDb, filepath) else var loadDb Application.dataPath " StreamingAssets " databaseName this is the path to your StreamingAssets in iOS then save to Application.persistentDataPath File.Copy(loadDb, filepath) endif Debug.Log("Database written") var dbPath filepath endif connection new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite SQLiteOpenFlags.Create) Debug.Log("Final PATH " dbPath) Also I've created a filed in database keeping database version to check what version the user has (like the version with 400 levels, the one with 600 levels or maybe more). What I don't know is what is the best solution to add more records to an existing database. Has anyone got a solution?
|
0 |
Colliders slightly intersecting each other any solution? Consider this simple scene In Unity, colliders slightly intersect each other. Typically, this isn't a problem. However, I want to make a custom character controller using a box collider and not a capsule collider. In the above scene, the floor is divided into 2 objects, each with their own collider. The playercontroller has their own box collider. And the problem if the box collider moves forward, it will clip with the seam on the floor, even though both floor objects have the same height. The box will stop moving as if it has run into a wall. If I keep adding force to the box, it will never move forward. It will stay stuck on the seam this only exists because the box is slightly inside the first floor collider, and it will hit the second collider of the floor like a wall. This only occurs because of collisions clipping. With most playercontrollers, a capsule collider is used and thus this problem doesn't exist. Is there a workaround? How can the box smoothly move across the floor without colliding with the seam? Notes This does occur with capsule colliders but rare and is not very noticeable. A possible solution would be to merge all the colliders of the scene into one, unified collider. It is extremely tedious and has its drawbacks. This occurs if I am moving the collider with both MovePosition(), AddForce(), or modifying the velocity position of the transform.
|
0 |
UI Button OnClick not playing AudioClip on gameObject Basically, I am loading an Audio Clip onto a game object's Audio Source in the Awake function when the game starts. When I click on the game object a UI comes up that basically has a Play button attached and all I want to do is play the Audio Clip on the Audio Source. The problem is I can see that there is an Audio Clip on the Audio Source at runtime and I can play it in the inspector at runtime but, when I click the button nothing happens. I have tried just referencing the gameObject in the OnClick() of the UI button and that doesn't work and I have also tried going through and getting the gameObject through GameObject.Find public void PlayMe() GameObject objs GameObject.FindGameObjectsWithTag("Voice log") foreach (GameObject obj in objs) if (obj.layer LayerMask.NameToLayer("Selected")) Debug.Log("Found it") if (obj.GetComponent lt AudioSource gt ().clip.loadState AudioDataLoadState.Loaded) obj.GetComponent lt AudioSource gt ().Play() Debug.Log("Should Play") Both of my Debugs print when I click the Play button.
|
0 |
Add Rigidbody and MeshCollider at runtime is it a bad practice? Good day. To simulate an explosion of a vheicle, I decided to do this When I need to explode veichle , at runtime, i add rigidibody for every single part of veichle (5 10 part door, wheel, hood etc), and collider (mesh). I detach them from parent I apply an AddExplosionForce to every single part This cause a big lag in my game, so I'm supposing this is not the efficent way. The other way could be to add Rigidbody and Collider in my prefab, with Rigidbody.gravity false, and isKinematic true, then enabling after explosion, but also this is not good for performance. Do you have some suggestions to achive my scope, considering that I could have a lot (5 10) enemy veichles at time on my scene ? Thanks
|
0 |
How can I easily create edit a level for a scrolling shooter game? I've been asking this question over the years many a time, but I still haven't found an answer when i search for one. Now I have slightly more knowledge of how programming is done and want to start making some full games. I want to start with a side scrolling shooter (space style like R Type Gradius). I have many ideas in my head for good levels, and i even have some basic 3d skills in Maya Blender to make the assets, but I do not know how best to formulate the levels. Lets say the space shooter has 30 levels. Each level might have about 10 15 enemy types and a boss on some levels. How best to store the location of all the enemies? (Same scenario for all the background objects,obstacles, powerup locations etc.) Is there a better way than manually building the whole level in a Unity Scene editor view? Another way I have tried is to set spawn positions for every single object as a Vector2 or similar in XML or JSON, but how i did it that seemed even harder to make the levels than just inside the editor (not even accounting for having to write the functionality to get the data from the textfile).
|
0 |
How do I play a particle system when moving? I have a car that I move with a Physics based movement (AddForce(), AddTorque(), etc...) and I have a simple particle system attached behind the car as follows I'd like to play this ParticleSystem whenever the car moves I tried checking if the car's rigidbody's velocity was greater than 0 if(m Rigidbody.velocity.z gt 0) m ParticleSystem.Play() if(m Rigidbody.velocity.z 0 amp amp m ParticleSystem.isPlaying) velocity.z 0 is unreliable, verified with Debug.Log m ParticleSystem.Stop() I then tried using Input if(Input.GetAxis("Vertical") gt 0) the car is moving along the positive z axis m ParticleSystem.Play() if(Input.GetAxis("Vertical") 0 amp amp m ParticleSystem.isPlaying) m ParticleSystem.Stop() These two methods don't work, I'm probably making assumptions on how Rigidbody.velocity behaves (when you stop the car for example, it becomes negative, so the particle system would keep playing until it reaches 0)
|
0 |
Tweaking screen transitions not to fire every time in Unity I'm making a simple screen transition system for my game which consists of two states firing the right clips (one for the starting half od the transition animation, one for the ending one) and a condition between the end and start one which is set to true when user wants to change the level (so that the Start animation would fire in the previous animation and the End in the new one). This is cool and all but poses two problems firstly, the game starts with the End phase animation which looks a bit weird. Secondly, since the Restart button in the main game just reloads the level, it causes the End transition to fire every time too which looks weird and out of place. How would I go about tweaking the Animator so that the End phase only runs when I actually change the level as opposed to when starting the game or reloading the current scene? Maybe there's some way to pass some kind of a parameter when loading a new scene that I'm not aware of? This way, I could just pass a flag like shouldFireEndAnimation so that it does not fire when the game just starts or a level restarts?
|
0 |
Unity2D Sprite Mesh Lighting Issue I am trying to make my 2D mesh render sprites with the same brightness as the original file. On the below picture, the mesh on the left is darker than the UI Image on the right, which is an exact likeness of the original file. How can I make the mesh as bright as the Image? So far, I've been looking into the following potential culprits Shader attached to the Mesh Global lighting settings Mesh renderer lighting settings The above image is with Environment Lighting Ambient Color at FFFFFF. Environment Lighting Ambient Color Intensity doesn't help. Increasing the shader's emissions can offset the darkness but it's not an ideal solution. All other lighting settings both globally and on the Mesh Renderer are default. At this point, I'm lost Any help would be much appreciated!
|
0 |
TextField Add in Editor does not display when put under if statement I've been trying to make a custom editor window in Unity and I needed to make an quot add TextField quot button. When I add a TextField directly (without requiring a button), it works. When I put it under if(GUI.Button()) it does not show up. Here's my code private static List lt string gt s new List lt string gt () private void OnGUI() if (GUI.Button( quot quot ) ) s.Add(GUI.TextField(new Rect(0,50,Screen.width,20), quot field quot ))
|
0 |
What edition of VS is installed by Unity and what are its capabilities? My brother just installed Unity on my desktop, and it seems like it installed Visual Studio 2017 as well. I was planning to install Visual Studio before this, so I was wondering what kind of version is this edition of VS? Is this like a bare bones version? Does it work like a standalone version without lacking features? Can I use it just as a regular IDE to program in? I typically program in C , and I never used Unity before, so I'm not sure if this version of VS is only suited for Unity.
|
0 |
Sending message to all players in room from Photon server? I need to send a message to all players in the room from a Photon server. Sending the message from a player would introduce too much latency so I need the server to collect data and distribute messages at a rate of 16 s without a player's influence. Is there a way to do this?
|
0 |
How to blend motions with Mecanim I'm struggling with Mecanim. My concern is to blend straight turning animations with strafe animation for a humanoid character. I downloaded a SampleAsset from unity and took Ethan character as example. The animator uses a blendtree which naturally blend idle walking running animations with a smooth turning left right animations. In this case the Ethan character cannot strafe. I'm trying to understand how to blend strafe movement with it's actual straight turning blending motion. Was I somewhat clear?
|
0 |
Overlap transparent particles without blending? (Unity) I'm trying to create a continuous output of light from an object (like the exhaust of a space ship), and I thought I'd use particles to achieve this. But I'm running into a problem with alpha blending. I'd like to decrease the particle system's alpha over time, but because there's such a high density of particles, they end up evaluating to a solid color for most of the system's duration. This blog post basically shows what I'm trying to achieve https mispy.me unity alpha blending overlap The idea is to use a stencil test to make sure pixels in a sprite particle aren't gone if they're overlapping another sprite particle. Pass Stencil Ref 2 Comp NotEqual Pass Replace Then the author adds an alpha cutoff to make sure transparent pixels on an underlying sprite don't prevent new pixels from being written. half4 frag (v2f i) COLOR half4 color tex2D( MainTex, i.uv) if (color.a lt 0.3) discard return color But this solution requires you to eliminate soft edges, so I'm thinking it wouldn't look good in a particle system. The author also hinted at an alternate solution involving ZTest, but I can't visualize what that would be.
|
0 |
Board like strategy map I want to make a strategy game like Risk. I want to use C for the mechanics and Unity for the graphics. My problem is that I don't know how to create the map itself and integrate it with C . I don't want a tile map but instead I want to create a customized world map, with different provinces defined by me. The map would be something like Imperial Glory, where you see it top down and then move your generals like chess pieces. I'm not implementing any real time battles at this point, it's just something really simple, like a board game. Could anyone please help me? I'll try to explain it a bit better I need to create a map of the Mediterranean basin that would cover all the land occupied by the Romans at the height of their empire. Next, I'll divide the map into 20 provinces (Italy, Gaul, Germania, etc), each one producing a set ammount of resources and population. I also want them to have their own wheather and buildings (for example, you can only train soldiers in provinces that have a barracks). I guess I'll need a text box popup that appears when you click on a province to display it's information. I'll also need some buttons to open dropdown menus or perhaps whole windows, for other purposes such as diplomacy, statistics, tech trees, etc. I wanted the map to be in 3d because I think it would be much more interesting to look at it in perspective instead of flatten 2d. I'm fairly new into Unity so I really admit that I have no idea where to start. Please, have patience with my ignorance. Thank you very much for all your help. If there are any doubts about my question, please let me know and I'll try to explain it better. PS I think I'll make it a turn based game since I think this would make it simpler to code and faster to run.
|
0 |
How can I instantiate enemies in a 2D game at a set Viewport Position before my camera enters the room? (Or alternative solution!) I'm currently working on a 2D game where I'm trying to pre populate my level with encounters, I want the enemies already in the room when the player enters. Right now the encounter is triggered upon entering the room when the camera bumps into the collider and the enemies are instantiated at the Viewport position, however because it does it while the camera is moving into the room the position is incorrect. Using hard values isn't an option because the maps could of course change and also I may want them randomly generated at some point. So I guess ultimately the problem is the camera not being in the right position when they instantiate and not wanting enemies to quot pop quot in once it is. Is there a way I can I instantiate an enemy at the same point on the screen regardless of resolution in each specific room at the start of the level? Encounters will have up to 3 enemies and they will always hold the same formation (with spots randomized to add diversity) Here is my instantiating code SerializeField public List lt GameObject gt levelEnemies new List lt GameObject gt () GameObject levelEnemy Vector3 enemyPosition Vector3 viewportPosition new Vector3(0.8f, 0.5f, 10f) Place on the screen I decided I want single enemies to appear Camera cam void Start() Debug.Log( quot Enemy Triggered quot ) cam Camera.main enemyPosition cam.ViewportToWorldPoint(viewportPosition) levelEnemy Instantiate(levelEnemies 0 , enemyPosition, Quaternion.identity) instantiate test enemy at the converted position navigation.DisableNavigation() Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3) Here's what should be happening when the enemy is instantiated (triggered manually through the editor once camera has been moved fully) Here is what happens when the camera collider bumps into the encounter collider Any help in the right direction would be much appreciated or a workaround! Here is what my camera collider looks like (Room 1) and my enemy encounter collider looks like (Room 3)
|
0 |
Moving spilling water inside a cup of glass I made a glass of water but there are somethings i didnt know how to do well, what i did is i put a mesh on the top of the glass to represent the surface of the water but it doesnt really work well with glass because if you look from the sides you wont really see that there is water in there, this is what i did the glass from the side as you can see it doesnt really work well in my case. I also tried putting an object that has the same shape as the cup inside to represent water but that would make it difficult for what i want to do next, because my next step would be to make the water rotate in the opposite rotation of the cup and make it spill if it reaches the top of the cup, and that is my second question how do i make the water spill from the cup? Any help is very much appreciated.
|
0 |
How can I check if component is enabled? using System.Collections using System.Collections.Generic using UnityEngine public class CameraInformation MonoBehaviour public string currentCameraState Start is called before the first frame update void Start() var components new List lt Component gt () foreach (var component in GetComponents lt Component gt ()) if (component ! this) var fullName component.GetType().FullName if (fullName.StartsWith( quot Cinemachine quot )) currentCameraState component. Update is called once per frame void Update() private void OnEnable() private void OnDisable() At this line I want to assign the string the component status if it's enabled true or false.
|
0 |
How do I procedurally animate a cell eating another cell? The entities in my game are soft body, amorphous cells. I'd like to create an animation where enemies are engulfed by the player's cell. That is, I want to generate a "cell eating another cell" effect. See this video for the type of motion I want https www.youtube.com watch?v iO vOFFf1uQ I'm considering using fluid dynamics to achieve this, but I'm lost as to where to start. I'm working in Unity2D, and Fluvio doesn't seem to provide what I need. Does anyone have advice on the best way for me to proceed?
|
0 |
Unity Failed to create decoder for ScreenSelector.png My game works fine in the editor, but when I build and run the build the view is zoomed in, my tilemap is missing, and the camera follows a gameobject it should not. How it should look and how it looks I checked the logs and this is the error I am served Failed to create decoder for 'C Users Hamuel The First Documents Jetplatformer Builds Builds Data ScreenSelector.png' 0x80070002 Further Investigation shows that ScreenSelector.png is absent from the path stated in the error. I cannot find anything that says what ScreenSelector.png is, or does. I am using the post processing stack by unity. Any help would be much appreciated!
|
0 |
How can I load multiple scenes in background? I want to queue the loading of multiple scenes in background and show all of them at the same time when all complete their loading. The only idea I have by reading the docs is to root all objects in every scene I want to load this way in a single GameObject that is disabled by default and when all my LoadSceneAsync finishes its work, I can them activate each scene root GameObject. Without doing that, I have all related scenes being loaded and being showed in the screen at different times and this is just not acceptable. I'm creating this question because I believe there must be a better way to accomplish that rather than rooting all the scene into a single game object.
|
0 |
Unity crashes when opening a project Why does this happen? I'm new to Unity development. I have installed Unity yesterday (2015 09 06). This is the error that I get
|
0 |
How can I scale a color component by Time.deltaTime and still fit it into a byte? I am confused about this issue, and I can't find why I get this and how to fix it properly from the Google searches I've tried. This is a short version of my code byte redtarget 70 byte greentarget 222 byte bluetarget 255 byte opacitytarget 1 byte redcurrent 0 byte greencurrent 0 byte bluecurrent 0 void OnMouseOver() redcurrent redcurrent redtarget Time.deltaTime greencurrent greencurrent greentarget Time.deltaTime bluecurrent bluecurrent bluetarget Time.deltaTime if(redcurrent gt redtarget) redcurrent redtarget if(greencurrent gt greentarget) greencurrent greentarget if(bluecurrent gt bluetarget) bluecurrent bluetarget theobject.GetComponent lt Renderer gt ().material.SetColor(" EmissionColor",new Color32(redcurrent,greencurrent,bluecurrent,opacitytarget)) Please ignore the other errors that could have been introduced when I copy pasted it to here. And this is the error I get As you see the error, "cannot implicit convert type float to byte", the problem is caused by Time.deltaTime that returns a float value, and I need a byte due to Color32. Is there any way to turn Time.deltaTime to byte? Or should I use another type of color that use floating point numbers? I'm a beginner with Unity so I'm sorry if this has already been asked somewhere as I said, I can't find it on the Internet.
|
0 |
Unity Sprite vertices in 3D world Rookie here, still learning the basics of Unity. I've been using a quad as a cursor sitting flat on top of a hilly terrain mesh. I've been getting the terrain angle by raycasting down at all four corners of the quad and finding where it hits the floor, then editing the quad vertices to shape it to the terrain angle. Probably not the ideal way but it works great for what I needed. So the next step is replacing it with a sprite. I changed from quad to a sprite renderer, and added a little animation to it. I went to edit the vertices and the setup is completely different (it seems to have 20 vertices now instead of 4). I did notice the SpriteRenderer has 4 triangles, but the points are Vector2s rather than Vector3, so I guess that won't work either since I'm applying it to a 3d world? Can anyone with experience point me in the right direction with this?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.