Making one object to move to another

I’m making a simple 2d tower defense game using unity 2D, so i need enemies to move through tracks. Navmeshagents wont do any good, so i need to make a simple movement script.
I have made a simple script, and i want to make enemy to move to target’s transform/position/point.
Right now i’m moving my enemy only by changing velocity in another script.

var velocity : Vector3;
enemy.transform.position += velocity * Time.deltaTime;
//somewhere else
//if distance to target is less than number
switch(something) {
    case a:
    velocity = new Vector3(speed * 0, speed * -1, 0);
    break;
   
    case b:
    velocity = new Vector3(speed * 1, speed * 0, 0);
    break;
   
    case c:
    velocity = new Vector3(speed * 0, speed * 1, 0);
    break;
}

This makes enemy to move only to some direction, but i want to make enemy to towards target object, how can i make it / calculate it ?

Found it - instead of changing enemy’s position every time with +=, just had to do
gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, target.transform.position, speed * Time.deltaTime);

1 Like

You should change “speed * 0” to just “0”.

It’s unnecessary math for the CPU.

Yeah, that was just a try, i was looking how things work, it is now completely removed by MoveTowards method.

Ha! Oh, right…