0
\$\begingroup\$

So i have this enemy gameobject and i want it to move in a certain pattern like a patrol. So i want him to move from A to B to C then Back to B to A. The script I worked out makes him go from C to A directly but I dont want that. Can someone please help . The Length of PatrolPoint Array in 3 `using UnityEngine; using System.Collections;

public class EnemyPatrol : MonoBehaviour {

public Transform [] patrolPoints; // An Array of path points to be followed
private int currentPoint ;
public float enemySpeed ;

void Start()
{

    currentPoint = 0;
    transform.position = patrolPoints[ currentPoint].position; // Starting Point
}

void Update()
{

    if(transform.position == patrolPoints[currentPoint].position)
    {
        currentPoint ++ ;
    }


    if(currentPoint >= patrolPoints.Length)
    {
        currentPoint = 0 ;
    } 

    transform.position = Vector3.MoveTowards(transform.position , patrolPoints[currentPoint].position , enemySpeed*Time.deltaTime);

    }

} `

\$\endgroup\$
0
\$\begingroup\$

Currently you have it loop back to the first point with currentPoint = 0;. You will need to decrement it each time by one, much like how you were incrementing it before. Perhaps use a condition to check whether to go forward or backward through the points:

private bool backtracking = false;
...
void Update() {
    if (transform.position == patrolPoints[currentPoint].position) {
        if (backtracking)
            currentPoint--;
        else
            currentPoint++;
    }

    if(currentPoint >= patrolPoints.Length) {
        backtracking = true;
    } 
    ...
}
\$\endgroup\$
0
\$\begingroup\$

I know it's a bit late but I'm going to post my code with some comments to help anyone else that may be stuck in this situation. This is for 3D, apply Vector2 if using 2D.

private bool left; //I set a boolean named left so that when true the object moves left

void Start () {
    left = true; //I set left to true so it would move left first
}

void Update () {
    if (transform.position.x >= 6.9f)
        left = true; //So if my X position is more 6.9 or more, left is set to true
    if (left)       //If Left is true it shall move 1 space to the left
        transform.Translate(-1f*Time.deltaTime,0f,0f);

    if (transform.position.x <= -6.9f)
        left=false;
    if (!left)    //But if its false (declared false on the above line) move right by the same speed
        transform.Translate(1f*Time.deltaTime,0f,0f);

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.