Question by
james9201 · Jun 01, 2016 at 01:52 AM ·
pathfindingnewbienewfollow playerradius
How can I get an object to follow my player once within a certain radius, but stop once out of radius
I'm making a 2D rpg game for school, and I need to make enemies follow the player once within a certain radius of him. But to stop chasing if he leaves a certain radius? I know this isn't very specific, and I would appreciate any help. Simpler is better as this is my first unity project and I am struggling with very basic things. Here is my current movement for slime, if you want to add comments and or add the chase code to it.
using UnityEngine;
using System.Collections;
public class SlimeController : MonoBehaviour {
public float moveSpeed;
private Rigidbody2D myRigidBody;
private bool moving;
public float timeBetweenMoves;
private float timeBetweenMoveCounter;
public float timeToMove;
private float timeToMoveCounter;
private Vector3 moveDirection;
// Use this for initialization
void Start () {
myRigidBody = GetComponent<Rigidbody2D> ();
//timeBetweenMoveCounter = timeBetweenMoves;
//timeToMoveCounter = timeToMove;
timeBetweenMoveCounter = Random.Range (timeBetweenMoves * 0.75f, timeBetweenMoves * 1.25f);
timeToMoveCounter = Random.Range (timeToMove * 0.75f, timeToMove * 1.25f);
}
// Update is called once per frame
void Update () {
if (moving)
{
timeToMoveCounter -= Time.deltaTime;
myRigidBody.velocity = moveDirection;
if (timeToMoveCounter < 0f)
{
moving = false;
//timeBetweenMoveCounter = timeBetweenMoves;
timeBetweenMoveCounter = Random.Range (timeBetweenMoves * 0.75f, timeBetweenMoves * 1.25f);
}
} else {
timeBetweenMoveCounter -= Time.deltaTime;
myRigidBody.velocity = Vector2.zero;
if (timeBetweenMoveCounter < 0f)
{
moving = true;
//timeToMoveCounter = timeToMove;
timeToMoveCounter = Random.Range (timeToMove * 0.75f, timeToMove * 1.25f);
moveDirection = new Vector3 (Random.Range (-1f, 1f) * moveSpeed, Random.Range (-1f, 1f) * moveSpeed, 0f);
}
}
}
}
Thank you a ton :)
Comment
Your answer
Follow this Question
Related Questions
Steam VR one object interaction using both controllers 0 Answers
2D Pathfinding with platformer 1 Answer
When do i use new ? 1 Answer
Platformer Jump Script Without AddForce 0 Answers