# How to have an object move between two locations

Hey guys!

I’m having issues getting an object to move back and forth in a project I’m working on. I want to the object to move back and forth between two predefined points. I’ve tried using transform.translate. I can get it to move in a given direction but I cant seem to get it to move back once it reaches the desired location. I’ve seen some snippets and examples of using mathf.pingpong but i’m confused as how to actually us it. Could someone enlighten me please.

Yes they are. I’ve seen examples that will bounce back and forth based on time (will go one direction for x seconds then go the other direction for x seconds). I’ve also seen examples of using SIN. I don’t know if this will help me. i have three objects total that i am using and two of those will move exclusively on the z axis. It has been a while since i’ve done anything with SIN even on a purely mathematical level much less using it in code. I’m really just looking for the most efficient way to pull off this movement. I don’t want all kinds of useless code floating around if it can be avoided.

I’ve also been having problems with infinite loops. I’ve been experimenting with a couple different loops to help facilitate the movement because i need it to keep moving autonomously for the duration of the program. However, my unity seems to lock up every time i add an infinite loop. Any ideas on this?

im not great with maths, but ive just put together something that moves an object between 2 waypoints(only 2 with this code)

its messy as hell code but hopefully you might be able to learn something from it

``````//on the object you want to move
using UnityEngine;
using System.Collections;

public class bounce : MonoBehaviour {

// Use this for initialization

public waypoint[] waypoints;
public string waypointOne ;
public string waypointTwo ;
public float speed = 0.1f;
waypoint currentWaypoint;
int waypointInt = 2;
bool changeWaypoint = false;

void Start () {
GameObject[] tempWaypoints = GameObject.FindGameObjectsWithTag ("waypoint");
waypoints = new waypoint[tempWaypoints.Length];
int ii = 0;
foreach (GameObject go in tempWaypoints) {
waypoints[ii] = go.GetComponent<waypoint>();
ii++;
}

}

// Update is called once per frame
void Update () {
if (!changeWaypoint) {
currentWaypoint = waypoints[0];
} else {
currentWaypoint = waypoints[1];
}
if (Vector3.Distance(transform.position,currentWaypoint.transform.position) > 1){
transform.LookAt(currentWaypoint.transform.position);
transform.position += transform.forward * speed;
//you can also add some other stuff like a wait time in here
} else {
changeWaypoint = !changeWaypoint;
}

}
}
``````