- Home /
How to move several objects "y" units during a fixed time
I have a selection of transforms that I need to move a certain amount of units up during a fixed time. This is my corotine.
float timer = 0f;
while (timer < riseTime) {
foreach (Transform trans in sel.list) {
pos = trans.position;
pos.y = pos.y + (sel.y *(cubeSize+cubeSpacing) * Time.deltaTime) / riseTime;
trans.position = pos;
}
timer+= Time.deltaTime;
yield return null;
}
The distance between the last object and my visual reference is never the same. I can't fix it and I would really appreciate any help.
I have done it beautifully with Vector3.Lerp but I need to store the initial positions for all the cubes in an array and that just doesn't sound good to me.
Thanks in advance.
you will need to store them somewhere, it doesnt really matter if you store them in an array or in individual values on the objects, you will still have to collect and reference the data.
Well yes, but if I could do it with first method the code would be much more efficient right?
i think you are really "straining the gnat" here, this is not going to be a massive gain in efficiency unless you are moving thousands of objects.
are all the units being moved constantly or are you choosing when to move them?
I chose when to move them... $$anonymous$$aybe you are right and I'm just complicating things. Anyway I spent so much time on the first method and Im so sure it's right. I would really like to know why it's not working.
so the 4 cubes at the top move correctly and the two at the bottom do not?
Answer by bubzy · Nov 17, 2014 at 01:59 PM
this works, not sure if its the kind of thing you are after though.
using UnityEngine;
using System.Collections;
public class moveDir : MonoBehaviour {
// Use this for initialization
float timeToMove = 1f;
float currentTime;
GameObject[] cubeList;
bool move = true;
void Start () {
cubeList = GameObject.FindGameObjectsWithTag("cube");
currentTime = Time.time + timeToMove;
}
// Update is called once per frame
void Update () {
if(move)
{
moveCubes(timeToMove);
}
if(!move)
{
currentTime = Time.time + timeToMove;
}
if(Input.GetKeyDown(KeyCode.A))
{
move = !move;
}
}
void moveCubes(float delayTime)
{
if(Time.time < currentTime)
{
foreach(GameObject cube in cubeList)
{
cube.transform.position += new Vector3(0,1,0)*Time.deltaTime;
}
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613171722im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
transform.position not setting position OR animation setting position even though it shouldn't 0 Answers
[2D] Get the position of an object outside the scope 2 Answers
moving objects with transform position 2 Answers
Why can't I assign transform.position to a Vector3 object? 3 Answers
Why is rotation offset 1 Answer