2D Object Movement that can stop on collision detection?

I’m trying to code troops for my game that could move towards the position of my mouseclick. I got this done with the MoveTowards function, and it works perfectly with one unit. However, when multiple units want to move towards the same position, even with colliders, they start overlapping. I believe that it’s because the MoveTowards never finishes, so it keeps trying to move towards the same point, leading to the units clipping over each other. Is there any way to fix this?

I tried to find a way to cancel the MoveTowards, but that doesn’t appear to be possible. I also tried to override it with another MoveTowards function towards the same point on collision detection, but that also doesn’t work. I’m searching for other functions that can move to a certain point, but the only other one appears to be lerp, and I can’t find any way to stop that one as well. Is there any way to stop this?

If you look for basic solution, then you can create some bool , that will be turned to off when you will get your target (you can check it by OnCollisionEnter, OnTriggerEnter, transform.position and etc.) And in Update method or where you call MoveTowards method, you can check if this bool still true, if not, then stop calling MoveTowards. Basic example:

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

public class delete : MonoBehaviour
{

    public Transform target;
    public float speed;
    private bool keepMovingTowardsTarget;


    private void Start()
    {
        keepMovingTowardsTarget = true;
    }
    void Update()
    {
        if (keepMovingTowardsTarget)
        {
            float step = speed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, target.position, step);
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if(collision.transform.tag == target.tag)
        {
            keepMovingTowardsTarget = false;
            Debug.Log("We reached our target! I am stopping MoveTowards.");
        }
    }
}
1 Like

Thank you for the response! I’m a bit confused about the code that gets executed at the collision though. When we check the tags, what exactly does that mean?

There are tons of tutorials about this. Just google it. In two words, you are saying unity that - when i am collision with something, check his tag, if his tag similar to tag of my target, then i am near of my target, so lets just stop here.

Learn about colliders,triggers:

Also you can if you have Rigidbody you can make its velocity = vector2d.zero. This is so basic info, that you can find in top 5 searches of google: “how to stop 2d object unity” .