How can I use the Lerp the right way ? The duration is set to 10 but the transform is moving too fast and not in 10 seconds as I wanted.
Chocolade
536
Reputation points
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveToTarget : MonoBehaviour
{
public enum TransitionState
{
None,
MovingTowards,
Transferring
}
public Transform destinationTransform;
public bool isChild = false;
public AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, 0.0f, 1.0f, 1.0f);
public float duration = 10.0f;
public bool go = false;
private float t;
private Transform originTransform;
private float timer;
private TransitionState state = TransitionState.MovingTowards;
private Vector3 originPosition;
private SphereCollider col;
private bool enableCollider = true;
void Start()
{
t = 0.0f;
curve.postWrapMode = WrapMode.Once;
originPosition = transform.position;
col = GetComponent<SphereCollider>();
}
void Update()
{
if (go)
{
if (col != null && enableCollider)
{
Destroy(col);
Destroy(transform.GetComponent<Rigidbody>());
transform.GetComponent<InteractableItem>().enabledInteraction = false;
enableCollider = false;
}
switch (state)
{
case TransitionState.MovingTowards:
var v = destinationTransform.position - transform.position;
if (v.magnitude < 0.001f)
{
state = TransitionState.Transferring;
originTransform = destinationTransform;
timer = 0;
return;
}
t += Time.deltaTime;
float s = t / duration;
transform.position = Vector3.Lerp(transform.position,
destinationTransform.position, curve.Evaluate(s));
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;
transform.localPosition = new Vector3(0, 0, 0);
isChild = true;
go = false;
state = TransitionState.None;
this.enabled = false;
return;
}
break;
default:
this.enabled = false;
return;
}
}
}
}
When the transform is moving to the target(destinationTransform) even if the duration is set to 10 the transform is moving very fast and get the target after 2-3 seconds not 10.
I want the transform to move using the duration by seconds.
Something is wrong with the way I'm using the lerp in this part :
t += Time.deltaTime;
float s = t / duration;
transform.position = Vector3.Lerp(transform.position,
destinationTransform.position, curve.Evaluate(s));
I guess I'm using the Lerp in the right way.
And in the second place I'm also not sure if I'm using the right way with the Lerp :
this.transform.position = Vector3.Lerp(originTransform.position, destinationTransform.position, timer);
Developer technologies | Windows Forms
1,933 questions
Developer technologies | C#
11,575 questions
Sign in to answer