Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

move object from one position to another slowly

Discussion in 'Physics' started by ki_ha1984, Jan 29, 2015.

  1. ki_ha1984

    ki_ha1984

    Joined:
    Aug 24, 2014
    Posts:
    111
    Hi,

    I have a object (cube) and i want to move it only in Y axis i developed a code like this.

    Code (CSharp):
    1.  
    2. private float[] floo = new float[] { 2.73f, 6.37f, 11.19f, 15.80f, 20.31f, 24.84f};
    3.          public int flooNum = 0;
    4. void Update(){
    5.         if (Input.GetMouseButtonDown (0)) {
    6.   //gameObject.MovePosition(new Vector3(gameObject.transform.localPosition.x,  floo[flooNum], gameObject.transform.localPosition.z));
    7.            flooNum ++;
    8.   gameObject.transform.localPosition = new Vector3(gameObject.transform.localPosition.x, floo[flooNum], gameObject.transform.localPosition.z);
    9.          }
    10. }
    11.  
    line 6 or line 8 makes the same thing. moves the object in every click, step by step in the points of the array floo[], only for Y axis.
    It make it so fast that i cannot see it. My problem is not the fast move.

    My problem is, when i am over the object with the "First Person Controller" of unity, ι climb over it without problem but i fall down, my character, some thing like the object that moves is transparent after it went to the destination position.


    Any idea ?


    Thanks in advance
     
  2. ki_ha1984

    ki_ha1984

    Joined:
    Aug 24, 2014
    Posts:
    111
    Any idea. Please.
     
  3. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    6,008
    If your game is running at 80 frames/second, then you are going to cycle through 80 positions in your floo[] array every second. You'll end up in the last position in less than 1/8 of a second, very fast!

    Second, if I get what you're saying, the answer to your problem is that you should never move objects using the .transform function if you want the physics to be stable (collision to occur). This is because your object will 'teleport', i.e., instantly move to the new position and there is no time for the physics engine to calculate a collision.

    Therefore, you should add a rigidbody to the cube and move it using Rigidbody.AddForce().
     
  4. ki_ha1984

    ki_ha1984

    Joined:
    Aug 24, 2014
    Posts:
    111
    Hi,

    Thank you Billy4184 for your answer.

    Any code sample on how to move object from Y1 TO Y2 position slowly.

    Thnaks
     
    Vjr_6174 likes this.
  5. ki_ha1984

    ki_ha1984

    Joined:
    Aug 24, 2014
    Posts:
    111
    i made this but still does not move my object
    I would like to tell you that

    I have one parent object (empty Object) with many childs (cubes).

    I have rigibody in the parent object also the code there.

    Code (CSharp):
    1. private float[] floo = new float[] { 2.73f, 6.37f, 11.19f, 15.80f, 20.31f, 24.84f};
    2. public int flooNum = 0;
    3.  
    4. void Update(){
    5.         if (Input.GetMouseButtonDown (0)) {
    6.      
    7.             Vector3    a = new Vector3(gameObject.transform.localPosition.x,  floor[floorNum], gameObject.transform.localPosition.z);
    8.              rigidbody.AddForce(a);
    9.         }
    10.      
    11.     }
    Any idea?


    Thanks
     
  6. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    6,008
    You have a few problems here. First of all, I hope that floo and flooNum in Lines 1 & 2 and floor and floorNum in line 7 is just a typo, otherwise you'll need to fix that.

    Secondly, you need to understand that rigidbody.AddForce takes a force vector, not a position vector. The object will accelerate and the position will change even though the force is constant. So change your Vector a to something like (0f, 1f, 0f) to get it to move straight upward. This applies a constant force of 1 upward. Increase it if it is too slow. Also, make sure that your rigidbody is not set to Kinematic in the Inspector window in the Editor.

    If you need your object to move smoothly upward at a constant speed (without acceleration), use rigidbody.velocity and set the values to the speed that you want your object to move on each axis.

    Also, put all physics calculations (such as rigidbody functions) in the FixedUpdate(), not Update().
     
  7. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    6,008
    By the way, if you want to go to a specific target position, you will have to move toward it, tapering the speed off as it approaches the target. Something like, e.g.:

    Code (CSharp):
    1.  
    2. public float speedCoefficient = 1f;  // how fast you want to go, this will be multiplied by the distance
    3. public float maxSpeed = 10f;   // The maximum speed you want to move
    4. Vector3 finalPosition = Vector3(10f, 10f, 10f);    // Whatever your final position is
    5. Vector3 direction; // For getting normalized direction to target
    6.  
    7. void FixedUpdate(){
    8.     direction = (finalPosition - transform.position).normalized;  // Get the normalized direction to target
    9.     float distance = Vector3.distance (finalPosition,  transform.position); // Get distance to target
    10.     float speed = Mathf.Clamp(distance*speedCoefficient, 0f, maxSpeed);   // Keep speed under limit
    11.     rigidbody.velocity = direction *speed; // Make the speed dependent on the distance to the target
    12. }
    13.  
     
    Last edited: Feb 27, 2015
    Kiamo likes this.
  8. ki_ha1984

    ki_ha1984

    Joined:
    Aug 24, 2014
    Posts:
    111
    Dear Billy4184 thank you again for your answer but you code gives an error " error CS1519: Unexpected symbol `<internal>' in class, struct, or interface member declaration" in the last line of your code.

    Can you please help one more time.

    Thank you again.
     
  9. ki_ha1984

    ki_ha1984

    Joined:
    Aug 24, 2014
    Posts:
    111
    Also it gives this erro "error CS0236: A field initializer cannot reference the nonstatic field, method, or property" for line 4 of your code.


    Code (CSharp):
    1. public float speedCoefficient = 1f; // how fast you want to go, this will be multiplied by the distance
    2. public float maxSpeed = 10f; // The maximum speed you want to move
    3. Vector3 finalPosition = Vector3(10f, 10f, 10f); // Whatever your final position is
    4. Vector3 direction = (finalPosition - transform.position).normalized; // Get the normalized direction to target
    5.  
    6. FixedUpdate(){
    7. Vector3 distance = finalPosition - transform.position; // Get distance to target
    8. float speed = Mathf.Clamp(distance*speedCoefficient, 0f, maxSpeed); // Keep speed under limit
    9. rigidbody.velocity = direction *speed; // Make the speed dependent on the distance to the target
    10. }
     
  10. Jonny-Roy

    Jonny-Roy

    Joined:
    May 29, 2013
    Posts:
    666
    Billy4184 likes this.
  11. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    6,008
    Edited my answer, sorry for being messy, I didn't know you were going to copy/paste! Don't forget to add 'void' in front of FixedUpdate().

    I recommend visiting the Unity Learn page as well as making friends with the Manual. Don't forget that if you're using MonoDevelop and not sure what a particular function like Mathf.Clamp does, you can highlight it and press Ctrl + ' to open the online manual reference.
     
    Jonny-Roy likes this.
  12. ki_ha1984

    ki_ha1984

    Joined:
    Aug 24, 2014
    Posts:
    111
    Hi again and sorry for the delay,

    First of all thank you for your answers.

    I know how to search in the unity help tools but I am confused with the physics, for this reason can you help me one more time?

    I specially need to manage the object by clicking on other objects which are defined as button.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4.  
    5. public class ElevetorManager : MonoBehaviour {
    6.         public  GameObject theObject;  
    7.         private float[] floo = new float[] { 2.73f, 6.37f, 11.19f, 15.80f, 20.31f, 24.84f};
    8.         public int flooNum = 0;
    9.        
    10.         void Update(){
    11.         if (Input.GetMouseButtonDown (0)) {
    12.                 RaycastHit hitInfo;
    13.                 GameObject target = GetClickedObject (out hitInfo);
    14.                 if (target.CompareTag ("Btn")) {
    15.  
    16.                     string s = target.name; //all names of the buttons are: btn-0, btn-1..... btn4
    17.                     originalColor = target.renderer.material.color;
    18.                     string[] numIs = s.Split('-');
    19.                     Int32.TryParse(numIs[1], out flooNum);
    20.                    
    21.                    
    22.                     // in every mouse click i get the num of the floo where my object "TheObject" have to go
    23.                     //simple go to the y position where y=floo[flooNum].
    24.  
    25.                    
    26.                 }
    27.             }
    28.         }
    29. }
    Like in the above code when i click on button object i get the id from the name and from the floo array i know where to go. My problem still is how to go my object slowly in that y position?

    Thank you again.
     
  13. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    6,008
    So all of the code you posted above works well, but you need to move the object? Did you try the code I wrote way back in reply #7? That was for moving an object smoothly from one position to the other. If you know your start position and target position, substitute them in and it should work. The speed variable determines the speed that your object will move there.
     
  14. ki_ha1984

    ki_ha1984

    Joined:
    Aug 24, 2014
    Posts:
    111
    I add again the corrected code of the reply#7 and returns an error " error CS1502: The best overloaded method match for `UnityEngine.Mathf.Clamp(float, float, float)' has some invalid arguments"for the line 17.


    Code (CSharp):
    1. public float speedCoefficient = 1.0f;
    2.     public float maxSpeed = 30.0f;  
    3.     Vector3 finalPosition;    
    4.     Vector3 direction;
    5.  
    6.  
    7.  
    8.     void Start()
    9.     {
    10.         finalPosition = new Vector3(transform.localPosition.x,  floo[3], transform.localPosition.z);
    11.         direction= (finalPosition - transform.position).normalized;
    12.     }
    13.  
    14.  
    15.     void FixedUpdate(){
    16.         Vector3 distance = finalPosition - transform.position;
    17.         float speed = Mathf.Clamp(distance*speedCoefficient, 0f, maxSpeed);
    18.         rigidbody.velocity = direction *speed;
    19.     }

    Thank you again
     
  15. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    6,008
    I edited my post again, line 9 is all I changed. Let me know if it doesn't work. It might be good for you to try to go through my code and understand it yourself in which case you probably would have picked up the problem easily.

    The problem of course, is that UnityEngine.Mathf.Clamp(float, float, float) wants three floats, whereas I gave it a Vector3 (distance) as the first argument.
     
  16. ki_ha1984

    ki_ha1984

    Joined:
    Aug 24, 2014
    Posts:
    111
    Finally worked for me.

    Thank you very much