Taik
Taik

Reputation: 265

Move Object to Destination Smoothly Unity3D

I am trying the whole day to move an object from point A to point B smoothly, so I tried Lerp, MoveTowards and SmoothDamp but every time the object just disappear from point A and appear on point B instantly!

I tried every solution that I found in internet but I got the same result.

Can you please save my life and help me to solve that?

Here's the codes I've tried:

    transform.position = Vector3.SmoothDamp(transform.localPosition, Destination, ref velocity, Speed);

transform.position = Vector3.Lerp(transform.localPosition, Destination, Speed);

transform.position = Vector3.MoveTowards(transform.localPosition, Destination, Speed);

And more...

Upvotes: 2

Views: 12360

Answers (2)

Dan Wahl
Dan Wahl

Reputation: 108

You need to continuously update the position using Lerp. You could do this using a coroutine as follows (assuming Origin and Destination are defined positions):

public IEnumerator moveObject() {
    float totalMovementTime = 5f; //the amount of time you want the movement to take
    float currentMovementTime = 0f;//The amount of time that has passed
    while (Vector3.Distance(transform.localPosition, Destination) > 0) {
        currentMovementTime += Time.deltaTime;
        transform.localPosition = Vector3.Lerp(Origin, Destination, currentMovementTime / totalMovementTime);
        yield return null;
    }
}

You would call this coroutine with:

StartCoroutine(moveObject());

Upvotes: 5

Ehsan Mohammadi
Ehsan Mohammadi

Reputation: 1228

Try this:

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

public class SmoothMove : MonoBehaviour 
{
    public float speed = 0.01f;
    private Vector3 destination;

    void Start()
    {
        destination = transform.position;
    }

    void Update()
    {
        transform.position = Vector3.Lerp(transform.position, destination, speed)
    }

    void SetDestination(Vector3 newPos)
    {
        destination = newPos;
    }
}

I hope it helps you.

Upvotes: 1

Related Questions