Object following target instead of moving towards it.

Hi there,

i’m making a 2D game that’s based on avoiding/evading enemies.
The problem i’m facing right now is i can’t get the enemies to move towards the target/player, but instead they follow it. So they never actually “attack” because they only follow it around and dont even come close to it. Also if the target/player stops moving, they stop moving.

I’m wondering what’s wrong with my code.

Kind regards.

using UnityEngine;
using System.Collections;

public class BeeBehaviour : MonoBehaviour {

    public Transform target;
    public float moveSpeed = 3;

    void Start () {
        target = GameObject.Find("MainObject").transform;
    }

    void Update () {
        Chase();
    }

    void Chase () {
            Vector3 targetDirection = target.position - transform.position;
            transform.position += targetDirection * moveSpeed * Time.deltaTime;
    }
}

Could it be the classic case of “don’t go where the target is NOW, but where it WILL BE”?

Also, please use CODE tags when posting code.

Thank you for alerting me about the code tags. Also i’m new to c# in general so i’m not sure if that’s the case

Well in your code, you’re correctly calculating the direction to the target, then move to it. So you will always be trailing behind.

For what you need, I would greatly recommend to read the Nature By Code (there is a complete free version online), especially the chapter “Autonomous Agents”. There is a lot of ground for various type of movement, from follow, intercept, arrive to flow fields and flocking. The example code is in Processing, but the concepts, which are explained in great detail, can apply to any programming language:

http://natureofcode.com/book/chapter-6-autonomous-agents/

2 Likes

Thanks SO much!

You are so close.
I think you just need to normalize the direction calculation, like this:

    void Chase () {
            Vector3 targetDirection = target.position - transform.position;
            transform.position += targetDirection.normalized * moveSpeed * Time.deltaTime;
    }

Normalizing a Vector3 gives it a length / magnitude of 1. That way, when multiplied by your speed, it will be a consistent speed, not dependent on the distance between the two objects.

1 Like