0
\$\begingroup\$

Here is the code I am using:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveToTarget : MonoBehaviour
{
    public enum TransitionState
    {
        None,
        MovingTowards,
        Transferring
    }

    public Transform destinationTransform;
    public float speed;
    public float lerpTime;
    public bool isChild = false;

    private Transform originTransform;
    private float timer;
    private TransitionState state = TransitionState.MovingTowards;

    void Start()
    {
        
    }

    void Update()
    {
        switch (state)
        {
            case TransitionState.MovingTowards:
                var v = destinationTransform.position - transform.position;
                if (v.magnitude < 0.001f)
                {
                    state = TransitionState.Transferring;
                    originTransform = destinationTransform;
                    timer = 0;
                    return;
                }
                Vector3 moveDir = v.normalized;
                transform.position += moveDir * speed * Time.deltaTime;
                break;

            case TransitionState.Transferring:
                timer += Time.deltaTime;
                this.transform.position = Vector3.Lerp(originTransform.position, destinationTransform.position, timer);
                if (timer >= 1.0f)
                {
                    this.transform.parent = destinationTransform;
                    isChild = true;
                    state = TransitionState.None;
                    this.enabled = false;
                    return;
                }
                break;

            default:
                this.enabled = false;
                return;
        }
    }
}

I have two questions :

  1. How can I use the lerpTime variable to control the speed of the motion? Now it's taking a second more or less before the moving object finishes its motion and gets parented to the destination (at line 50):

    this.transform.parent = destinationTransform;

  2. How can I make the object increase its movement speed slowly to max and then gradually slow down and until it stops at the target? Should I use smoothdamp or lerp here?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
case TransitionState.Transferring:

    // Divide deltaTime by your travel duration.
    // The longer you set the duration, the smaller the increments.
    timer += Time.deltaTime / lerpTime;

    // Compute a blend weight that eases in at the start and out at the end.
    float blend = Mathf.SmoothStep(0, 1, timer);

    // Use the blend weight for your lerp.
    this.transform.position = Vector3.Lerp(
                                 originTransform.position,
                                 destinationTransform.position,
                                 blend);
\$\endgroup\$

You must log in to answer this question.

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