How to mak enemy walk back and forth

Hi
I’d like to make a script to control my enemy walk right to the target,and back to the start point,and so on.However,my enemy didn’t turn back when it moves to the target…
Can anyone help me to work it out?thx.

Here is my script:
function Update () {
var target = GameObject.FindWithTag (“target”).transform;
var offset = target.position - transform.position;
if(offset.x>0){
transform.position.x+=0.1;}
if(offset.x <0){
transform.position.x+=-0.1;}
}

2 Answers

2

You can use waypoints, you set 2 empty objects to serve as the points you want the character to move back and forth, and then you can do something like the following:

    currentWaypoint = myWaypoint1;
    var moveTo = currentWaypoint.transform.position.x-_transform.position.x;
if (Mathf.Abs(moveTo) <= 0.05f) {
	// At waypoint so stop moving
	GetComponent<Rigidbody2D> ().velocity = new Vector2(0, 0);
     if(currentWaypoint == myWaypoint2)
     {
        currentWaypoint = myWaypoint1;
     }
     else
     {
         currentWaypoint = myWaypoint1;
     }
}
else
{
    GetComponent<Rigidbody2D> ().velocity = new Vector2(GetComponent<Transform> ().localScale.x * moveSpeed, GetComponent<Rigidbody2D> ().velocity.y);
}

Things to note, “moveSpeed” is the speed that you assigned to the character to be moving at (in other words a public variable at the inspector), so would be “myWaypoint1” and “myWaypoint2” (2 public gameobject variables). You could also do these using an array of gameobjects and looping through the index of the array to get thought all the waypoints (which would allow you to have as many as you would like) but this code is merely and example to get you going and it’s up to you to improve upon it, you could also search online for more waypoint example codes

use graphs.