_id
int64
0
49
text
stringlengths
71
4.19k
0
Building a game project in C for Unity in VS? Say that a project needs to be created from scratch for later use in Unity, for scripts. What is the ideal way to setup this without using a template in Visual Studio? Can this be created in C with some simple classes and one or two game loops?
0
Saving settings when exiting the application I created a static class CustomPlayerPrefs, it has a WriteToDisk() method that writes the saves to disk. For saving I am using Application.quiting event RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen) static void Init() Application.quitting WriteToDisk But on android it never works. I know that applications are not closed but paused, but it doesn't even work when I restart the device or force the application to stop. How to fix this or how to make it better? Need IOS and Android support.
0
How do I correctly set up a Unity animation to move? I downloaded a custom .fbx model from the asset store, imported it to my project and placed it in my scene. I then created an animator controller and added it to the object. To get the animations (that came with the model) into the animator tab, I dragged them onto the model in the hierarchy. I then set the one animation to default and pressed play, but in the game window, the model didn't move. What might be going on? The only time it did something was when I set it to "play from start" but that made it go through all the animations. I'm quite new to Unity 4. If you need any extra information, please ask.
0
Jerky Character movement after adding mouse orbit script I added a custom mouse orbit script to my project. When the right mouse button is clicked, the camera can be rotated around the player. The issue, after this change, is my player movement has become jerky choppy and not smooth. If I remove my mouse orbit script, player moment is back to normal i.e smooth. I can't seem to pin point what is causing this jerky movement withing MouseOrbit script Video demo Code This is where we initialize our script void Start() Initialize() This is where we set our private variables, check for null errors, and anything else that needs to be called once during startup void Initialize() h this.transform.eulerAngles.x v this.transform.eulerAngles.y cameraTransform this.transform cam Camera.main smoothDistance distance timerot TimeSignature((1 rotationDampening)) 100.0f NullErrorCheck() We check for null errors or warnings and notify the user to fix them void NullErrorCheck() if (!viewTarget) Debug.LogError("Please make sure to assign a view target!") Debug.Break() if (collisionLayers 0) Debug.LogWarning("Make sure to set the collision layers to the layers the camera should collide with!") This is where we do all our camera updates. This is where the camera gets all of its functionality. From setting the position and rotation, to adjusting the camera to avoid geometry clipping void Update() if (!viewTarget) return if (Input.GetMouseButton(1)) Cursor.lockState CursorLockMode.Locked h Input.GetAxis("Mouse X") horizontalRotationSpeed Time.deltaTime v Input.GetAxis("Mouse Y") verticalRotationSpeed Time.deltaTime h ClampAngle(h, 360.0f, 360.0f) v ClampAngle(v, minVerticalAngle, maxVerticalAngle) Debug.Log ("value of h " h) newRotation Quaternion.Euler(v, h, 0.0f) else Cursor.lockState CursorLockMode.None if (Input.GetKeyDown(KeyCode.D)) h transform.eulerAngles.y 90 newRotation Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z) if (Input.GetKeyDown(KeyCode.A)) h transform.eulerAngles.y 90 newRotation Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z) We set the distance by moving the mouse wheel and use a custom growth function as the time value for linear interpolation distance Mathf.Clamp(distance Input.GetAxis("Mouse ScrollWheel") 10, minDistance, maxDistance) smoothDistance Mathf.Lerp(smoothDistance, distance, TimeSignature(distanceSpeed)) We give the rotation some smoothing for a nicer effect smoothRotation Quaternion.Slerp(smoothRotation, newRotation, TimeSignature((1 rotationDampening) 100.0f)) newPosition viewTarget.position newPosition smoothRotation new Vector3(0.0f, height, smoothDistance) Calls the function to adjust the camera position to avoid clipping CheckSphere() smoothRotation.eulerAngles new Vector3(smoothRotation.eulerAngles.x, smoothRotation.eulerAngles.y, 0.0f) Vector3 dir new Vector3(0, 0, distance) cameraTransform.position newPosition cameraTransform.position viewTarget.position smoothRotation dir cameraTransform.rotation smoothRotation Time Signature with speed as input private float TimeSignature(float speed) return 1.0f (1.0f 80.0f Mathf.Exp( speed 0.02f))
0
UI clicks hitting game objects below I have a canvas with a panel with set width height inside. The canvas rendermode is set to ScreenSpace Overlay. My clicks on the panel are falling through and hitting the game objects below triggering their mouse events. The little green circle is a Sprite with the following event public void OnMouseDown() Debug.Log("click") Vector3 newPos Camera.main.WorldToScreenPoint (this.transform.position) newPos.x panel.GetComponent lt RectTransform gt ().rect.width 2.0f newPos.y panel.GetComponent lt RectTransform gt ().rect.height 2.0f panel.transform.position newPos I've been reading through the docs but I'm missing something... How do I stop my clicks hitting the game objects below the panel?
0
get back unity default interface i installed unity recently .and interface of unity looks like that see the image in all tutorials i see on the internet. but this is my one(I'm not in the game tab I'm in the scene tab)it's look like brown and i don't like it.i want default interface the interface in first pic which is black .how can i get black interface back ?
0
C in Unity with dependencies I am currently creating a c program to eventually use in Unity. This c program contains references to libraries like OpenCV and dlib, referenced with a include statement which calls in other files, which are installed on my machine. My question is How do you compile your c project so that it runs in Unity completely self contained? i.e no reference to external files are needed, and all that are references are included within the program. Is there a specific tool to use, or a useful tutorial on the net? Thanks for the help.
0
Nested Coroutine Movement is slugish So I have a few AIs walking between waypoints. What I want to accomplish here is to have my AI move to the waypoint, when he reaches it, he must stop, wait for a few seconds (Not walk just stand still), then move to the new waypoint. Lets pretend he was observing while at this point. Issue right now He moves to the waypoint with a twitchy behavior where he would usually avoid objects, sometimes gets stuck while moving to objects or its like the AI cant decide what to do, move or stand still. Without the Waitforseconds method the AI avoids objects perfectly. Please note I want to use Coroutines for this even if you wouldn't use recommend it for this. If you have a suggestion for using Unity's Random to decide when he stands still after reaching a point or not, that would be a bonus for me. We define all fields and call the FSM() Coroutine with a default patrol state in the Start Method, from Here, This is my Code Update Implemented A Boolean IsMoving variable This works to some extent. The AI now moves perfectly to the waypoint. The Twitching however continues once the AI reaches the waypoint vicinity until he leaves the waypoint radius The movement then continues to a normal state. IEnumerator FSM() while (alive) switch (state) case State.PATROL StartCoroutine(Patrol()) break case State.CHASE Chase () break default break yield return null lt summary gt Patrol will move to a waypoint if too far, otherwise move to a next waypoint if one is reached. lt summary gt IEnumerator Patrol() Sets a common speed for the agent to move in. agent.speed patrolSpeed Now we want to check the position the character is at vs the waypoint location If i am too far, move closer My Position Waypoint Indexes We Set Multiple if (Vector3.Distance (this.transform.position, waypoints wayPointIndex .transform.position) gt 2) Telling the navmesh agent where to go. agent.SetDestination (waypoints wayPointIndex .transform.position) false, false Specifies if we are jumping or crouching character.Move (agent.desiredVelocity, false, false) Now we want to check the position the character is at vs the waypoint location If i am at a waypoint, move to a new index else if (Vector3.Distance (this.transform.position, waypoints wayPointIndex .transform.position) lt 2) character.Move (Vector3.zero, false, false) yield return new WaitForSecondsRealtime (6.0f) wayPointIndex 1 Move towards a new waypoint in the waypoint indexes flags Move to a random waypoint wayPointIndex UnityEngine.Random.Range (0, waypoints.Length) else Doesn't move, plays the idle movement We know this point wont be reached but if so... character.Move (Vector3.zero, false, false) yield return null
0
Unity HDRP draw order doesn't change when asset is set to higher priority? I don't like the way that light got baked into part of my mesh. It might make sense for me to try to blacken that area of the lightmap in Photoshop, but first I tried to just hide it with a probuilder object that uses an unlit black material I changed the priority of this object from 0 to 1, higher than any object in this scene, or at least the floor object, but it does not draw over the floor in Game View. I tried using a higher number and setting it beneath the floor instead of intersecting it, but it is just being rendered the usual way. Also note that I have a UI Canvas component being drawn in ScreenSpace, in case that has anything to do with it. How can I get this object to render in front of the floor while it is intersecting the two front faces, like in the picture?
0
Gravity well shader for Unity2D I'm trying to find or create a gravity well distortion shader for Unity. I've been looking around and all I can find are "lenses" which bend space around a black hole. I'd rather have a distortion that "pulls" or "bends" the image behind into a small hole. Essentially, what this would look like if viewed from above (ignoring the sphere) I can't seem to find any examples or a common terminology for it.
0
Unity 5 Virtual Reality Supported Text shimmering aliasing in GearVR I've spent the last 2 days trying to figure this out but have not come up with a conclusion. I'd appreciate if anyone has experienced the same and any thoughts. Basically, I'm noticing that if I have a scene with text in it (world canvas and UI text component), when I build for GearVR with Unity's VR support, the text aliases like crazy. To be honest I'm not even sure 100 if it is plain old aliasing. The text just constantly shimmers. I tried moving things around in case it was z fighting but it seems it is not. I tried enabling anti aliasing from the quality settings and neither does it seem to make a difference. I tried tweaking the Canvas Scaler Dynamic and Reference pixels unit settings (which are not entirely clear to me from the docs btw). But at most, I was able to make the text slightly blurry as mentioned in the Unity VR guide and it barely helps. I tried making the canvas and text huge and then scaling the canvas down to 0.05. finally I tried making my text bold and bigger. And that seemed to mitigate the shimmering to a certain extent but not 100 . But I've seen Unity apps for GearVR that don't exhibit this shimmering issue. So I am wondering what else might I be missing. I'm on 5.3.3.p3 if it makes any difference.
0
How do you actually build once you encounter the 'Too many method references' error? I'm making a very simple mobile F2P arcade game in Unity After adding SDKs for facebook, gamesparks, firebase, and appodeal I coud not build, getting the "Too many method references 76221 max is 65536" error. The solution from Too many field references 70613 max is 65536 is apparently to export an ADT project, import it into Android studio and go from there. I built following these instructions, and after building my Android studio project had errors relating to the facebook SDK similar to here Unity exporting android project with Facebook SDK issue The solution proposed there is to copy all the .aar from your Unity project to files to the Android studio project and add lines to the build.gradle file referencing them, which I did. After doing all that the 4 facebook related errors are gone but one new one appears Error more than one library with package name 'android.support.v7.appcompat A proposed solution for that is to search for the offending file and delete it in windows explorer but there is nothing with that name in my Android studio project folder. I tried removing some .aar files with appcompat in the name but I ended up reverting to the previous 5 facebook errors This whole thing has been a bit of a nightmare and I have no idea what I am doing. I would love to hear from someone who encountered this error and got past it and was able to build their game again. Surely this must be a common issue for anyone making a commercial mobile game in Unity?
0
Unity Cube edges are jagged I am new to Unity. I have a basic setup following Brackeys tutorial. When in game mode, I see the red cube having jagged edges. I tried increasing the antialiasing in Unity to 8x but it did not work. I also tried turning on antialiasing in my Nvidia control panel. But the issue still persists.
0
How to find an object which is added to a scene only when game starts? I'm looking for some advice how to find an object which is added to scene only when the game starts? Before start it isn't in Scene hierarchy. It's prefab.
0
Player going out of boundaries So, I been following up the Space shooter tutorial on Unity, I had an issue where the project was acting up with an alpha version, so I was able to get a version that worked on a old release and applied all the new things I developed But suddenly, my ship is acting up when getting closer to the boundary of its movement This is the player movement code public class playerMovement MonoBehaviour public float speed 0.0f public float tilt public Boundary boundary void FixedUpdate () float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") var movement new Vector3(moveHorizontal, 0.0f, moveVertical) var rigidBody GetComponent lt Rigidbody gt () rigidBody.velocity movement speed rigidBody.position new Vector3 ( Mathf.Clamp(rigidBody.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp(rigidBody.position.z, boundary.zMin, boundary.zMax) ) rigidBody.rotation Quaternion.Euler(0.0f, 0.0f, rigidBody.velocity.x tilt) System.Serializable public class Boundary public float xMin, xMax, zMin, zMax And this is the player boundary properties It used to work previously moving forward to the alpha, now I'm working on 2019.2.0f1, but since working on the alpha this is the behaviour I'm having As you can see, getting closer to the player boundary, takes the player out of the play area, and I can't determine why this might be happening. I already tried removing the Math.Clamp, as I though there migth be bug with the function in this version, but even without it, the problem is present.
0
Unity directional light for a day night cycle on a hex sphere So I am trying to create a Day Night cycle on a sphere but it doesn't work the way I want it to. As the model is hex tiled, you see the edges of the hex tiles also lit up like below. I am using a directional light source for the same. I don't want the above effect. I want it to ignore the edges and just be a straight line instead. Something like below Is there a way inside Unity that I could achieve this effect just using the lights?
0
Making plane with quad I'm a beginner Unity 3d developer. I want to keep quads one aside another touching each other and use that as a road for making an endless runner game. The problem is each of the quads have their own box collider thus the car bounces a little bit sometimes. Is there any way to get those stuff connected with each other and make the whole thing behave like a single plane? I know using a big box collider covering all the quads in the repeating unit is gonna work but I don't want to use that.
0
current value of x for vector2 game object I just need to push my game object in y direction not in of its x position,I need to assign it a new position but unable to access its current x position value so that can make it fix on its x position... please help I tried this Vector2 curScreenPoint new Vector2 (need the current x position of game object , Input.mousePosition.y) Vector2 curScreenPoint new Vector2 (0, Input.mousePosition.y) Vector2 curPosition Camera.main.ScreenToWorldPoint (curScreenPoint) transform.position curPosition
0
Get the tile in unity tile map I am trying to get the sprite of a tile in unity from where a raycast hits. Right now it only works in some cases, and always in positive x. This is my current code. Vector3Int LocalPos new Vector3Int((int)hit.point.x, (int)hit.point.y,0) Sprite spr tilemap.GetSprite(LocalPos) From what I can tell it gets the correct sprite. Edit I removed pointless code
0
How to offset a 2D GameObject by a pixel amount? I'm extremely new to game creation. I'm playing around with creating a 2D Unity game. The scene is setup from the default Unity 5 2D template. Following a tutorial, I've created a TerrainManager GameObject and Script. The script instantiates tiles and sets their position using a standard double loop. I've found a 2D isometric tile set. Each tile is visually rendered as rotated around the vertical axis by 45 degrees, creating more of a diamond shape rather than a square. This requires that every second tile be offset by half the tile width on the x axis, and half the tile height on the y axis. As each tile is of a different height, one can not simply offset the tile on the Y axis by half its height. Each terrain "layer" is 16px tall in the PNG. Some PNGs have a single "layer", some have multiple "layers". (For instance, a single layer water tile is 83px in height, while a dual layer "grass on top of dirt" layer is 99px in height. As the game object expects the transform.position as a Vector3 in (I assume) game units, I do not know how to compose this using pixel values. So the question I have is, how do I achieve the 16px y axis offset of the game object? I'm more than happy to provide additional details if needed.
0
Unity WebGL Canvas only loads on select machines https herbertjoseph.com There is a WebGL build in the background of this site, and it doesn't seem to laod on my iPad. I've asked a few people to visit and check it out, and some have said that the scene doesn't load on their workstations either... I've checked the console of the builds, and found no egregious errors. Most browsers, even mobile, support webgl now... How can I ensure it'll work across most all devices?
0
How to split 2 teams for a FPS death match game in Unity? I'm making a playable one level only FPS death match game in Unity. I'm in the part where the AIs now can find and shoot their own target and keep looping to find targets until nothing left. Every AIs and including player were tagged with tag "Target" for the AIs to randomly find their target. (I already excluded self finding). Now I want to split them in 2 teams. And here is the thing that I keep wondering. Should I use 2 tags for 2 teams (like team red, team blue for ex) then make and attach 2 scripts separately for each AI in the team (the logic in the script will be like "team red" will find game object with tag "team blue" and vice versa). Is that how it works? Is there more efficient way or should I say, "smarter" way to work around this problem? Here is the script if you need to know more about what I am trying to say https github.com Bezari0us FPS AI Behaviour
0
How can I make all the objects to move between the waypoints? using System.Collections using System.Collections.Generic using UnityEngine public class MovementSpeedController MonoBehaviour public List lt Transform gt objectsToMove new List lt Transform gt () public List lt Vector3 gt positions new List lt Vector3 gt () public int amountOfPositions 30 public int minRandRange, maxRandRange public bool randomPositions false public bool generateNewPositions false public float duration 5f public bool pingPong false private void Start() if (generateNewPositions (positions.Count 0 amp amp amountOfPositions gt 0)) GeneratePositions() StartCoroutine(MoveBetweenPositions(duration)) private void GeneratePositions() for (int i 0 i lt amountOfPositions i ) if (randomPositions) var randPosX UnityEngine.Random.Range(minRandRange, maxRandRange) var randPosY UnityEngine.Random.Range(minRandRange, maxRandRange) var randPosZ UnityEngine.Random.Range(minRandRange, maxRandRange) positions.Add(new Vector3(randPosX, randPosY, randPosZ)) else positions.Add(new Vector3(i, i, i)) IEnumerator MoveBetweenPositions(float duration) for (int i 0 i lt positions.Count i ) float time 0 Vector3 startPosition objectsToMove 0 .position while (time lt duration) objectsToMove 0 .position Vector3.Lerp(startPosition, positions i , time duration) time Time.deltaTime yield return null objectsToMove 0 .position positions i Now only the first object in objectsToMove is moving between the waypoints but I need all of the elements of objectsToMove to move between the waypoints. If I try this objectsToMove i .position Vector3.Lerp(startPosition, positions i , time duration) I will let out of bound index exception because the size of objectsToMove is not the same the size of positions i
0
Unity objects behaving different when NetworkTransform is used to sync movement I am experimenting with some simple multiplayer networking in unity. Currently I have a plane object as the ground, and a cube prefab as the player object. I have a network manager with round robin spawn and the built in HUD. The cube has simple movement control (up down is forward backward, left right turns the cube). I can successfully start a game, build it, and add a client from the built app. However, when movement gets sent over the wire, the non local player cubes in the game appear to "tilt forward," seemingly from the drag that the cube creates against the plane while moving. Strangely, when moving the local cube, no such tilt is experienced. Here is a gif which illustrates In the above gif, the cube being moved is in the foreground window. Notice how the cube is only tilting in the other window. Here is Update function of the Cube controller script Update is called once per frame void Update () Change translation float moveAmount CrossPlatformInputManager.GetAxis("Vertical") Vector3 deltaTranslation transform.position transform.forward movementSpeed moveAmount Time.deltaTime localRigidBody.MovePosition (deltaTranslation) Change rotation float turnAmount CrossPlatformInputManager.GetAxis("Horizontal") Quaternion deltaRotation Quaternion.Euler (turnSpeed new Vector3 (0, turnAmount, 0) Time.deltaTime) localRigidBody.MoveRotation (deltaRotation localRigidBody.rotation) MoveCamera() The ground is a plane with a rigid body and doesn't have a network identity or transform. How do I stop the dragging from occurring and have the behavior be consistent across both instances of the game? The full code to this project as it is right now is here https github.com andyperlitch blocks multiplayer Thanks!
0
Unity mailchimp Klaviyo subscription form Hey everyone so i want to add a subscription form on my game. so far i can send data to a database and display them on a leaderboard, i found a similar question here but its a bit outdated. Ideally i would like to use klaviyo but since this is the only lead i have i might want to get familiar with how it works! using System using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class MailingScript MonoBehaviour public InputField emailField public InputField nameField public void onClick() StartCoroutine(SendToMailChimp()) private IEnumerator SendToMailChimp() WWWForm form new WWWForm() form.AddField( quot EMAIL quot , emailField.text) form.AddField( quot b 0f079b7af1cef143021ff4236 6cd74c0a6a quot , nameField.text) form.AddField( quot subscribe quot , quot Subscribe quot ) UnityWebRequest www UnityWebRequest.Post( quot https slaga games.us1.list manage.com subscribe post?u 0f079b7af1cef143021ff4236 amp amp id 6cd74c0a6a quot , form) yield return www.SendWebRequest() if (www.isNetworkError www.isHttpError) Debug.Log(www.error) else Debug.Log( quot Registered quot ) this is my code so far but it wont do anything. i have a same code for the database which works!
0
Problem when trying to use rb.MoveRotation in Unity OK so I learned that rb.MoveRotation is different from rb.transform.Rotate(). But I am having trouble using it and hoping you can help me. I usually use transform.translate(Vector3.forward) (after using transform.Rotate(x,y,z)) , so that I know that will always make object move in the direction its facing. But this isnt working when I use rb.MovePosition. The object rotates when i remove the MovePosition line, but then for some reason doesn't when its there. I've tried multiple things as you'll see in the code. I cant understand also why, if I use the bottom commented attempt in my code, and then press D in game, it will go in the direction its facing and then get stuck. I've commented in my code to try to explain whats happening. What is the correct way to move the position of the player now I am using MoveRotation? I want to base my movement of the direction that the object is facing and not in world coordinates. Thanks void HandleKeys() if (Input.GetKey(KeyCode.A)) if (!facingLeft) rb.MoveRotation(Quaternion.Euler(0, 90,0)) facingLeft true rb.transform.Translate(Vector3.forward speed Time.deltaTime) if I remove this line, the character does turn and face left . But when its in he doesn't and both keys make him move right (and face right) also tried rb.MovePosition(transform.position Vector3.forward speed Time.deltaTime) this results in it going Vector3.forward in world coords rb.MovePosition(transform.position rb.transform.forward speed Time.deltaTime) this makes him go RIGHT gt ?? and the objects facing RIGHT why???? if (Input.GetKey(KeyCode.D)) if (facingLeft) rb.MoveRotation(Quaternion.Euler(0f, 90f, 0f)) facingLeft false rb.transform.Translate(Vector3.forward speed Time.deltaTime) if i leave this in, and the one marked above, then it works but only once, so if I press A then, D he heads right but wont turn round, if I press D first he just goes right if (Input.GetKeyDown(KeyCode.Space) amp amp IsGrounded()) rb.AddForce(Vector3.up jumpForce, ForceMode.Impulse)
0
How to adapt my mobile game for different aspect ratios? Before I start, I'd like to note that I work in the Unity Engine, but the basic theoretical stuff should be similar just about anywhere. It's not really hard to get the game's camera World view or UI to scale to many types of devices with different pixel counts as long as they have the same aspect ratio. But devices in general, and especially mobile phones, have all sorts of variables, aspect ratios can be anywhere from 16 9 to 20 9, and there are all sorts of different types of notches too. For this question I'm primarily going to ask about the aspect ratio and not touch on notches for now to stay on topic, but if you could explain how I can handle notches, that would be a good bonus. So, how do I make a game for a mobile device, that can be played in portrait and horizontal mode, on anything from small 16 9 screens like the Samsung Galaxy S5, to larger 19 9 aspect ratio (A notch) in the Google Pixel 4? Unfortunately due to IP restrictions, I can't show art, and I can't reveal the core mechanic of the game. but I have created a general mock up of what the ideal world UI scaling would look like The UI needs to be able to scale to the edges of the display like any other game. But the edges of the world need to be the edges of the screen (There needs to be walls that appear at on all 4 edges of the screen), however because the game is physics based, the walls can't actually move else it would cause inconsistencies between in the game from device to device. I know what I'm talking about here is primarily theoretical, but as someone who doesn't know much about aspect ratios (or notches), how can I ensure my game works consistently on this range of devices?
0
OnTriggerEnter is it called in both collider object? I've 2 object a Player and a Bonus object. In both script I've "OnTriggerEnter" script. In Player OnTrigger I Take Bonus value and add it to my Player (health, point, ammo) In Bonus OnTrigger I Play audio (when take it), Play Particle System and so on... But, it seems it's called only Player's OnTriggerEnter ... Why ? In Unity, if I have OnCollision OnTrigger enter in both object, which event is called ? Both ? Thanks
0
Unwanted rotations with transform.RotateAround I didn't tough i would have issues with this, but unfortunatly I did. I have a Character (which is more a pile of cube) with a body, a empty GameObject for each leg attached to the body with a join and 2 cubes for leg too. The body and the two empty gameobject are child of a Empty gamebject. The 2 cube that represent leg are both child of one of the empty gameObject. What I want to achieve is to rotate the leg around the position of its empty parent by doing this if(Input.GetKey("l")) l leg.transform.RotateAround(l leg.transform.parent.transform.position, new Vector3(1,0,0), 75 Time.deltaTime) unfortunatly, I only want it to rotate on x, but all of the axis are changing, which lead to unwanted rotation. Now, I know rotations aren't independant like translations, but I don't know how to fix this. If possible, i'd prefer to rotate locked joint via script but I have now idea how, I haven't seen anything about it when I looked up 2
0
Understanding pixel art in Unity 2d I am struggling to understand the basics behind pixel art in Unity. I understand what a unit is, and that if I draw my sprite with 16x16 pixels, I should set PPU to 16. Take stardew valley for example, in the image below you can clearly see that the player is not square. The creator of the game said he made everything in 16x16, but then how is there so much detail in the characters? Surely you do not patch several 16x16 squares together to make a character (as you would with a tilemap)? What is the "common" way of dealing with things that are not square, like the characters in the image. Do you just make 16x32 sprite and set PPU to 16? Wont that make it look a bit weird next to 16x16 sprites? Do you generally pick one size (i.e 16, 32, 64) And then stick to that for everything in the game? The visual Issue I've seen is this, where a 32x32 sprite looks very out of place (too sharp) next to a 16x16 sprite. So I am wondering, how do you mix sizes wihout getting this effect where one image looks much sharper than the other. If I for example wanted a character to be 16x32, or any non square value, when my tiles are 16x16
0
Unity What does the green line gizmo signify? When I place a point light it shows this green gizmo that ends in the terrain. What's the name of this gizmo? What does it signify?
0
How can I create a pressure pad in order to open a door? I'm making a 2D platformer with Unity. I want to create a pressure pad in order to open a door and I want the door to open when the player is on the pressure pad and close in few seconds after the player leaves the pressure pad. I've tried different ways but none of them worked. In this case, the door should be open upwards and close downwards. Also, I already created some animations (idle, open and close) for the door but don't know how to make a connection between these two objects then play the animations at the proper time. Thank you in advance. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Events public class PressurePad MonoBehaviour public UnityEvent OnActivate public UnityEvent OnDeactivate int objectsInContact IEnumerator Timer() yield return new WaitForSeconds(6) OnDeactivate.Invoke() void OnTriggerEnter2D(Collider2D other) objectsInContact if (objectsInContact 1 amp amp OnActivate ! null) OnActivate.Invoke() void OnTriggerExit2D(Collider2D other) objectsInContact if (objectsInContact 0 amp amp OnDeactivate ! null) OnDeactivate.Invoke() StartCoroutine(Timer())
0
Digital Speedometer wrong update Unity Hi I am making a digital speedometer and I want it to change like a normal meter like if speed is 10 on meter and the new speed is 50 it does not just show 50 on text instead gradually increase it. here is what I have done int speed int textSpeed int speedfinal public Text text Update is called once per frame void Update() speed GameObject.Find("gamePlayManager").GetComponent lt gamePlayManagerScript gt ().userSpeed textSpeed int.Parse(text.text) speedfinal (int)Mathf.Lerp(textSpeed, speed, 0.1f) text.text speedfinal.ToString() I am not sure if lerp is a good choice here to change text but that is what I know but it is adding 9 less then the orignal speed. Any idea how to do this. thanks.
0
How do I switch between different Update behaviour states in Unity? I have a bird entity that needs different update rules when it's moving or dying (among potentially other states). I want to avoid making my Update method a clutter of if else branches like this void Update() if(state movingState) Do moving logic. else if(state dyingState) Do dying logic. else if... Instead, I thought I could make a base class for all my bird behaviours, then derive classes for each state with their own update functions, and use the appropriate derived version based on the current state. public class BirdBaseModel MonoBehaviour void Update() ... public class BirdMoving BirdBaseModel void Update() ... public class BirdDying BirdBaseModel void Update() ... My BirdBaseModel is attached to the bird game object. Based on game states, I want to dynamically reference it in the GameController class. BirdBaseModel b if(State 1) b new BirdMoving() else if(State 2) b new BirdDying() Based on the above logic, I want to call the Update function of that particular class. How do I invoke the Update of the subclass?
0
Make an animation repeat X times I am using Unity Mecanim and I would like an animation ( walking animation about 2 seconds longs ) to repeat X times before moving to the next animation. How can I achieve this?
0
Accessing vertex Input in surf directly without vert's out parameter In Tessellation Shader I can get the vertex Input in vertex shader as follows o.worldPos v.vertex.xyz But how do I get the worldPos directly without filling the out parameter in the vert function. Asking this because the shader is a DX11 Tessellation one and out parameter in vert function is not available at all. basically I want Initialize my Input shader and pass It to surface shader In vertex shader.I can do It but It's different In Tessellation shader so I need to Accessing vertex position in surf directly without vert's out parameter. Shader "Tessellation Sample" Properties EdgeLength ("Edge length", Range(2,50)) 15 MainTex ("Base (RGB)", 2D) "white" DispTex ("Disp Texture", 2D) "gray" NormalMap ("Normalmap", 2D) "bump" Displacement ("Displacement", Range(0, 1.0)) 0.3 Color ("Color", color) (1,1,1,0) SpecColor ("Spec color", color) (0.5,0.5,0.5,0.5) SubShader Tags "RenderType" "Opaque" LOD 300 CGPROGRAM pragma surface surf BlinnPhong addshadow fullforwardshadows vertex disp tessellate tessEdge nolightmap pragma target 4.6 include "Tessellation.cginc" float EdgeLength float4 tessEdge (appdata full v0, appdata full v1, appdata full v2) return UnityEdgeLengthBasedTess (v0.vertex, v1.vertex, v2.vertex, EdgeLength) float Displacement struct Input float4 position POSITION float3 worldPos TEXCOORD2 Used to calculate the texture UVs and world view vector float4 proj0 TEXCOORD3 Used for depth and reflection textures float4 proj1 TEXCOORD4 Used for the refraction texture void disp (inout appdata full v, out Input o) UNITY INITIALIZE OUTPUT(Input,o) o.worldPos v.vertex.xyz o.position UnityObjectToClipPos(v.vertex) o.proj0 ComputeScreenPos(o.position) COMPUTE EYEDEPTH(o.proj0.z) o.proj1 o.proj0 if UNITY UV STARTS AT TOP o.proj1.y (o.position.w o.position.y) 0.5 endif sampler2D MainTex sampler2D NormalMap fixed4 Color void surf (Input IN, inout SurfaceOutput o) o.Albedo float3(0,0,0) ENDCG FallBack "Diffuse" but I have error Shader error in 'Tessellation Sample' 'disp' no matching 1 parameter function at line 173 (on d3d11)
0
Why do I get compile errors in every project, even new ones, and how do I fix them? I downloaded the latest version of Unity as you can see in the snap. I just created a new project and when I press the play button it shows compile error even if I have not created anything nor any script. I receive 4 blank errors in Unity and one non critical. I am not able to clear them except the non critical one.
0
How to create a wind tunnel sky diving effect like in Fortnite? I am using Unity and I want to create a sky diving effect, as if you were looking directly down while falling and have the wind fly past you. My guess is I have to do something with the particle system. How can I do this? An example is this video of Fortnite https youtu.be JFHs3uNJ9Cw?t 23s, you can see the wind flowing from the characters hands and feet.
0
How can I resolve this error I'm getting in my movement script? For my player controlling script, I have attempted to do it so the player can only jump two times, I've not had any errors in the script itself but when I save it and go back on Unity, the error I keep getting is this error CS0120 An object reference is required for the non static field, method, or property Collision.gameObject This is my code using System.Collections using System.Collections.Generic using UnityEngine public class playerController MonoBehaviour public float speed public float power private Rigidbody2D rb int numberofJumps 0 public int doubleJump 2 void Start() rb GetComponent lt Rigidbody2D gt () numberofJumps doubleJump void Update() if (Input.GetKey(KeyCode.D)) rb.AddForce(Vector3.right speed) if (Input.GetKey(KeyCode.A)) rb.AddForce(Vector3.left speed) if (Input.GetKeyDown(KeyCode.W)) if (numberofJumps gt 0) Jump() public void Jump() rb.AddForce(Vector3.up power, ForceMode2D.Impulse) numberofJumps 1 void OnCollisionEnter2D(Collision2D col) if (Collision.gameObject.tag "ground") numberofJumps doubleJump The error seems to be specifically regarding this line if (Collision.gameObject.tag "ground")
0
Can I apply a force to particles from a script? I'm working on a game which involves streams of electrically charged particles, being manipulated with electric and magnetic fields. Since I want a large number of small objects coming from an emitter and lasting a limited amount of time, a particle system seems like the way to go. My only problem now is how to apply the force? Suppose, for example, I have a charged object somewhere in the scene I want to apply a force toward it, varying with the radius squared. If my particles were Rigidbodies, applying this force in the FixedUpdate would be easy is there a way to do the same to an individual particle?
0
Changing coordinates of the object with velocity preservation In Doodle jump, if a player jumps over one side of the screen he appears on another side with preserved velocity and other physical parameters. I made two trigger colliders on the sides of the screen with OnTriggerEnter2D method. private void OnTriggerEnter2D(Collider2D collision) collision.transform.position new Vector3(collision.transform.position.x 0.95f, collision.transform.position.y, collision.transform.position.z) If I multiply collision.transform.position.x by 1f then on collision some glitching occurs. It gets stuck for a second. I believe this happens because when player is moved to the other side there is another collision detected and he is thrown back. Is there a more elegant way of handling this instead of multiplying by 0.95f? Final solution Tooltip("Controls where is the edge of the level where player is trasfered on the opposite side of the level.") SerializeField private float xAxisMovementConstraints private void DetectBoundryCross() if (transform.position.x lt ( xAxisMovementConstraints)) transform.position new Vector2(transform.position.x (xAxisMovementConstraints 2f), transform.position.y) else if (transform.position.x gt xAxisMovementConstraints) transform.position new Vector2(transform.position.x xAxisMovementConstraints 2f, transform.position.y)
0
Is it wrong to be creating new objects in Update()? I'm using Unity and sometimes I'm using th new keyword in Update, like new Vector3() etc... I wonder is this causes memory leak? I mean in every frame a new Vector3 is created. If this is the way of working that means there are thousands of Vectors created in memory. Is it true or do I think wrong?
0
How can I fix a GameObject along one axis only when it is part of another object in Unity? Hello I have an Object player and inside player, I have an object Boundary which is supposed to follow the player as he moves up or down only? (As the player moves right or left I don't want the boundary object to move. How can I do it?
0
I'm having resolution issues does my math suck? There are a lot of scripts involved so I'm just going to give a generalized description of the process. First, a 1x1 square tile is created. Second, that tile is placed out of the way, and 16 x 10 (160) new tiles are created starting at the (0,0) position and building outward in positive numbers. Now, the camera is a 16 10 display. At this point, I wanted to scale up the tiles. If I want to scale the map up I start by scaling the camera by 100, and then I scale the tiles, and align their position (edge to edge). At this point, scaling the tiles by 100 seems logical, but that didn't work correctly, for some reason. Scaling by 50 almost works, but the resolution is no longer a 16 10 grid like it was before the scaling. What am I doing wrong? I am using Unity.
0
How can I move game objects using keyboard in the Unity scene editor? I know I can click on the "move" button and use my mouse to drag the object around. How can I do the same using my keyboard?
0
Circular draggable UI element in Unity canvas I am trying to implement my own runtime color picker that's easy to use for touch interfaces. I want the hue slider to be a ring, along these lines, except the whole ring texture would rotate when dragged. I have scavenged enough code to get a raw image object rotating when dragged in a UI canvas in the manner I'm looking for private float baseAngle private Vector2 pos public void OnBeginDrag(PointerEventData eventData) pos transform.position pos eventData.pressPosition pos baseAngle Mathf.Atan2(pos.y, pos.x) Mathf.Rad2Deg baseAngle Mathf.Atan2(transform.right.y, transform.right.x) Mathf.Rad2Deg public void OnDrag(PointerEventData eventData) pos transform.position pos eventData.position pos float ang Mathf.Atan2(pos.y, pos.x) Mathf.Rad2Deg baseAngle transform.rotation Quaternion.AngleAxis(ang, Vector3.forward) Since it doesn't use colliders, how can I limit the draggable region to a circle within the square bounds of the texture? Even better, also limit it to a ring rather than a whole circle. Will I have to implement my own check based on some pure math or is there a built in way? thanks!
0
Positional noise changes in Unity Editor vs compiled I have a surface shader that adds a bit of positional noise, using the following code float2 uv main IN.uv MainTex float2( tex2D( PosNoise, IN.uv MainTex).r 0.5, tex2D( PosNoise, IN.uv MainTex).r 0.5 ) float2( Width, Height) MovementOffset o.Albedo tex2D( MainTex, uv main) MovementOffset is a float, the Width and Height are the size of the map in world coordinates. PosNoise is a texture that is the same for both versions. The problem I'm seeing is that the effective noise changes between how the image looks in the Unity Editor vs when it is compiled. The effect is such that I need to multiply the MovementOffset by a factor of 2 3 to have the same effect in the compiled version. Unity Compiled I don't understand what could be causing this, and am having some real difficulties figuring it out. Any suggestions on where to look? Thanks!
0
Texture tearing with UV texture atlas mapping The following code maps the texture from a texture atlas to a UV. The problem is I'm having texture tearing issues. Does anyone know how to overcome this problem and have any suggestions? Here is the code I have, all images are point filtered and no mipmapping is used. for (int i 0 i lt mesh.uv.Length i ) UVs.Add(GetUVTextureFromAtlas(mesh.uv i .x, mesh.uv i .y, voxel, 0)) ... Vector2 GetUVTextureFromAtlas(float x, float y, ushort voxel, Facing side) Rect rect GetVoxelTextureRect(voxel, side) float xout UVLerp(rect.x, rect.x rect.width, x) float yout UVLerp(rect.y, rect.y rect.height, y) return new Vector2(xout, yout) float UVLerp(float from, float to, float t) float difference to from return from (difference t)
0
Dragging a Rigidbody2D without passing through obstacles I have this body of code written for an object that needs to be an obstacle and another object that is draggable. I have colliders on both and a kinematic rigidbody on the draggable object, but the obstacle is still allowing the dragged object to be dragged through it. This is all 2d. I'm not sure what I'm doing wrong. The part that I'm confused on is this when you just add a collider to the obstacle sprite and a collider and rigidbody (all 2d) to the draggable sprite, if I don't add the script above, then the draggable sprite falls due to gravity on top of the obstacle and stop there, it doesn't fall through the obstacle sprite. However when I add the above script which has the OnMouseDrag function, and I move the draggable sprite around because now I can, it falls through the sprite. With no script the obstacle acts like an obstacle. With this script the it does not. using System.Collections.Generic using UnityEngine using UnityEngine.EventSystems public class Block MonoBehaviour public GameObject Four Object1 public GameObject clone Four Object1 private Vector3 screenPoint private Vector3 offset private Rigidbody2D rb2d private Vector3 screenPoint private Vector3 offset private Vector3 cursorPosition public void Start() rb2d GetComponent lt Rigidbody2D gt () GetComponent lt Rigidbody2D gt ().isKinematic true public void OnMouseDown() screenPoint Camera.main.WorldToScreenPoint(Four Object1.transform.position) offset Four Object1.transform.position Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z)) public void OnMouseDrag() Vector3 cursorScreenPoint new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z) cursorPosition Camera.main.ScreenToWorldPoint(cursorScreenPoint) offset transform.position cursorPosition public void FixedUpdate() rb2d.MovePosition(cursorPosition) Debug.Log("Update!")
0
Box Collider center relative to GameObject I'm trying to get the distance from the BoxCollider center of a gameobject to the bottom of that same BoxCollider. Note that the center of the collider is slighty modified. So far, I have float halfHeightCollider (bounds.size.y 2) I tried the following to take care of the slight modification float halfHeightCollider bounds.center.y (bounds.size.y 2) But seems like bounds.center give me the position of the center of the BoxCollider in the world, not relative to the gameobject, like in the inspector That value is the one I want. How can I get it?
0
Unity Check if sprite is within range around player I need to know if a sprite is within range (circle or square doesn't matter) around the player. If the sprite is, let's say, 100 blocks away from the player, I will disable it. This wouldn't be too much of an issue, just compare positions and you're done. However, my game is a tile based game and I want the world to be as big as possible, which will result in millions of sprites. I could also add a overlapcicle2D, but the problem is this these objects can't have a collider, since they could be walkable. So how can I check if the millions of sprites are in range of the player, without lowering performance? Alternatively, I could add occlusion culling. But how do you do this with sprites?
0
Limit a scrollbar's OnValueChanged to full step intervals only So I have done some research on the matter but I can't find anything. I created a UI scrollbar and asigned 10 steps to it.Then I noticed that the values of the scrollbar does not change in reference of the handle's steps but in reference of the pointer's position(like a slider).That seriously slows down the performance since it has a lot more to process "onValueChanged" and it is unnecessary for what I am trying to achieve. The values of the steps should go step 1 0.1(1),step 2 0.2(2) etc.I need to get these values and nothing in between or the step that the handle is currently on. How can I do that ?
0
Implicit conversion error why is this code trying to convert a 'World' to an 'int'? using System.Collections using System.Collections.Generic using UnityEngine public class World Tile , tiles int width int height public World (int width 200, int height 200) this.width width this.height height tiles new Tile width, height for (int x 0 x lt width x ) for (int y 0 y lt height y ) tiles x, y new Tile this, x, y public Tile GetTileAt(int x, int y) if (x gt width x lt 0 y gt height y lt 0) Debug.LogError ("Tile (" x ", " y ") is out of range") return null return tiles x, y anyone see anything wrong with this code because on line 18 of my code i get this error "cannot implicitly convert type 'World' to 'int' and i don't know what is going wrong.
0
Textures in build duplicated, despite they're packed into atlases I have a simple SpriteAtlas quot UIAtlas quot which is located in the Resources folder. It points to a folder quot UIAtlas quot which contains my menu textures. All of my batching is working perfectly, everything is being batched, because of the atlas. When I build an iOS version, in the Editor.log I can see this Build Report Uncompressed usage by category Textures 299.5 mb (30 ) Meshes 0.0kb (0 ) ... Used Assets and files from the Resources folder, sorted by uncompressed size 16.0 mb 1.6 Built in Texture2D sactx 2048x2048 Uncompressed UIAtlas 312aba98 ... 345.3 kb 0.1 Assets Resources UIAtlas medal.png ... more entries like this ... Please notice that this texture (medal.png), along with the other textures belongs to this atlas, which is already included in the build executable. I feel this is wrong. If I pack things, they should be packed into that texture and only that 2048x2048 texture should be in the build, right? What's wrong here?
0
Can I clip a collection of geometry to render only inside a particular worldspace volume? I am making a VR app in Unity. I have a giant map that I want to display on a virtual table. The map is too large to fit on the table, and I cannot change its size. (It is a third party asset, and does not easily have that capability.) How can I tell the camera not to render the parts of the map that fall off of the table? Perhaps something along the lines of Camera.DoNotRender(new Vector3(100, 0, 0)) I have been looking into using some MonoBehaviour messages such as OnPreRender, OnRenderObject, etc. But I do not know which one can help me, if any. Ideally, the pixels behind the non rendered pixels should be rendered, but that is not my priority. The map is made up of 100s of little renderers How can I have my Camera not render specific world space pixels?
0
Unable to rotate a 2D object, wanting to move it like a ball wheel I'm using Unity2D. I have a very basic 2D space with a platform, a ball and 2D physics. Physics is being applied and ball sits on top of the platform. However, it will not spin. Below is the script attached to the ball using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.EventSystems public class Circle MonoBehaviour private Vector3 screenPoint private Vector3 offset private float speed 10f public Rigidbody rb void Start() rb GetComponent lt Rigidbody gt () void FixedUpdate() float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) rb.maxAngularVelocity 999 rb.AddTorque(movement speed) void OnMouseDown() offset gameObject.transform.position Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z)) void OnMouseDrag() Vector3 curScreenPoint new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z) Vector3 curPosition Camera.main.ScreenToWorldPoint(curScreenPoint) offset transform.position curPosition The script is attached to the ball, I know this because I'm able to drag it (see OnMouseDown). I have also tried with other objects such as a rounded corner square, but I just can't get any spin or torque to be applied. Below is a screenshot of the inspector on the element. Circle.cs (the script) is the above pasted script. Any help appreciated.
0
Black screen when building apk Unity Alright, I have a bit of a confession to make I accidentally posted this question in the wrong place Stack Overflow. Whoops. Anyway, here's my problem. Sorry if you've seen this before. Here's the original post. I've been struggling with this issue for a few days now. Windows builds for my game work fine, but when I build it to Android, it loads, shows the "made with Unity" screen, then fades to black. Now, I know the next scene (an animated logo) is running because it is playing the audio in real time. However, nothing in the scene is visible. Then, the UI for the in game loading screen appears. Normally, the game would then load, and it does, but again, the camera thinks there are no sprites in the scene. I can still play the game, and the audio sounds just normal, but I can't see. Then, when I die, the game over UI appears, and I can use it as normal. The shop menu works absolutely fine, but the game itself does not. It's as if Unity decided that all SpriteRenderers in the game just didn't exist, and that the camera background color was now black. There are no scripts or animations causing this directly, as it does work in editor and on a PC build. The game also works fine using Unity remote, but the build has the issue. I also made sure that none of the textures were too large for Android (to the point where not one of them is larger than 256x256, which looks terrible but proves a point). Now, before anyone asks, yes, I have seen the other question on this topic, and no, sadly, it did not help. My camera is set to "solid color", not "don't clear." I tried "skybox" too, just to be safe. I have also tried disabling post processing, hoping that Android was just unable to handle it. It did nothing. I have even tried entirely disabling all of the sprites in the scene, but even then, the background is still black, indicating that the camera is still not playing nice. Also, here is a screenshot showing the quality settings for the Android build.
0
Resolving this kind of situation in my platformer (movement on slope with roof) I'm building a simple 2D character controller based on raycasts. At this moment I'm trying to finish the player ground interaction. For the ground I will be using edge colliders and no tiling information. I have most code working but there's something I don't really know how to fix. Here is an screenshot explaining the situation As you can see, Player (purple rectangle) is on a slope. When player wants to move right the new x and y coords are calculated to set the player feet again on the slope (Blue rectangle). But, after this response has been applied to the player to make it out of the slope, It is pushed through the roof and some part of it is sticking out the edge collider (red box). How do you handle this situation? On the other hand, If there's any way to accomplish this in a simpler fashion I'm all ears ). Cheers.
0
Unity Shader Material Only Activates when Clicked I am currently programmatically settings some shader textures, related to a Mesh Filter. The Mesh Filter is using a standard shader, and I am merely generating and setting the Bump and Height maps, via code. Sphere.materials 0 .mainTexture biome Sphere.GetComponent lt MeshRenderer gt ().materials 0 .SetTexture (" BumpMap", bump) Sphere.GetComponent lt MeshRenderer gt ().materials 0 .SetTexture (" ParallaxMap", heightTexture) This is fine. The issue is that the shader only seems to activate itself once it is clicked in the inspector. Is there some sort of Activate() function I need to call in order to apply the shader effects to the Mesh? Notice in the example (this is running in Play mode), that the shader only activates once I click the expand button on the Shader in the inspector. What is going on here?
0
NPC daily routines and scene loading I'm making a basic survival RPG in Unity 3d. I'm separating my world into different scenes to save memory but I'm not sure how I'm going to program NPC daily routines. For example, if the player arrives in a town scene in the morning, how do I ensure that the NPCs are working in appropriate places with the appropriate equipment? I suppose I could hard code it so NPCs are in certain places at certain times. Therefore, if the player arrives at 9 00am then all the NPCs will move to their 9 00am places. I'm just wondering if there is a better way of doing it than that. I can see myself needing to write a lot of code to cover all the possibilities so it could get really messy. I was hoping there was some way I could have the NPC routines continue seamlessly in the background but this would be taxing on memory if it's even possible. Any ideas pointers on this issue would be appreciated.
0
Realistically drivable car I want my car to be realistically drivable (like in real life...) Unfortunately all I did so far is Rotate the whole vehicle using A and D and AddForce in forward backward direction using W and S (which didn't prevent it from moving sideways and yes, I am using Rigidbody) I'm assuming I'd have to let front wheels rotate independently from the rest of the car, but how do I use them to move the car? And how do I force the car to move only in the direction of the wheels while still making drifting at high speeds possible?
0
Can I save a score as highscore, if it's a float? So I have this infinite runner type of game, subway surfers style. I chose a method where the player doesn't move, and instead the obstacles move towards him. My score is a float and it increases as time passes. However, I'm unable to figure out how can you save this as a highscore. I tried a few methods but most of them were for int so it didn't work out. Here is what I have for the score counting. It's currently missing the save score part completely. public class GameManagerC MonoBehaviour float score 0 public float scoreMulti 5 void Update() if (isPlayerAlive true) score Time.deltaTime scoreMulti scoreText.text score.ToString( quot Score 0 quot ) EDIT Many of you asked how I tried to implement the code I've found so here it is public float score public float highScore void Start() score PlayerPrefs.GetFloat( quot score quot ) highScore PlayerPrefs.GetFloat( quot highScore quot ) if (score gt highScore) highScore score StartGame() Update is called once per frame void Update() if (isPlayerAlive true) score Time.deltaTime scoreMulti scoreText.text score.ToString( quot Score 0 quot )
0
What to do to set gravity in unity What to do to set gravity in unity? I'm working on a game called "OXYGEN", and for the space scene. I want to set the gravity of the Controller to 0.38, or Mar's gravity.
0
UnityEditor related classes can not be referenced. Why? I have two classes. Both of them are placed in the editor interface field folder. using System using UnityEngine namespace editor.interface field public class RequiredInterfaceAttribute PropertyAttribute public readonly Type type public RequiredInterfaceAttribute(Type type) this.type type using UnityEditor using UnityEngine namespace editor.interface field CustomPropertyDrawer(typeof(RequiredInterfaceAttribute)) public class RequireInterfaceDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) if(property.propertyType SerializedPropertyType.ObjectReference) var requiredAttribute this.attribute as RequiredInterfaceAttribute EditorGUI.BeginProperty(position, label, property) property.objectReferenceValue EditorGUI.ObjectField(position, label, property.objectReferenceValue, requiredAttribute.type, true) EditorGUI.EndProperty() else var previousColor GUI.color GUI.color Color.red EditorGUI.LabelField(position, label, new GUIContent( quot Property is not a reference type quot )) GUI.color previousColor I have another class. using editor.interface field using UnityEngine namespace interface user.implementations public interface IInterface public class InterfaceUser MonoBehaviour SerializeField RequiredInterface(typeof(IInterface)) UnityEngine.Object interfaceImplementation The RequiredInterface(typeof(IInterface)) line throws the following error The type or namespace name 'RequiredInterfaceAttribute' could not be found (are you missing a using directive or an assembly reference?) Assembly CSharp csharp(CS0246) I can not understand why does not Unity see the RequiredInterfaceAttribute class and how could I make it see it.
0
Make enemy follow player intelligently I was trying to make a script to make my enemy follow my player intelligently (but not too much) and I want to know if there was a better way to do it (of course there is but I wanted to find a way myself) Here is what I did I wanted my enemy to detect the player when he approach a certain distance from him. I have a varibale to determine what distance the nemy have to back up (when player is too close) and when it has to follow the player (player too far). Now, I didn't wanted the enemy to just forgot there is an intruder when the player goes around a corner and they can't see him. When the enemy sees the player directly (raycast), they rotate toward him and start following him directly by normalizing the difference of their 2 position. Now is the tricky part i'm not sure about. My player has a list that keeps the 1000 last positions of my player and that update every 0.01 second to add the lastest position and remove the oldest. If the enemy can't see the player directly (!raycast) he goes through all the positions in the list by checking for every Vector3 1 is there something between the enemy and this position ? 2 is there something between this position and the player ? Then it add up the distance between the enemy and the point and the distance between the point and the player and checks 3 is the lenght of the path by going at this point shorter than the last shortest path ? if it's smaller, it's assigne to the best point. If it detected a point that matches these conditions, it goes at it and if it doesn't see the player, it continues checking for new points. If no point matches the condition, he just stop following the player (the enemy lost him). All this works with raycasting to check positions, presence of objects between enemy, player and points and path to go.
0
How to move my character by itself but I can still move its direction or where it is going, using Mobile Joystick? So, I am making a 2D airplane game right now and I wanted to know how to move my player automatically but I can still control where it should go or the direction. How do I code this using Mobile joystick? CODE public float moveSpeed Rigidbody2D myBody protected Joystick joystick void Start() myBody GetComponent lt Rigidbody2D gt () joystick FindObjectOfType lt Joystick gt () Update is called once per frame void Update() myBody.velocity new Vector2( joystick.Horizontal moveSpeed, joystick.Vertical moveSpeed )
0
How to retrieve the coordinates of an animated object? On Unity, I created a script in C to animate a cube. I am trying to create a script in C which, once the animated object and in support of a key of the keyboard (for example F) returns to me the coordinates of the object at the moment when I pressed F Can you give me this script? Thank you for your help
0
How to keep player rotated toward a sphere when within a certain radius? In my game the player can fly to multiple spheres, I want to make it so that when the player gets within a certain distance of the sphere, (maybe using a bigger is trigger sphere collider around it?) their feet will stay pointing towards the sphere until they leave the radius, (maybe using a quaternion?) then if they get within the radius of a different sphere, their feet will point towards that too. How can I make this work? I don't know too much about c , so any example code would help a lot too!
0
How people get their game ideas? One thing that always stop me when I want to start making a game is having no idea what to do. How do people get ideas for their game ? I mean realistic ideas for people who are alone with the minimum ressources (no money for assets, blender and unity). I will never stop being impressed by all new concept, mecanics or crazy ideas of game indie developpers come up with, like making game out of random everyday objects. I wish I was able to do that. Do developpers get their inspiration by looking at other games and trying to mix them or change the concept ? Do they look outside trying to come up with what they wish was a game ? Or do they simply walk around and try to imagine a game with whatever they see or reallife situations or concept ?
0
Touch a specific area on the screen in Unity 5 I am building a Roulette game in Unity 5. I want to place bets on a Roulette table when I touch specific areas on the screen with mouse(PC) and touch(mobile). For example when i touch Number 1 on the roulette table a bet should be placed on that number. I tried using box collider iwth trigger but I think thats for only colliders. Screenshot attached
0
UNET spawn dynamically generated object unity Spawning works when all clients are connected, but if a client connects after I spawn all my prefabs there are errors. I spawn the object before changing its Rigidbody's velocity, which seems to cause the problem. I spawn objects, change them, then the other client joins, and the errors come. these are the errors Failed to spawn server object, assetId 953c1c6ecbb84304280d1334ef5dae0b netId 26 I also make changes to variables on other scripts. All objects have network identities, network transforms, and are spawnable prefabs.
0
Unity3d webplayer failed to download data file When testing my game web builds on localhost, I get the error "Failed to download data file". The game data file is correctly placed, and the page loads fine, it just wont download the plugin, or prompt me to do so. I tried the following things Add MIME Types to IIS 7.5 Open IIS Manager Double click "MIME Types" in the IIS section. Click Add on the right side "Actions" menu. File name extension .unity3d MIME type application unity3d click ok Restart the server (right side "Actions" menu) That didn't work for me specifically because it turned out I was using IIS Express, so I did the following If Windows 7, browse to 'C Users Documents IISExpress config ' and open the file ApplicationHost.config. Search for 'staticContent' and add the following before the closing tag However, again, it didn't work..
0
How do I transform from local points to world when using a scroll view? I'm using a scroll view to store my game character icons (basically an RPG). The movement system for the characters is tile based, but in game hazards could be located anywhere. So I need to detect if a certain tile will interset with a hazard if a character moves into it. To do this I can calculate the corners of the tile using the co ordinate system of the scroll view. I thought I could turn these into world co ordinates then query to see if the collider attached to the hazard contains the point (the collider could be rotated so I can't just do the math myself). When I try to convert the co ordinates into world co ordinates though the numbers I get just don't match up. For example, the lower left corner of the tile a character will move into is at ( 1250.0, 938.0). If I convert that to world co ordinates I get ( 28.7, 49.8). The actual position for the hazard I'm testing against has a world position of ( 8.0, 1.5, 93.4) though and the test tile should be right on top of it. I'm using code like this to try to get the world co ordinates Vector2 charPosition5 travellingCharacter.owningGameObject.GetComponent lt RectTransform gt ().transform.TransformPoint(travellingCharacter.GetComponent lt RectTransform gt ().anchorMax) Vector2 charPosition6 travellingCharacter.GetComponent lt RectTransform gt ().transform.TransformPoint(travellingCharacter.owningGameObject.GetComponent lt RectTransform gt ().anchorMin) Can someone tell me what values I should be feeding in or what other function I should be using please?
0
How to create inline glow shader for 2d polygon in CG using Unity Shader Lab? So here is what I am trying to do. Given irregular polygon (on the left) I would like to be able to create a shader that would resemble Photoshop inline glow effect with opaque fill (on the right). Creating similar effect for 3d object I can achieve with Fresnel function. However, I am not able to do it for a flat surface of any given irregular 2d polygon. EDIT I am planning on using Voronoi method to generate polygons and then connecting individual polygons to territory shapes based on which player owns them. Which, then will have border material applied. What I need is effectively border (or territory) shader. That means shader has to work for more irregular shapes, like the one below.
0
A coroutine to rotate one point around another by a given angle without referring to game object I need to rotate a point around another point (in 2D) by a given angle over a given duration, independent of game object (meaning that I've manually created the points and they're not positions from a game objects transform ) as shown in the image below where point B rotates to C by and angle e around A by with radius AB. Using a coroutine would be preferable. UPDATE Based on links provided by MichaelHouse I wrote the following methods to rotate a control point over time by a certain angle but it rather moves to a point (which is not the desired point) immediately to another point, not by the right angle. I'm not sure what I've done wrong. public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Quaternion angle) return angle (point pivot) pivot IEnumerator RotateControlPointWithDuration(Vector3 point, Vector3 pivot, float duration, float angle) float currentTime 0.0f float ourTimeDelta 0 ourTimeDelta Time.deltaTime float angleDelta angle duration how many degress to rotate in one second while (currentTime lt duration) currentTime Time.deltaTime ourTimeDelta Time.deltaTime Vector3 newPos RotatePointAroundPivot(point, pivot, Quaternion.Euler(0, 0, angleDelta ourTimeDelta)) points 0 new Vector2(newPos.x, newPos.y) yield return null IEnumerator runMovement() yield return new WaitForSeconds(2.0f) Vector3 point new Vector3(points 0 .x, points 0 .y, 0) Vector3 pivot new Vector3(points 3 .x, points 3 .y, 0) StartCoroutine(RotateControlPointWithDuration(point, pivot, 2.0f, 45.0f)) UPDATE 2 I've tried another approach using trig functions, but the point moves erratically before finally arriving at a point that seems to be the right point. Please see the code below IEnumerator runMovement() yield return new WaitForSeconds(2.0f) Vector2 pivot points 3 StartCoroutine(RotateControlPointWithDuration(pivot, 2.0f, 90.0f)) IEnumerator RotateControlPointWithDuration(Vector2 pivot, float duration, float angle) float currentTime 0.0f float ourTimeDelta 0 Vector2 startPos points 0 ourTimeDelta Time.deltaTime float angleDelta angle duration how many degress to rotate in one second while (currentTime lt duration) currentTime Time.deltaTime ourTimeDelta Time.deltaTime points 0 new Vector2(Mathf.Cos(angleDelta ourTimeDelta) (startPos.x pivot.x) Mathf.Sin(angleDelta ourTimeDelta) (startPos.y pivot.y) pivot.x, Mathf.Sin(angleDelta ourTimeDelta) (startPos.x pivot.x) Mathf.Cos(angleDelta ourTimeDelta) (startPos.y pivot.y) pivot.y) yield return null
0
How to make balls (water, or fluid) through pipe I'm working on a project and get stuck for days. I want to make balls going through the pipe like this game You can watch this Youtube video for more detail. How can i replicate this game machenis?
0
Night cycle object not going smootly when object instantiated Hello so I'm adding night cycle to my game it's going smoothly for object except the instantiated one as you can see that is a different color on it. so here the script for night cycle public GameObject ca1, ca2, ca3, ca4, ca5, ca6 void Update() if ( GameManager.instance.isStarted) timer Time.deltaTime if (timer gt maxTime) GenerateObstacle() if ( GameManager.instance.score gt 450) if ( GameManager.instance.score 2 0) GenerateBuwungObstacle() if ( GameManager.instance.score gt 3000) if ( GameManager.instance.score 5 0) GeneratedMeteorObs() timer 0 if ( GameManager.instance.score 200 0 amp amp activeFade null amp amp activeFadeObjectClouds null) fadeToBlack !fadeToBlack Color colorCactusObs fadeToBlack ? Color.white Color.gray activeFadeObjectCactus StartCoroutine(ObjectCactusFadeTo(colorCactusObs)) for generating the cactus public void GenerateObstacle() choosedObstacle Random.Range(0, Obstacles.Length) GameObject obstacle Instantiate(Obstacles choosedObstacle ) IEnumerator ObjectCactusFadeTo(Color destination) Color start1 ca1.GetComponent lt SpriteRenderer gt ().color Color start2 ca1.GetComponent lt SpriteRenderer gt ().color Color start3 ca3.GetComponent lt SpriteRenderer gt ().color Color start4 ca4.GetComponent lt SpriteRenderer gt ().color Color start5 ca5.GetComponent lt SpriteRenderer gt ().color Color start6 ca6.GetComponent lt SpriteRenderer gt ().color for (float t 0 t lt 1f t (Time.deltaTime fadeSpeed) 2) ca1.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start1, destination, t) ca2.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start2, destination, t) ca3.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start3, destination, t) ca4.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start4, destination, t) ca5.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start5, destination, t) ca6.GetComponent lt SpriteRenderer gt ().color Color.Lerp(start6, destination, t) yield return null ca1.GetComponent lt SpriteRenderer gt ().color destination ca2.GetComponent lt SpriteRenderer gt ().color destination ca3.GetComponent lt SpriteRenderer gt ().color destination ca4.GetComponent lt SpriteRenderer gt ().color destination ca5.GetComponent lt SpriteRenderer gt ().color destination ca6.GetComponent lt SpriteRenderer gt ().color destination activeFadeObjectCactus null I already try with for loop in the object cactus fade but still not smooth
0
Allow code after a bugged line to continue without use of try and catch My problem is with C in unity, but I think the problem can be applied to all coding languages. For example I have a start function event that may initiate many things. Some lines of code may issue a bug but I want to allow new lines of code run after that without having to encapsulate every line of code with try and catch. Is there any common solution for this that I'm missing?
0
Day and Night mode according to user's real local time How do I make it so the texture of my plane is a black sky when it's night according to player's local time (say from 10 PM to 5 AM it's going to be black, and from 6 AM to 9 AM it's going to be a blue sky)? Blue sky texture name is "bluesky" Black sky texture name is "blacksky" Thanks.
0
Having trouble setting a game object as a child of another. What is wrong here? So I'm trying to raycast on mouse click if it hits any thing make that object a child of the sender (in this case the parent). Below is my code... public class PhysGun MonoBehaviour private GameObject Player void Start () Player GameObject.Find("Player") Update is called once per frame void Update () Vector3 fwd transform.TransformDirection(Vector3.forward) if (Input.GetMouseButton(0) amp amp Physics.Raycast(transform.position, fwd, 10)) this.transform.parent Player.transform transform.SetParent(Player.transform) Debug.Log("There is something in front of the object!") The script is attached to a child of the player and I will eventually attatch it to a motion control (Vive). What am I doing wrong exactly? I've tried multiple ways to do this and none of them work (or present any errors). Also to clarify the issue it's not parenting the game object hit by the ray cast to the Player like I want it to.
0
How to "undraw" a SetPosition on LineRenderer? I'm animating the SetPosition on a line renderer to show a laser site quickly quot spin up quot so the user sees the laser head outward. I'd like to do the reverse and when a user switches off the laser sight and it also quickly retracts. I have the spin up working good, but I can't figure out how to quot undraw quot the line when a user toggles the sight off. Once its quot undrawn quot a user can just spin it up again when they turn it back on. Here is the code (ignore the weapons checks) using System.Collections using System.Collections.Generic using UnityEngine public class WeaponAimAlignment MonoBehaviour weapon assignments SerializeField private Transform rocketBarrel laser sight assignments SerializeField private float aimOnSpeed SerializeField private Transform aimLaser SerializeField private LineRenderer lineRend private bool aimOn false private float counter private float dist void start() lineRend.enabled false void FixedUpdate() if (Input.GetKeyDown(KeyCode.B) amp amp aimOn false) aimOn true lineRend.enabled true lineRend.SetPosition(0, aimLaser.transform.position) else if (Input.GetKeyDown(KeyCode.B) amp amp aimOn true) lineRend.enabled false aimOn false Ray rayOrigin Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hitInfo if (Physics.Raycast(rayOrigin, out hitInfo)) if (hitInfo.collider ! null) Vector3 direction hitInfo.point rocketBarrel.position machineGunBarrel.rotation Quaternion.LookRotation(direction) grenadeBarrel.rotation Quaternion.LookRotation(direction) rocketBarrel.rotation Quaternion.LookRotation(direction) if (aimOn true) dist Vector3.Distance(aimLaser.transform.position, hitInfo.point) if (counter lt dist) counter .1f aimOnSpeed float x Mathf.Lerp(0, dist, counter) Vector3 pointA aimLaser.transform.position Vector3 pointB hitInfo.point Vector3 pointAlongLine x Vector3.Normalize(pointB pointA) pointA lineRend.SetPosition(1, pointAlongLine)
0
Making read from and write to databases I want to make a few simple databases for a sports game using Unity2D(C ). One is a read only google sheet where it takes the players from the pool and adds them into the game at the start. Another one is a read and write database where all 30 team's players will be saved as well as current stats( a lot of numbers), I don't know if i should make this online or local saves. I want to keep the cost at a minimal. Generally new to making databases, can someone point me in the right direction?
0
Double vision with Google Cardboard in Unity I am working on a VR app. I have a terrain and some cube placed in the terrain.Even I have added the Reticle to point at the cube and display some message when the user gaze at the cube. I have set the distortion to "None". The problem I am facing here is,when I run the app the cubes and the pointer(reticle) is seeing as double in the scene.What will be the reason for it.Can anybody help me out please.
0
Spatial Jitter problem in large unity project I have a very large environment where i am getting very weird view of objects as picture given below As you can see there are black lines spot, maybe the vertex lit problem. Currently I am using Standard specular shader. Remember this problem is only occuring at the end of the project (away from origin like position 17000, 0, 144) As a workaround i tried to change my shader to Unlit and i found this shader Shader "Unlit UnlitAlphaWithFade" Properties Color ("Color Tint", Color) (1,1,1,1) MainTex ("Base (RGB) Alpha (A)", 2D) "white" Category Lighting Off ZWrite Off ZWrite On uncomment if you have problems like the sprite disappear in some rotations. Cull back Blend SrcAlpha OneMinusSrcAlpha AlphaTest Greater 0.001 uncomment if you have problems like the sprites or 3d text have white quads instead of alpha pixels. Tags Queue Transparent SubShader Pass SetTexture MainTex ConstantColor Color Combine Texture constant This shader has almost solve the problem but i have to tweak and set colour of each object as be default it is not according to my expectation.
0
Unity Physics collision metrix doesn't work on ParticleCollisions I have this Physics collision metrix(1). I have Player layer on the ship and PlayerShells on Particles whitch's my shooting. The problem When I shoot, OnParticleCollision on my shells collides with player, but as you can see on the picture it shouldn't happen. Proofing my theory, I testet it (2) and (3) screenshoots My quot collision quot code private void OnParticleCollision(GameObject other) SetDamage(other.GetComponent lt ISetDamage gt ()) Creating hit effect mainParticles.GetCollisionEvents(other, collEvent) Vector3 pos collEvent 0 .intersection hit posotion Quaternion newRot Quaternion.Euler(transform.rotation.x, transform.rotation.y, transform.rotation.z) Tryed to rotate effect like opposite from bullet, but it doesn't work for now switch (other.GetComponent lt Stats gt ().GetMatter) case Matter.Steel Instantiate( hitSteel, pos, newRot) break case Matter.Wood Instantiate( hitWood, pos, newRot) break case Matter.Flesh Instantiate( hitFlesh, pos, newRot) break case Matter.Dirt Instantiate( hitDirt, pos, newRot) break case Matter.Stone Instantiate( hitStone, pos, newRot) break What am I doing wrong?? (
0
Sometimes can't use the rendered mesh as a collider in Unity? Most of the times I can use the Mesh Filter's mesh as collider in Mesh Collider But sometimes there is just nothing. No collider. Why? I used this free asset https assetstore.unity.com packages 3d environments fantasy green forest 22762
0
Unity Running code on the "Create Other" menu? Right now I am trying to create a TextMesh GameObject from code. The graphics primitives are accessible through PrimitiveTypes, I'm thinking there must be something similar, and if not, I could at least run whatever static function is bound to the menu if only I knew the name. The more general question is "how one get at all the other items on the "Create Other" without using the menu itself?"
0
How can I change the root namespace for scripts in Unity? How can I change the root namespace for scripts in Unity? I went to Edit Project Settings... Editor Root namespace and put there the gameplay value. I checked that the Assembly CSharp.csproj has the lt RootNamespace gt gameplay lt RootNamespace gt Now I go to VS Code editor, create a class and the class still uses a wrong namespace. What may I be missing here?
0
How to change AddForce code to MovePosition or SetVelocity? Vector2 vec new Vector2(horizontal, vertical) vec Vector2.ClampMagnitude(vec, 1f) Vector3 camF cam.transform.forward Vector3 camR cam.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized targetPosition (camF vec.y camR vec.x) MoveSpeed Vector2 targetVelocity (targetPosition transform.position) Time.deltaTime rb.AddForce(targetPosition rb.velocity, ForceMode.VelocityChange) My problem is my character doesn't affects by the gravity when i changed my code from transform.position to rb.AddForce. I searched online and even asked here how to calculate gravity and add it to my character, nobody knew, so i think if i can change this code to rb.MovePosition or rb.SetVelocity maybe it does affects by the gravity?
0
How do I use this Perlin Noise texture to change the mesh? Using the Unity docs page on Perlin noise, I made this script Width and height of the texture in pixels. public int pixWidth public int pixHeight The origin of the sampled area in the plane. public float xOrg public float yOrg The number of cycles of the basic noise pattern that are repeated over the width and height of the texture. public float scale 1.0F private Texture2D noiseTex private Color pix private Renderer rend void Start() rend GetComponent lt Renderer gt () scale Random.Range(15, 20) xOrg Random.Range(0, 20) yOrg Random.Range(0, 20) Set up the texture and a Color array to hold pixels during processing. noiseTex new Texture2D(pixWidth, pixHeight) pix new Color noiseTex.width noiseTex.height rend.material.mainTexture noiseTex void CalcNoise() For each pixel in the texture... float y 0.0F while (y lt noiseTex.height) float x 0.0F while (x lt noiseTex.width) float xCoord xOrg x noiseTex.width scale float yCoord yOrg y noiseTex.height scale float sample Mathf.PerlinNoise(xCoord, yCoord) pix (int)y noiseTex.width (int)x new Color(sample, sample, sample) x y Copy the pixel data to the texture and load it into the GPU. noiseTex.SetPixels(pix) noiseTex.Apply() void Update() CalcNoise() The only difference between this code and the Unity docs example is that I added some randomness to the size and origin points of the texture. I attached the script to a plane, and now when I run the game, the plane has a random noise texture on it. Now I want the texture to give height to the mesh, so it will look like a terrain. How do I do this?
0
How to make rigid body move smoothly on uneven platform? Right now I'm using Rigidbody2d for the game character along with polygon collider 2D(2d platform game). I'm beginner hope I'm using correct components. And transform to move character from left to right. Character.transform.Translate(Vector2.right speed Time.deltaTime) And upward(jump). Character.transform.Translate(Vector2.up speed Time.deltaTime) When the game character moves on slopes there's lot of friction and bounciness and rotation and its worse when jumping from slopes.
0
Smoothly switch between 2 pairs of oscillating colors I have a simple script that changes the emission color based on a bool. The first color is its idle color, which transitions between orange and light purple using a lerp weighted with a sine wave. The second color is its quot isinDanger quot state, and this lerps between orange and red. Is there any way to make the transition between both of these color variants smooth? When the bool is set to true the colors switch instantly with no transition. I've tried numerous things to try to get them to be smooth but ultimately it just breaks the lerping. using System.Collections using System.Collections.Generic using UnityEngine public class GemGlowOrange MonoBehaviour public Material Mat Color Red Color lightpurple Color orange public bool isInDanger false Color CurrentColor float startTime public float speed 1.0f void Start() startTime Time.time time since game started orange new Color(1.320755f, 0.5346785f,0.2928088f,1f) making my colours RGBA Red new Color(0.858f, 0f,0f,1f) lightpurple new Color(1.320755f,0.2973427f,0.8263685f,1f) var Mat GetComponent lt Renderer gt ().sharedMaterial making a reference to the material so we can enable the emission keyword if you do not want this to affect every object using this material then use quot Getcomponent lt Renderer gt ().material quot the same goes with setting the color as you can see further down. Mat.EnableKeyword( quot EMISSION quot ) this is making sure this shader has the emission keyword enabled. void Update() float frac (Mathf.Sin(Time.time startTime) speed) CurrentColor Mat.GetColor( quot EmissiveColor quot ) if (!isInDanger) Mat.SetColor( quot EmissiveColor quot , Color.Lerp(lightpurple, orange, frac)) getting the same material over and over again each frame and updating its emission colour else if (isInDanger) Mat.SetColor( quot EmissiveColor quot , Color.Lerp(Red, orange, frac)) if it is in danger then it will alternate between red and orange.
0
How can I prevent movement from analog joystick "bounce"? I'm working on a top down game where the player can move up down left right. The sprite changes to the corresponding direction, and I have an internal value that tracks the direction the player is facing. The actual movement is handled just by doing rigidbody2D.MovePosition(player.position movement speed Time.deltaTime) and it's working fine. Direction is determined by looking at the absolute values of all 4 axis values and seeing which one is greatest. The problem I'm having is when using an analog joystick on a controller. So, if you suddenly let go of the stick, it has a little "bounce" where it goes past the center, and into the opposite direction. I uploaded a slow motion video of the joystick being released, to show this "bounce." See GIF here I added some logging to the input, and here are some numbers The joystick bounce always ends up being somewhere between lt 0.1 to up to 0.5, for maybe 1 frame in time. What can I do to mitigate the effects of this bounce? It's causing my player to suddenly look in the opposite direction if they suddenly stop moving. I've had these ideas for solutions, but I'd love some advice Increase deadzone to be over 0.5 This seems like an easy fix, but that feels like it's too big of a deadzone. Ignore input if the difference between last frame and current frame is greater than a specific value (maybe 0.5?) Average out input over the last few frames and then move? Seems like it could be buggy though (and feel laggy)
0
Unity Smoothing between two floats which are continuously changing I'm looking for some help with smoothing between an original float and a target float, where the original float is consistently changing (potentially interfering with interpolation techniques and or Mathf.SmoothDamp) I tried Mathf.SmoothDamp with the below (float rocketBoostPower is a global variable) float yVelocity 0.0F float tempForce rocketBoostPower Input.GetAxis("Mouse Y") shiftSpeed 5f rocketBoostPower Mathf.SmoothDamp(rocketBoostPower , tempForce, ref yVelocity, 0.5f) This doesn't change the force at all however, it just stays locked in place. I'm currently using the below to change my power, however I want to smoothly change the power instead of just incrementing sharply on each Update frame rocketBoostPower Input.GetAxis("Mouse Y") shiftSpeed 5f Please can someone help? I need the assumption that every update will receive a new rocketBoostPower value, whilst still smoothing its previous value.
0
Update the UI Rotation According to camera rotation I have a camera which is showing the userInterface (canvas) object into the front of my camera. I am only updating my userinterface position if the camera raycast is not hitting my userInterface object collider. something like this public class UIPlacerAtCamFront MonoBehaviour public GameObject userInterface public float placementDistance Vector3 uiPlacementPosition RaycastHit objectHit void Update () Vector3 fwd this.transform.TransformDirection(Vector3.forward) Debug.DrawRay(this.transform.position, fwd 50, Color.green) if (Physics.Raycast(this.transform.position, fwd, out objectHit, 50)) raycast hitting the userInterface collider, so do nothing, userinterface is infornt of the camrea already else raycast is not hitting userInterfae collider, so update UserInterface position accoding to the camera uiPlacementPosition this.transform.position this.transform.forward placementDistance userInterface.transform.position uiPlacementPosition Continuously update userInterface rotation according to camera userInterface.transform.rotation this.transform.rotation The above script has attached with my camera, it displaying the object correctly but as i start to rotate my camera my UI object rotation looks very strange as below image suggested As i rotate, this problem occurs I know that the problem is in rotation, so I tired to change my this rotation code userInterface.transform.rotation this.transform.rotation to this userInterface.transform.localEulerAngles new Vector3 (this.transform.localEulerAngles.x, 0, this.transform.localEulerAngles.z) but it bring another strange rotation for me, like given below I want that my userinteface object face my camera correclty, even my camera watching the start or end of my userinteface object. How can i rotate my UI according to camera rotation correctly?
0
How to set default pose of model from Blender? (Exported as FBX) I have a model that has lots of animation clips(actions). Before export as FBX, I set the pose to named "default" pose and exported as FBX like this. But in Unity, it's changed to first animation clip in animation list in Blender! I try to fix it, but there is nothing I can do. I can't change the order of animations in Blender and Unity either. This wasn't first time, I had same issues before but I just ignored because it's fine in game play, but I really want to fix it this time. What I want is set "default" pose in edit mode in Unity(not play mode). How do I set "default" pose as default, not first animation clip in the list? Using Blender 2.78, and Unity 2017.3.0f3.
0
Idle Walk animation problem and double button input axes I have 2 problems with unity3d. First, I created an animator and attached it to player. In animator I put 2 condition, Speed and Running (first is float, second is boolean). Default Animation is Idle. Then player press W, I want animation to fade from idle to walk and when he stop press the button, I want the animation to fade from walk to idle. Here is my problem. When I press W, he make walk animation, but after it he play half of idle animation and after it he enter again in walk animation. How can I loop the walk animation until he release W? And if he release, even if the animation isn't totally played, I need the animator to make transition to idle. How can I make this "transition"? Then I release W, he just go from walk to idle animation without any transition (and it is a kind of wear). Second, How can I put 2 input buttons on axes? I mean If he press W, there should go vertical axes. When he press W Left Shift, there should go running axes. How can I attach 2 buttons to 1 axes? I am new in unity and I want to figure out how to work with this things.
0
Creating 3D gravity in zero G tied to mass in unity with c As a total beginner, I've been working on a patch job script for a gravity mechanic in an open space sim, I want to derive all my objects from this "Block ALPHA" object and its' set of variable attributes, so it's important that I get it right before moving on. The idea is simple enough, call an array of all interactive objects' coordinates and apply a basic equation to simulate gravitational pull. After some tinkering I have a piece of code that ticks all the boxes AFAIK, but I can't for the life of me figure out the syntax error I've made... I've been up all night massaging the script to fit my needs, but in the best cases it only raises one error "expected ' '" Maybe I'm just tired, maybe I broke the code, but trying to place parentheses only seems to bring more errors Here's the code as it is so far complete with the compiler error and suggested fix (in red), which does no good whatsoever using UnityEngine using System.Collections public class DynamicWeightAnalysis MonoBehaviour Strength of attraction from your game object, ideally this will be derived from a calculation involving the objects volume and density eventually public float RelativeWeight Here, we name our target objects GameObject blockALPHA Initialise code void Start () here, we define our target objects further by searching for the predefined tag blockALPHA GameObject.FindGameObjectsWithTag("Block ALPHA") Use FixedUpdate because we are controlling the orbit with physics void FixedUpdate () " EXPECTED" this is where we define the graverage coordinates Vector3 graverage (Vector3 blockALPHA) if (blockALPHA.Length 0) return Vector3.zero float x 0f float y 0f float z 0f foreach (Vector3 pos in blockALPHA) x pos.x y pos.y z pos.z return new Vector3(x blockALPHA.Length, y blockALPHA.Length, z blockALPHA.Length) Vector3 offset here we get the offset between the object and the average position of all objects offset graverage transform.position This is the variable for square magnitude calc float magsqr Offset Squared magsqr graverage.sqrMagnitude Check distance is more than 1 to prevent division by 0 (because my blocks are all 1x1x1, any closer and they'd be intersecting) if (magsqr gt 1f) Create the gravity make it realistic through division by the "magsqr" variable GetComponent lt Rigidbody gt ().AddForce((RelativeWeight graverage.normalized magsqr) GetComponent lt Rigidbody gt ().mass) I don't doubt that I've overlooked something stupid, but it's my first stab at proper coding, so, no shame in asking Thanks D
0
TBS Shooter targeting AI I have some experience in developing all sorts of (small) games using Unity3D, I have a few personal game projects and I also work for a small game studio. The only subject in game development that I've avoided at all costs was AI, up until now. My other projects required just basic NPC algorithms, so i can't call that AI. On to my problem I have 2 or more player opponents that have to shoot at each other, taking turns (think of a Worms game). They fire using a ballistic arc, adjusting firing power and gun elevation. The problem is making the CPU player to behave like a human player would, without using firing at random. I have, from other games, and algorithm that computes the angle and projectile velocity required to hit dead on the target, but that would kill the opponent in the first few seconds. So i need a smarter, human like approach fire a trial shot, smartly adjust to improve aim. Also account for wind direction and speed that affect the projectile. After some AI research, I was thinking of using genetic algorithms, but i do not need a perfect solution to my problem (to hit the target in the first round) but rather a constant improving one. Also if the algorithm could be tuned for easy medium hard difficulty would be great. I do not necessarily need a complete solution, but a direction to dig to.
0
Increase speed with each enemy destroyed? I need some help with coding this idea "For each Target destroyed, increase the Gunner's speed by (speed variable)". The idea is that the Gunner is automatically moving, and I want it to become more frantic with each target hit. Here's the relevant code I have so far using UnityEngine using System.Collections using System.Collections.Generic void Update () Gunner Move () gives me the error "Assets Scripts MovementPathScript.cs(60,83) error CS0200 Property or indexer System.Array.Length' cannot be assigned to (it is read only)" void Gunner Move() if (GameObject.FindGameObjectsWithTag ("BulletProgressionObject").Length 1) Gunner SpeedIncrease () void Gunner SpeedIncrease() behavior that I'm not sure how to make for the bullets colliding with target's parent object void OnTriggerEnter(Collider other) if (other.gameObject.CompareTag ("BulletProgressionObject")) Destroy (other.gameObject) I think it's a foreach loop, but the issue I'm having is properly implementing it. Any suggestions or referrals would be greatly appreciated.