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;
}
}
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:
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.