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 :
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;
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?