- Home /
Question by
DevDynasty · Jan 31, 2020 at 09:46 AM ·
positionenemy aipatrol
Patrol enemy going back to origine after reaching a Waypoint
Hello , i'm looking to create a simple patrol script but the differences between the others script I found is I would like this : the eneny go back to origin after reached a waypoint.
I'm stuck because the enemy reach the point but doesn't change his direction ...
public class PatrolTanks : MonoBehaviour
{
public Transform[] patrolPoints;
public float speed;
private int currentPatrolIndex;
private Vector2 directionFlip;
private Vector3 origin;
private Vector3 currentDestination;
private enum State
{
FORWARD,
BACKWARD
}
private State currentState;
void Start()
{
origin = this.transform.position;
currentPatrolIndex = 0;
currentDestination = patrolPoints[0].position;
currentState = State.FORWARD;
// directionFlip = GetDirectionFlip();
}
void FixedUpdate()
{
if (HasReachedCurrentDestination())
{
print("Atteint.");
if (currentState == State.FORWARD)
{
currentDestination = origin;
currentState = State.BACKWARD;
print("Go back to origin : " + currentDestination + "origin = " + origin);
}
else
{
currentPatrolIndex++;
if (currentPatrolIndex > patrolPoints.Length - 1)
currentPatrolIndex = 0;
currentDestination = patrolPoints[currentPatrolIndex].position;
currentState = State.FORWARD;
print("Go to next point : " + currentDestination);
}
}
// print("GO TO : " + transform.position + " -> " + currentDestination);
Vector3 newDirection;
if(State.FORWARD == currentState)
newDirection = transform.position - currentDestination;
else
newDirection = currentDestination - transform.position;
transform.Translate(newDirection * Time.fixedDeltaTime * speed);
}
private bool HasReachedCurrentDestination()
{
return Vector3.Distance(transform.position, currentDestination) < 1.0f;
}
Comment
Answer by LeFlop2001 · Jan 31, 2020 at 10:06 AM
Im nut a 100% sure what you were looking for but thats what I think you meant. using UnityEngine;
public class Test : MonoBehaviour
{
public Vector3[] patrolPoints;
public float minDistance;
public float movementSpeed;
int patrolIndex;
bool returnToStart;
private void Start()
{
patrolPoints[0] = transform.position;
patrolIndex = 1;
}
private void Update()
{
if (returnToStart)
{
Movement(patrolPoints[0]);
}
else
{
Movement(patrolPoints[patrolIndex]);
}
}
void Movement(Vector3 position)
{
transform.position += (position - transform.position).normalized * movementSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position,position) < minDistance && !returnToStart)
{
returnToStart = true;
}
else if (Vector3.Distance(transform.position, position) < minDistance && returnToStart)
{
patrolIndex++;
returnToStart = false;
if (patrolIndex == patrolPoints.Length)
{
patrolIndex = 1;
}
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612222442im_/https://answers.unity.com/themes/thub/images/avi.jpg)