I have created the code to make a cube move towards a ball.
Now I want the cube to move towards the ball when the ball is within a certain distance from the cube, and the cube will not go out of range when chasing the ball.
How do I define the distance and range?
Thanks!
Following is my code.
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public float moveSpeed = 3f;
public float rotationSpeed = 5f;
private Transform myTransform;
void Awake ()
{
myTransform = transform;
}
void Start()
{
GameObject go = GameObject.FindGameObjectWithTag("Ball");
//select the target
target = go.transform;
}
void Update()
{
Debug.DrawLine(target.position, myTransform.position, Color.yellow);
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}