3
\$\begingroup\$

I am instantiating my game objects (spheres) through scripts. I want my spheres to move from one location to another. but I don't know how to do this. Update is called once per frame. Is that what I should use? I am using the free version of Unity; I don't want to use special plugins.

How do I move these game objects from one location to another, over time?

\$\endgroup\$

1 Answer 1

11
\$\begingroup\$

Yes, the Update loop is ideal for this. There are no special plug-ins required and you can do this with the free version. Basically you move the objects a tiny bit towards their destination each frame. When all those frames run one right after the other, it gives the appearance of smooth movement. A self contained script would look like the one I've created below. Ideally you'd take this as a starting point, and update it to use your own speed and starting point.

//move towards a target at a set speed.
private void MoveTowardsTarget() {
    //the speed, in units per second, we want to move towards the target
    float speed = 1;
    //move towards the center of the world (or where ever you like)
    Vector3 targetPosition = new Vector3(0,0,0);

    Vector3 currentPosition = this.transform.position;
    //first, check to see if we're close enough to the target
    if(Vector3.Distance(currentPosition, targetPosition) > .1f) { 
        Vector3 directionOfTravel = targetPosition - currentPosition;
        //now normalize the direction, since we only want the direction information
        directionOfTravel.Normalize();
        //scale the movement on each axis by the directionOfTravel vector components

        this.transform.Translate(
            (directionOfTravel.x * speed * Time.deltaTime),
            (directionOfTravel.y * speed * Time.deltaTime),
            (directionOfTravel.z * speed * Time.deltaTime),
            Space.World);
    }
}

This code could be anywhere (for now just put it inside the script you're using it from). Tn the script attached to the sphere you want to move, you'd put: MoveTowardsTarget() in the Update() function.

\$\endgroup\$
3
  • \$\begingroup\$ I am so much thankful to you @Byte56. I found first time that much comprehensive answer thanks allot. I'll try this. \$\endgroup\$ Commented Mar 27, 2014 at 14:23
  • \$\begingroup\$ Sure thing, good luck. \$\endgroup\$
    – House
    Commented Mar 27, 2014 at 14:26
  • 1
    \$\begingroup\$ This is really helpful, thank you so much! I have a question though, what happens on different resolutions? Is the speed going to increase on a higher resolution or remain the same? How do I make it so the speed is same on every resolution? \$\endgroup\$ Commented Feb 14, 2016 at 3:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .