0
\$\begingroup\$
using UnityEngine;
using System.Collections;

public class Move : MonoBehaviour
{
    public Transform target;
    public float rotationSpeed;
    public float moveSpeed;

    private Vector3 originPos;
    private Quaternion originRot;

    private void Start()
    {
        originPos = transform.position;
        originRot = transform.rotation;
    }

    private void Update()
    {
        var distance = Vector3.Distance(transform.position, target.position);
        if(distance < 0.1f)
        {
            transform.rotation = Quaternion.Lerp(transform.rotation, originRot, Time.deltaTime * rotationSpeed);
            transform.position = Vector3.MoveTowards(transform.position, originPos, Time.deltaTime * moveSpeed);
        }

        transform.rotation = Quaternion.Lerp(transform.rotation, target.rotation, Time.deltaTime * rotationSpeed);
        transform.position = Vector3.MoveTowards(transform.position, target.position, Time.deltaTime * moveSpeed);
    }
}

At this line if the distance is less then 0.1f it should start moving back to the original position but the transform is not moving it's just staying at the same place :

transform.position = Vector3.MoveTowards(transform.position, originPos, Time.deltaTime * moveSpeed);
\$\endgroup\$
0
\$\begingroup\$

It seems that your object is likely actually rapidly jittering back and forth between states. This is because you are not making it remember what direction it is traveling in.

The moment distance < 0.1f is true, it will indeed start moving back to its origin. However, this will make the comparison untrue again, putting it back on its original trajectory.

The way to fix this is to have the comparison instead toggle a flag that determines the object's current priority, which you would reset whenever it has to move towards its target again.

In addition, you are currently making the object move towards target regardless of the distance variable. This should probably be caught in an else clause, instead.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.