how to stop moving

Hi, could you help me. I am definitely not a coder. I need to stop my object by time or distance (whatever). I hope it’s simple task for you guys. Here is a code:

using UnityEngine;
using System.Collections;

public class StartAnimation : MonoBehaviour {
	
	public float speed;
	public Vector3 direction;
	
	void Update() {
	transform.Translate (direction * speed * Time.deltaTime);
	}
}

2 Answers

2

public float speed;
public Vector3 direction;
public float time;
public float distance;
public bool stopAfterTime;
public bool stopAfterDistance;
private float startTime;
private Vector3 startPos;

    void Start()
    {
        startTime = Time.time;
        startPos = transform.position;
    }

    void Update()
    {
        if (stopAfterTime && Time.time - startTime < time)
            transform.Translate(direction * speed * Time.deltaTime);
        if (stopAfterDistance && Vector3.Distance(startPos, transform.position) < distance)
            transform.Translate(direction * speed * Time.deltaTime);
    }

Dont tick stopAfterTime and stopAfterDistance at the same time. It would result in weird movement. If you want I can extend my code to handle this.

Thank you very much. It does work when I use stopAfter Distance. But I could not succeed with stopAfterTime. Looks like that the code sets the time delay before start moving an object. Or am I doing something wrong?

Solved:) I have changed "startTime > time" to "startTime < time" and now it works too. Oribow, thank you very very much!

Fixed it in the post. Could you accept it now?

I used the distance joint as suggested by @toromano - btw, if you see this, can you answer to the question so I can mark you answer as correct? thank you for help