Ways to Unity 13: how to get close to an object (by using simple vector math)

Pre-Tips

Every position in 2D or 3D world is a vector.
Vector is a measure of length and direction. (Or if you can’t imagine, it’s a mixture of length and direction)

Imagine 

If we got two points, one is on the left called A, one is on the right called B.

How can you move the A to B?

Well, you just do this: A + (B - A)

So you do the same thing with vectors.

The Code

The following code shows how to let an enemy object approaching the player constantly.

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

public class Enemy : MonoBehaviour
{
    public float speed;
    private Rigidbody enemyRb;
    private GameObject player;

    void Start()
    {
        enemyRb = GetComponent<Rigidbody>();
        player = GameObject.Find("Player");
    }

    void Update()
    {
        Vector3 lookDirection = (player.transform.position - transform.position).normalized;
        enemyRb.AddForce(lookDirection * speed);
    }
}

The author: yingshaoxo

https://yingshaoxo.blogspot.com/2020/12/ways-to-unity-13-how-to-get-close-to.html