Making an object move and then stop when it reaches a certain point

Hi new to coding and trying to get my head around c#
I want a ball to move to a certain point at a speed and then stop

public class MoveTopLeft : MonoBehaviour {

    public float movementSpeed = 10;

    private Rigidbody rb;

    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody> ();
    }
  
    // Update is called once per frame
    void FixedUpdate () {
        Vector3 endPosition = new Vector3 (-8, 0, -8);
        if (transform.position = endPostion){
        transform.Translate (Vector3.back * movementSpeed * Time.deltaTime);
        }
    }
}

What do I need to change to make it stop at the endPostion point?

Firstly, I’d like to point out that you should be using Update, not FixedUpdate. FixedUpdate is the physics update that runs after a certain interval of time, not according to the game’s frame rate. (unless you want to be moving with physics, i see you’re doing GetComponent())

To compare two things, the boolean operator is “==” not just “=”, which I’m sure is causing you issues.

You also probably want to only move if “transform.position != endPosition” (does not equal end position), then move.

Your Translate will move the object in global -Z direction over time, but that is potentially not towards the end-vector.

Try this:

public class MoveTopLeft : MonoBehaviour {

    public float movementSpeed = 10;

    private Rigidbody rb;
    private Vector3 endPosition = new Vector3(-8, 0, -8);
    // Use this for initialization
    void Start() {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update() {
        if(transform.position != endPosition) {
            transform.position = Vector3.MoveTowards(transform.position, endPosition, movementSpeed * Time.deltaTime);
        }
    }
}

for use with physics:

public class MoveTopLeft : MonoBehaviour {

    public float movementSpeed = 10;

    private Rigidbody rb;
    private Vector3 endPosition = new Vector3(-8, 0, -8);
    // Use this for initialization
    void Start() {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void FixedUpdate() {
        if(rb.position != endPosition) {
            Vector3 newPosition = Vector3.MoveTowards(rb.position, endPosition, movementSpeed * Time.deltaTime);
            rb.MovePosition(newPosition);
        }
    }
}
12 Likes