How to do ping-pong motion?

I want to make one of the gameobjects in my game to move back and forth from point A to point B repeatedly, but I wasn’t sure how… please help!

It would be helpful if you gave me code in C#, but JavaScript is also fine.

I answered this exact question 2 weeks ago. There’s a complete code example.

An even simpler example:

using UnityEngine;

public class AnotherExample : MonoBehaviour
{
    public Transform a, b;

    [Range(0, 1)]
    public float speed = 1;

    void Update()
    {
        float pingPong = Mathf.PingPong(Time.time * speed, 1);
        transform.position = Vector3.Lerp(a.position, b.position, pingPong);
    }
}

using UnityEngine;
using System.Collections;

public class simpleBounce : MonoBehaviour {

	// Use this for initialization

	public Transform targetPos; //assign these in inspector with "waypoint" gameobjects or something.
	public Transform startPos;  

	bool towards = true;
	public float speed = 0.1f;

	void Start () {

	}
	
	// Update is called once per frame
	void Update () {
	
		if (towards) {
			transform.LookAt(targetPos.position);
			transform.position += transform.forward * speed * Time.deltaTime;
			if (Vector3.Distance (transform.position, targetPos.position) < 1.0f) {
				towards = false;
			}
		} else {
			transform.LookAt(startPos.position);
			transform.position += transform.forward * speed * Time.deltaTime;
			if (Vector3.Distance (transform.position, startPos.position) < 1.0f) {
				{
					towards = true;
				}
			}
		}
	}

	}

this will (very simply and crudely) do what you want. :slight_smile:

Mathf.PingPong?

I don’t really know what you’re trying to create here.
EDIT: Okay, I made a simple code trying. Tell me if there’s anything wrong with it, also, you will need to modify this to your scene.

using UnityEngine;
using System.Collections;

public class glides : MonoBehaviour {

    public float speed = 5;
    public float acceleration = 10;
    public float turn = 7;

    public float turnDistance = 1;

    public Vector3 pointA;
    public Vector3 pointB;

    public bool goingToB = true;
    
    private float curSpeed;
    private Vector3 wanted;
	
	void Update () {
	    
        if(goingToB)
        {
            wanted = pointB;
            if ((pointB - transform.position).sqrMagnitude < turnDistance * turnDistance)
            {
                goingToB = false;
                curSpeed = 0;
            }
        }
        else
        {
            wanted = pointA;
            if ((pointA - transform.position).sqrMagnitude < turnDistance * turnDistance)
            {
                goingToB = true;
                curSpeed = 0;
            }
        }

        curSpeed = Mathf.Min(curSpeed + acceleration * Time.deltaTime, speed);
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(wanted - transform.position), turn * Time.deltaTime);
        transform.Translate(0, 0, curSpeed * Time.deltaTime);

	}
}