Quantcast
Channel: Questions in topic: "independent"

Framerate Independent Firing Rate (delta time?)

$
0
0
I am attempting to make a consistent firing rate. I have done a lot of research on figuring out consistent rates that are independent of framerate and most of the articles about it use deltaTime. However, most timers do not. I have a timer that works as long as the interval is not less that "0.2". Any number less than that has inconsistent results depending on the framerate. Specifically, when I play the project in the maximized window, versus a small window. Here is the code I am using. I know this has been beaten to death, so forgive me, please. I assume I must use some form of deltaTime multiplier somewhere. using UnityEngine; using System.Collections; public class Shooter : MonoBehaviour { // public GameObject bullet; // public Transform cam; public float interval; public float lastFire = -9999; public int shotsFired; void Update () { if(Time.time = lastFire + interval; } } I have toggled out the bullet references so that it can be easily tested. The reason I know it is inconsistent is because I implemented a test that lasts for a specific amount of time. I realize my test may be faulty and could be the actual problem. If so, please let me know. I really appreciate any and all help. Thanks, and God bless! Howey

Framerate independent physics (FixedTimestep, FixedDeltaTime)

$
0
0
How do I achieve 'correct' framerate-independent physics in Unity? As I understand it; physics logic should always be performed in the FixedUpdate() function (Application of forces, etc), but does this mean I should *scale* my forces by Time.fixedDeltaTime - similarly to the way we should scale by the [variable] deltaTime in the Update() function for game logic - or is this taken care of by the physics engine its-self? My reasoning for this is; if the number of required physics steps or the fixed update duration changes, then the forces applied will no longer be correct. However if the physics engine already takes this into account, then there is no reason to do the multiplication myself. I've read a few articles on the topic of physics in Unity, however there seems to be a lot of confusion and misinformation out there regarding how to properly achieve framerate-independence - perhaps this thread can clear some of that up? :)

Spinning a mesh independent of its forward movement?

$
0
0
This question is really about how do I create a prefab that allows for this. What I want is a billboard that will always face the camera while it is moving in space. I believe I do this with a gameobject that contains no mesh that has a child gameobject with the billboard mesh. A script I would add to child billboard gameobject would control its orientation to the camera. The parent gameobject would have a script attached that controls its movement. I am having trouble creating the basic prefab with the empty parent and the child with only the billboard in the Unity UI. When I try to drop in the child gameobject it merges rather creating the child. Can someone help me out with the steps to create this kind of a prefab?

Movement FPS Independent, how to?

$
0
0
Hello people, I've already asked this here a few times, but no one awsered, so let's try again. I've made a Character controller myself, and I tought i did things right when it comes to FPS independency, but when I tessted in other machines, it does'nt seem so. My code is pretty big. but the main lines are these: if(grounded == false) //Gravity for falling {finalmovement.y -= gravity * Time.deltaTime;} if(Input.GetButtonDown("Jump")) //Jumping {finalmovement.y = 7;} myTransform.position += (myTransform.rotation * finalmovement)*Time.deltaTime; //Overall movement I tought it is ok, if my character is not on the ground, the gravity is applied with Time.deltaTime, and if I jump, the Y of finalmovement goes to 7 and then starts to go down with the gravity to make my character move downward. But the problem is, when i have low fps, my character doesn't jump as high. why? It seems that the gravity is being applied more strongly ( I guess its because the Time between frames is bigger ), in other words, my movement is not FPS independent, even if I use Time.deltaTime. How can I solve this? Is my guess about the problem right? Thanks in advance.

List Problem :(

$
0
0
> using UnityEngine; > using System.Collections;> [System.Serializable] > public class pl> { public string name; public int> hp,maxhp; public int attack; }>> ________________________ > using UnityEngine; > using System.Collections;> using System.Collections.Generic;> public class player : MonoBehaviour {> public pl[] pl; public List pll;>> void Update(){>> } void OnGUI(){> if(GUILayout.Button("TIKLA")){> pll.Add(pl[0]);>> } } }> **> Sorry for very bad english :( When I add list same item.> When I change the name of the last item> Change is happening as I have all of the same item> I want to be independent of the items **

Jump not affected by changing velosity.y

$
0
0
Hello :) I've just done double jump in my game and in a some way it's affected by changing velosity.y by game object. It means the power of second jump depends on a time(?) and changing velosity.y(?) between double clicking "Space". I want to make it independent and the jump's power is need to be the same all the time. Where am I wrong? Thanks in advance! Tomas void Update () { if(Input.GetKeyDown(KeyCode.Space)) { if(grounded) { rigidbody2D.AddForce(new Vector2(0f, jumpingForce * moving)); grounded = false; jumpCounter = 1; } else if(!grounded && jumpCounter == 1) { jumpCounter++; rigidbody2D.AddForce(new Vector2(0f, jumpingForce * moving)); //Debug.LogError("And second jump"); } } }

Get real world's time which independent with device

$
0
0
I'm creating a game on Iphone/Android. In my game, user plants a tree then have to wait for that tree grow up. Each time user opens game, I check the time when user planted the tree and the current time, then decide the tree is grew up or not. The problem is, if user plants the tree, then change device's time, he/she can cheat to make the tree grow faster. How to avoid this? Is there a way to get the "real world current time" which user can not change?

Android Resolutions Independent

$
0
0
Hi! I started with unity some weeks ago. Im trying to make a simple side-shooter 2d game, i had set the camera with a script to 1280x720 so i can test it with my phone on landscape orientation. There are a lot of resolutions for android, how should i work around this for not getting sprites scaled or off screen? Thanks :)

Keep Parent scaling independent to Child's (C#)

$
0
0
With this script it makes the child objects rotate based on the parents position, I want to implement something that will allow me to change the parents scale but not have that affect the child scale. Any ideas how I could implement that into this script ? using UnityEngine; using System.Collections; public class Tutorial_3_Q1 : MonoBehaviour { public Transform _parent; private float eulerAngles; void start() { } void Update() { transform.RotateAround(_parent.position, _parent.rotation.eulerAngles, 50 * Time.deltaTime); print(transform.eulerAngles.x); print(transform.eulerAngles.y); print(transform.eulerAngles.z); } void OnGUI() { GUI.Label(new Rect (10, 10, 200, 20),"Euler Angle x ="+ transform.eulerAngles.x); GUI.Label(new Rect(10, 30, 200, 40), "Euler Angle y ="+ transform.eulerAngles.y); GUI.Label(new Rect(10, 50, 200, 60), "Euler Angle z ="+ transform.eulerAngles.z); } }

Is Endianness Unity platform independent

$
0
0
Does all of builds will be little endian format regardless of the final build platform? I'd rather not use BitConverter class with: if (BitConverter.IsLittleEndian) Array.Reverse(bytes); If it will be little endian anyway, creating, checking and reversing after is a waste of resources. I already build my custom byte converter class which threats everything as little endian. But the question about multiplatform stays.

Why is this small part of code not frame independent ?

$
0
0
I have this code and been messing around with time.deltatime for quite a long time now, not sure why it isnt frame independant, please help. void Update() { Vector3 velocity = bulletSpeed * transform.forward + gravity; //Debug.Log (transform.position); //Debug.Log (velocity); gravity += new Vector3 (0, -9.8f, 0); newPos = velocity * Time.deltaTime + transform.position; direction = newPos - oldPos; float dist = direction.magnitude; if(Physics.Raycast(oldPos,direction,out hit,dist,layersToCheck)) { //Debug.Log("hit Object name: " + hit.collider.gameObject.name); Destroy(gameObject); } else { oldPos = transform.position; transform.position = newPos; }

How do I use Time.unscaledTime?

$
0
0
I know what it does but I'm not sure how to use it in my code All the answers I've found just point to how it's a good way to move or animate when Time.timescale == 0 I need some simple example code I have 2 moving Cubes, I want one to keep moving when game is paused

Can't achieve framerate independent movement

$
0
0
Hello, I can't get my movement to be framerate independent. Here's the code I using inside Update: void Update () { if (Input.GetKeyDown(KeyCode.Escape)) Application.Quit(); if (Input.anyKey) { velx ++; } else { velx *= drag; } velx = Mathf.Clamp(velx, -max_velx, max_velx); Vector3 delta = new Vector3(velx * Time.deltaTime, 0, 0); transform.Translate(delta); } When I change the quality of the graphics in the game.. the player speed changes considirably. I can't see where the problem might come from, since I'm scaling the velocity by the time spent on the frame.

Framerate independent Movement

$
0
0
In my project I have Unity's [CharacterController](http://docs.unity3d.com/Manual/class-CharacterController.html). This is the code that made it move. It's working great when using fixed timestep. vel.x *= friction; vel.z *= friction; vel.x += input.x; vel.z += input.z; cc.Move (vel); I want my game to support unlocked framerate so the character's movement should be updated on per-frame basis. The problem is that the acceleration is really inconsistent. Eventually all framerates hit the maximum speed (they get closer to it every frame), but 1000 FPS reaches it almost instantly, while 15 FPS takes a long time to accelerate. After pondering about it, it makes sense, but I wasn't able to make the acceleration consistent... What is the mathematical solution to this? Any tips are appreciated!

Resolution independence

$
0
0
Hi, I have drag mechanic in my game and I want to have same experience in all devices. I've done this before in another game engine and now that Unity gives us Dpi with Screen.DPI, it should be much easier to achieve, but I can't figure it out for the love of the god. My theory is you have to divide the delta movement of touch with Screen.Dpi to normalize the movement and make it same across devices with different screen sizes and dpi's: (touch0.deltaPosition.x / dpi) * SENSITIVITY * Time.deltaTime; But this doesn't work. Would someone please tell me why? I've done extensive search on this but surprisingly nothing much can be found. Thanks in advance and regards.

Yet another Time.deltaTime question

$
0
0
Jumping and framerate independence. Tried solutions, didn't like. Here is simple example that demonstrates the point - empty scene, attached this to gameobject: using UnityEngine; using System.Collections; public class jumpTest : MonoBehaviour { private float velocityY = 0; private int counter = 0; private float jumpHeight = 0.1f; private Vector3 gravity = new Vector3(0,-.1f,0); // Update is called once per frame void Update () { // gravity framerate independent float gravityY = gravity.y * Time.deltaTime; if (counter == 0) { // Jump is impulse, wont mult jumpHeight // @see http://answers.unity3d.com/questions/1156824/forcemode2dimpulse-do-we-need-timedeltatime.html // velocity framerate independent velocityY += (jumpHeight + gravityY); } else { velocityY += gravityY; } if (velocityY

How Do I get Units to Move to Different Locations?

$
0
0
I keep coming back to this because this is still an issue to me. I switched my focus to other Unity and C# studies but now I'm back. I've seen some videos. Still stuck. Situation: I have a small Terrain and two spheres. I want to give orders to each sphere separately to move to different locations...at the same time though. I want to do it in a "classic" RTS fashion (Ideally, anyway) by left mouse click on unit and then right mouse click on destination. I'm thinking I need a private bool isSelected switch for the left mouse click and then some sort of raycast to mark the destination. But I can't quite figure out exactly how to write this in code. I know how to use raycasting...I can make ALL the units go to a single right-click location, that's easy...I just can't make two units go to separate locations at the same time. I've done all this with physics, without physics, with NavMesh and without NavMesh...all of that. Bummer. I've been spending a lot of time on this but I feel like I'm missing something really basic that's keeping me from accomplishing my task.

How to make multiple objects with the same script work independently?

$
0
0
I created a script for sinusoidal motion. The movement works perfectly, but the various objects with this script do not move independently. What could I do to solve this problem? Here is the script: using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy4 : Nave { public float horizontalSpeed; public int yFactor; private float count = 3; private Vector3 s; private bool setPos = false; private float x; private float y; // Use this for initialization void Start () { x = 0; y = 0; s = transform.position; side = Side.defside.ENEMY; } // Update is called once per frame void Update () { y += yFactor * Time.deltaTime; x = Mathf.Sin (Time.time) * horizontalSpeed; transform.position = s + new Vector3 (x,y, 0); } }

Como posso mover GameObjects de mesmo script de forma independente?

$
0
0
Criei um script o qual faz um GameObject se mover de forma senoidal. O movimento ocorre perfeitamente, mas quando mais de um GameObject contendo este script está em cena todos se movem como um espelho um do outro e não de forma relativa, deixando o jogo muito artificial. Tentei usar posicionamento local e mesmo assim não consegui resolver o problema. Eis o código: using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy4 : Nave { public float horizontalSpeed; public int yFactor; private float count = 3; private Vector3 s; private bool setPos = false; private float x; private float y; // Use this for initialization void Start () { x = 0; y = 0; s = transform.position; side = Side.defside.ENEMY; } // Update is called once per frame void Update () { y += yFactor * Time.deltaTime; x = Mathf.Sin (Time.time) * horizontalSpeed; transform.position = s + new Vector3 (x,y, 0); } }

how to make enemy clone work independently?

$
0
0
so I am making a shooting game where the game spawns 5 enemies from a prefab. the problem is that when the enemy clone gets instantiated it works properly, but when the enemy clone detects the player, all of the enemy clones start shooting at the player. I want the enemy clone that detected the player to be the only one that will shoot at the player, and not all of the enemy clones. here is the code for my enemy object: using UnityEngine; using System.Collections; public class enemyMovement : MonoBehaviour { Rigidbody2D rb2d; public Transform target; private float nextFire; public float turnTime; public float speed; public float trackSpeed; int turn; public GameObject particles; int enemyHp = 100; private float explodeTime; // Use this for initialization void Start() { rb2d = GetComponent(); particles.gameObject.SetActive(false); target = GameObject.Find("fighter").transform; } float h, v, zed; public static bool check = true; // Update is called once per frame void Update() { float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); if (check == true) { if (Time.time > nextFire) { nextFire = Time.time + turnTime; turn = Random.Range(0, 5); switch (turn) { case 1: h = horizontal - 1; v = vertical; rb2d.transform.eulerAngles = new Vector3(0, 0, 90); // Debug.Log("left"); break; case 2: h = horizontal + 1; v = vertical; rb2d.transform.eulerAngles = new Vector3(0, 0, 270); // Debug.Log("right"); break; case 3: h = horizontal; v = vertical + 1; rb2d.transform.eulerAngles = new Vector3(0, 0, 0); // Debug.Log("up"); break; case 4: h = horizontal; v = vertical - 1; rb2d.transform.eulerAngles = new Vector3(0, 0, 180); // Debug.Log("down"); break; } } Vector2 temp = new Vector2(h, v); rb2d.AddForce(temp * Time.deltaTime * speed); } else if (check == false) { Vector3 vectorToTarget = target.position - transform.position; float angle = (Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg) - 90; Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward); transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * speed); if ((target.position.x > rb2d.position.x + 7 && target.position.x rb2d.position.x - 15) || (target.position.y > rb2d.position.y + 5 && target.position.y rb2d.position.y - 15)) { transform.position += transform.up * Time.deltaTime * trackSpeed; }//if the enemy is within the range of the player, the enemy will follow the player. else if(target.position.x > rb2d.position.x + 15 || target.position.x rb2d.position.y + 15 || target.position.y explodeTime) { explodeTime = Time.time + .5f; particles.gameObject.SetActive(false); } } // Debug.Log(check); } void OnTriggerEnter2D(Collider2D other) { if(other.gameObject.CompareTag("player fighter")) { check = false; }// if the player touches the onTrigger for the enemy, the enemy will follow the player. } void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("player bullet")) { Destroy(other.gameObject); enemyHp -= bulletMove.bulletDamage; } } }

How do I make and object's position and rotation independent again?

$
0
0
Just as the title says. How can I make the position of an object independent again after making it dependent earlier. This is what I have right now: if(ItemPickedUp == true){ // If you press the E key. if(Input.GetKeyDown("e")){ // The CarryableObject becomes a child of the Utility Props again. CarryableObject.transform.parent = UtilityProps.transform; // The drop position. CarryableObject.transform.position = new Vector3(Character.transform.position.x, Character.transform.position.y, Character.transform.position.z + OffsetDropPosition); // The rotation is no longer relative to the Character. CarryableObject.transform.rotation = Character.transform.rotation; // The gravity gets reenabled. CarryableObject.GetComponent().useGravity = true; // The child collider if-statements. if(Child1 != null){ Child1.GetComponent().enabled = true; } if(Child2 != null){ Child2.GetComponent().enabled = true; } if(Child3 != null){ Child3.GetComponent().enabled = true; } if(Child4 != null){ Child4.GetComponent().enabled = true; } } }

Touch Joystick behavior changes with resolution

$
0
0
I tried my game on mobile (tablet res: 1600*2560) and the joystick behaves different there. In free aspect and other default resolutions, it behaves normally. How can I make the behavior independent from screen resolution? Any help is highly valued.

Jump not framerate independent

$
0
0
Hey, I'm using a custom 2D controller, it has a Move() method that uses transform.Translate(velocity) to move the character. In my player controller script I apply gravity by doing this every frame right before I call Move() : velocity.y += gravity * Time.deltaTime; My Jump() method is called before the gravity, and sets the velocity.y to the jumpForce **once**. At 60+ fps i'm able to jump over a specific amount of tiles, at 30 fps I miss the last tile by a small amount of height, the weird thing is that if I slow down the game with time scale, I reach the same height. What is going on? **EDIT:** Bunny83's solution worked perfectly, I'm going to keep Eno-Khaon's answer because it clearly explains the issue, thanks guys much appreciated

any way to *not* use deltaTime when framerate slows?

$
0
0
Let me explain. I'm looking for what is essentially a 'hybrid' timestep. I'm making a bullet hell game which requires very little incongruencies with bullet patterns and speed. As a result, when the framerate slows down past a certain target framerate (say, 60 fps) I would prefer my systems run without taking delta time into account. So calculations would be taken step by step and the simulation would run more slowly, which is exactly what I want. On the other hand, once it's past the target framerate, I would like it it to maintain the delta, so it just moves more smoothly without speeding up. Any suggestions for this, or solutions like it?

Animation clip skipping keyframes when FPS drop?

$
0
0
have a simple setup in my animation clip for a **sword attack**: ![alt text][1] Just a basic sprite animation and two gameobjects that are **disabled/enabled via keyframes**. One of the GameObjects is a "damage" object (collider) I use as a slash for attacks, so it turns on on a certain part of the attack and then turns off on another. Simple enough. But I noticed with horror that when the editor started to skip frames due some lag, **sometimes the keyframes that turned on the damage object were skipped**, so the collider never appeared on the attack. This obviously would break the game when the fps drops. Haven't tested this on an actual build on a slow device, but is this behaviour expected? Is it only something that happens on the editor preview? Or this approach is not a reliable way of doing game logic? Thanks in advance for your help! [1]: https://i.imgur.com/wjgZSwv.jpg

Best Way to turn part of a 3D model in game

$
0
0
While developing a current project, I've realized I might have an issue later in the project. This game is utilizing 3D models of mechs, which has brought up an interesting question for me. While the player is controlling the mech (3rd person), I want the user to be able to move the mech quickly in any direction at will, which will rotate the legs towards wherever the player is pointing. However, I also want the torso of the mech to be permanently aimed towards the enemy, which brings me to my question. Is there a simple way in Unity to have the mech's legs move independently from the main torso of the mech, or should I export them as 2 objects that I can then just parent and control independently of each other in engine?

sell an asset made for Unity projects but without using the Asset Store

$
0
0
Hi Everyone, I wanted to ask if it's possible (e.g. legal) to sell a plugin that I made for Unity **without** going through the asset store? Me and some friends of mine are planning a startup for making Unity plugins, and want to create our own marketplace, as we wanted to create a subscription-based system to our works. As far as what we've read so far in Unity's documentations (unless we've missed some), Unity only has **free** and **paid** options.

Changes done in prefab script get applied to all instances of that prefab.

$
0
0
I am making multiple instances of prefab that has a script asign to it. In the script I am simply changing its color on mousedown. But clicking on one instance of prefab in the scene makes all other instances to change. I tried to change the material, so that each instance has its own material, but it did not seem to help. By logging I found out, that the method called on mousedown gets call for each instance. Could anyone explain this behaviour to me? I attached the code of script of the prefab and also code that I instantiate the prefabs with. using System.Collections; using System.Collections.Generic; using UnityEngine; public class markTile : MonoBehaviour { // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { Debug.Log(GetComponent().transform.position+"clicked prefab"); Color currentEditorColor = EditorController.getEditorController().getCurrentEditorColor(); GetComponent().material.color = currentEditorColor; } } } } public void CreateTileMap() { for(int i=0; i().material = material; } } }

Duplicate prefab and all its variants to new prefab with new variants

$
0
0
Is it possible to make totally independent copy of prefab with all its variants? For example I have: Prefab_1 -> Variant_1 -> Variant_2 And at the end there must be: Copy_Prefab_1 -> Copy_Variant_1 -> Copy_Variant_2 Prefab_1 and Copy_1 are totally independent. Just two different prefabs with their own variants.

how to make player run-speed independent of computer?

$
0
0
Hi everyone, I'm new to unity and I've written a script for my player run. Although I used Time.deltaTime but yet the run speed is changing in different computers. Could you please check my code and tell me where I'm doing wrong? Thanks in advance using UnityEngine; // attach the script to the player public class PlayerMovement : MonoBehaviour { public float runSpeed = 140f; public float jumpSpeed = 9f; public float gravity = 9.81f; public float laneWidth = 2.5f; public float smooth; public float minRunSpeed = 130f; public float maxRunSpeed = 250f; public float accelerationTime = 60; private float time; CharacterController controller; Vector3 direction; float directionY; bool isMoveStarted = false; int lane = 1; // 0:left 1:middle 2:righ; void Start() { controller = GetComponent(); direction = new Vector3(0, 0, 0); time = 0; } void Update() { if (isMoveStarted) { runSpeed = Mathf.SmoothStep(minRunSpeed, maxRunSpeed, time / accelerationTime); time += Time.deltaTime; ProcessUserInput(); direction.z = runSpeed * Time.deltaTime; HandleSliding(); Run(); } } void LateUpdate() { UpdateXPosition(); } void Jump() { directionY = jumpSpeed; } void Run() { directionY -= gravity * Time.deltaTime; direction.y = directionY; controller.Move(direction * Time.deltaTime); } void StartMoving() { isMoveStarted = true; GameObject.Find("TileManager").SendMessage("PlayEnvironmentSound"); } void ProcessUserInput() { if ((Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A)) && lane > 0) { lane--; } if ((Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D)) && lane




Latest Images