move object from one position to another slowly

Hi,

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

private float[] floo = new float[] { 2.73f, 6.37f, 11.19f, 15.80f, 20.31f, 24.84f};
         public int flooNum = 0;
void Update(){
        if (Input.GetMouseButtonDown (0)) {
  //gameObject.MovePosition(new Vector3(gameObject.transform.localPosition.x,  floo[flooNum], gameObject.transform.localPosition.z));
           flooNum ++;
  gameObject.transform.localPosition = new Vector3(gameObject.transform.localPosition.x, floo[flooNum], gameObject.transform.localPosition.z);
         }
}

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

Any idea. Please.

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().

Hi,

Thank you Billy4184 for your answer.

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

Thnaks

1 Like

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.

private float[] floo = new float[] { 2.73f, 6.37f, 11.19f, 15.80f, 20.31f, 24.84f};
public int flooNum = 0;

void Update(){
        if (Input.GetMouseButtonDown (0)) {
      
            Vector3    a = new Vector3(gameObject.transform.localPosition.x,  floor[floorNum], gameObject.transform.localPosition.z);
             rigidbody.AddForce(a);
        }
      
    }

Any idea?

Thanks

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().

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.:

public float speedCoefficient = 1f;  // how fast you want to go, this will be multiplied by the distance
public float maxSpeed = 10f;   // The maximum speed you want to move
Vector3 finalPosition = Vector3(10f, 10f, 10f);    // Whatever your final position is
Vector3 direction; // For getting normalized direction to target

void FixedUpdate(){
    direction = (finalPosition - transform.position).normalized;  // Get the normalized direction to target
    float distance = Vector3.distance (finalPosition,  transform.position); // Get distance to target
    float speed = Mathf.Clamp(distance*speedCoefficient, 0f, maxSpeed);   // Keep speed under limit
    rigidbody.velocity = direction *speed; // Make the speed dependent on the distance to the target
}
1 Like

Dear Billy4184 thank you again for your answer but you code gives an error " error CS1519: Unexpected symbol `’ in class, struct, or interface member declaration" in the last line of your code.

Can you please help one more time.

Thank you again.

Also it gives this erro “error CS0236: A field initializer cannot reference the nonstatic field, method, or property” for line 4 of your code.

public float speedCoefficient = 1f; // how fast you want to go, this will be multiplied by the distance
public float maxSpeed = 10f; // The maximum speed you want to move
Vector3 finalPosition = Vector3(10f, 10f, 10f); // Whatever your final position is
Vector3 direction = (finalPosition - transform.position).normalized; // Get the normalized direction to target

FixedUpdate(){
Vector3 distance = finalPosition - transform.position; // Get distance to target
float speed = Mathf.Clamp(distance*speedCoefficient, 0f, maxSpeed); // Keep speed under limit
rigidbody.velocity = direction *speed; // Make the speed dependent on the distance to the target
}

Change this:

Vector3 direction = (finalPosition - transform.position).normalized;

To:

Vector3 direction;

Start()
{
direction= (finalPosition - transform.position).normalized;
}
It should sort that error out.

1 Like

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.

1 Like

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.

using UnityEngine;
using System.Collections;
using System;

public class ElevetorManager : MonoBehaviour {
        public  GameObject theObject;   
        private float[] floo = new float[] { 2.73f, 6.37f, 11.19f, 15.80f, 20.31f, 24.84f};
        public int flooNum = 0;
       
        void Update(){
        if (Input.GetMouseButtonDown (0)) {
                RaycastHit hitInfo;
                GameObject target = GetClickedObject (out hitInfo);
                if (target.CompareTag ("Btn")) {

                    string s = target.name; //all names of the buttons are: btn-0, btn-1..... btn4
                    originalColor = target.renderer.material.color;
                    string[] numIs = s.Split('-');
                    Int32.TryParse(numIs[1], out flooNum);
                   
                   
                    // in every mouse click i get the num of the floo where my object "TheObject" have to go
                    //simple go to the y position where y=floo[flooNum].

                   
                }
            }
        } 
}

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.

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.

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.

public float speedCoefficient = 1.0f; 
    public float maxSpeed = 30.0f;  
    Vector3 finalPosition;    
    Vector3 direction; 



    void Start()
    {
        finalPosition = new Vector3(transform.localPosition.x,  floo[3], transform.localPosition.z);
        direction= (finalPosition - transform.position).normalized;
    }
  

    void FixedUpdate(){
        Vector3 distance = finalPosition - transform.position; 
        float speed = Mathf.Clamp(distance*speedCoefficient, 0f, maxSpeed); 
        rigidbody.velocity = direction *speed;
    }

Thank you again

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.

Finally worked for me.

Thank you very much