-1

I want to make the object change its position in a few seconds. For example, it will "reach" a point within 5 seconds.

Choose a position and reach it within a fixed number of time. It is possible? Does it have a function?

Lat example. My object is in (10f, 10f, 0) I want him to reach (20f, 10f, 0) in 2 seconds.

Is it possible?

Update: in scratch, for example it called "glide 10, 78. secs to 3" - moving to 10X, 78Y in 3 seconds

Ziv Sion
  • 424
  • 4
  • 14
  • 1
    This is commonly called *Lerping* (ie, linear interpolation), or *Tweening* (ie, beTween). You can code your own (as the various answers below show), or use one of several packs on the asset store. I recommend LeanTween or DOTween. – Immersive Jan 20 '21 at 18:11
  • it's a lot to take in at once, but you really need to **Tweeng**. its one line of code once you are hip to use tweeng. (note, don't use a "tween library" like 20 years ago, just tweeng) how to .. https://stackoverflow.com/a/37228628/294884 – Fattie Jan 21 '21 at 01:48

4 Answers4

1

Use Vector3.Lerp inside a coroutine.

Vector3 beginPos = new Vector3(10f, 10f, 0);
Vector3 endPos = new Vector3(20f, 10f, 0);
float time = 2;

void Start(){
    StartCoroutine(Move(beginPos, endPos, time));
}

IEnumerator Move(Vector3 beginPos, Vector3 endPos, float time){
    for(float t = 0; t < 1; t += Time.deltaTime / time){
        transform.position = Vector3.Lerp(beginPos, endPos, t);
        yield return null;
    }
}

Vector3.Lerp basically interpolates between two vectors:

Lerp(a, b, t)   = (1-t)a + tb        
Lerp(a, b, 0)   = (1-0)a + 0b = a  
Lerp(a, b, 0.5) = (1-0.5)a + 0.5b = 0.5a + 0.5b     
Lerp(a, b, 1)   = (1-1)a + 1b = b        
Daniel
  • 7,357
  • 7
  • 32
  • 84
1

Unless you're 90 years old, just use a tweeng.

It's this easy

StartCoroutine(5f.Tweeng( (p)=>transform.position=p,
  startHere,
  endHere) );

it goes from startHere to endHere in 5 seconds.

That's all there is to it.

A tweeng extension is only a few lines of code, example: https://stackoverflow.com/a/37228628/294884

You can do anything with a tweeng, fade volume, twist objects, animate the size of type, fade images, whatever.

Every single large project you'll ever work on, they already use tweeng. It couldn't be simpler.

Fattie
  • 27,874
  • 70
  • 431
  • 719
0

To give you a general idea:

public class MoveToTarget : MonoBehaviour
{
    public Transform target;
    public float duration;

    float distance;
    float t;
    private void Start()
    {
         distance = Vector3.Distance(transform.position, target.position);
    }
    private void Update()
    {
      
        transform.position = Vector3.MoveTowards(transform.position, target.position,
            (distance/duration) * Time.deltaTime);
    }
}
-1

For sure!

There are a lot of ways to accomplish this in Unity.

I am going to assume that you are making a 3D experience and using RigidBody components.

FixedUpdate is a special method that Unity calls every 20ms - no matter what is going on with rendering, or performance - this is so you can do you physics simulations reliably and smoothly.

Remember the classic formula: rate * time = distance?

private void UpdateRigidBody()
{
    Vector3 targetDestination = Vector3.MoveTowards(transform.position, destination, speed * Time.deltaTime);

    var rb = transform.GetComponent<Rigidbody>();
    rb.MovePosition(destination);
}

Where speed is calculated and with destination set on the object (below).

In your case, you know the distance (destination - current position), and you know the time = 2 seconds.

Your unknown is the rate (speed).

Speed = distance / time.

So you will need some other function to setup the movement - like ChaseTarget?

private void ChaseTarget(Vector3 target, float timeToReach)
{    
    destination = target;
    var distance = (destination - transform.position);
    speed =  distance / timeToReach;
}

So, somewhere in your game controls logic you would call ChaseTarget and give it a target (a Vector3) and a time to get there. You setup these member variables on your object (targetDestination and speed) and the UpdateRigidBody function will smoothly get you there.

Typically, when you are close enough to the target you do some sort of new game logic and then reset the target destination (inside of UpdateRigidBody:

    var destXZ = destination;
    var posXZ = transform.position;

    var dir = destXZ - posXZ;
    var arrived = dir.magnitude < arrivedRadiusMagnitude;
    if (arrived) // If I have arrived
    {
        Arrived();
    }

Where the arrivedRadiusMagnitude is a game design question of how close can something get before it is considered arrived? For example some sort of tracking missile might explode when it is near a target, not necessarily right on top of it.

Erik Bethke
  • 563
  • 5
  • 17
  • it's really just completely wrong to use FixedUpdate, and very poor advice when people mention it. you want to simply and obviously *set the position **each video frame*** - ie just use Update or a Coroutine in the normal way. – Fattie Jan 21 '21 at 01:56
  • FWIW it's not "every 20ms", it depends on what time scale is set to. – Fattie Jan 21 '21 at 01:57
  • note that you (essentially) use FixedUpdate *in relation to physics*, that is to say *when adding **force***. When you add forces, you indeed do that at the rate of the *physics engine*, ie every physics engine frame. Then *the physics engine, obviously, calculates the correct positions at each drawing frame*. Note that drawing frames are completely unrelated to physics frames, and jiggle from them. (As it clearly states here for instance https://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html ) If one is NOT using physics (ie adding PhysX forces), but one is literally ... – Fattie Jan 21 '21 at 02:02
  • 1
    ... just setting positions, you must do it (obviously) with each drawing frame, ie in Update. (indeed note that, trivially, you're likely missing most draw frames if you incorrectly use FixedUpdate (ie "PhysicsUpdate") to move things!) If Unity had simply named FixedUpdate correctly as PhysicsUpdate, this endless mistake would not happen in Unity. – Fattie Jan 21 '21 at 02:04
  • Thank you man, learned a bunch of things from your comment and your better solution below. – Erik Bethke Jan 21 '21 at 05:00