Using transform.position and Mathf.PingPong on an object how have a random x position

Hi everybody,

So i’m triying to move an object from a point(A) to another point(B) and make him go back again to the first point (A) using Mathf.PingPong but the problem is that the point(A) have a Random value.

Here’s my script :

using UnityEngine;
using System.Collections;

public class MouvementObstacleCarre : MonoBehaviour {
public Vector2 vitesse = new Vector2(0,-2);
Vector2 vec = new Vector2(0,-1f);
public float range =1.7f;
Vector3 drag = new Vector3 ();

void Start ()
{
if (PlayerBox.isFristJump) // true when the player click on the screen for the first time
{

GetComponent<Rigidbody2D>().velocity = vitesse;
transform.position = new Vector3 (transform.position.x - range * Random.value, transform.position.y, transform.position.z);

}

}

void Update()
{

if (Score.CompteurScore >= 5 ) // when the player score 5 points then the movement begin
{ drag = transform.position;

Debug.Log(drag.x);
transform.position = new Vector3 (PingPong (Time.time, drag.x, -9.42f), transform.position.y, 0);

}
}


float PingPong(float aValue, float aMin, float aMax)
{
return Mathf.PingPong(aValue, aMax-aMin) + aMin;
}
}

the problem is with the drag.x : he doesn’t take the last position of the transform and start the movement with it.
Is it possible to start Mathf.PingPong with the last position of the point(A) just before the player score 5 points and make him go slowly ( without teleport) to the position of the point(B) wich is -9.42.

I’m stuck on this for like 2 days and i really need some help.

Thank you.

I would say use the built in Lerp function to move towards the new position. The way you have it setup the object will just teleport to the new position.

I tried Lerp but i didn’t used it correctly and the result wasn’t like i expected. Can you tell me how to used it with this values ? and you are right the object does teleport to the position but just one time and then he move correctly so i was thinking if i can get the exact last position of the drag= transform.position.x that maybe he will not teleport him to the new position.

Anyway thanks for your help.

Here’s a screenshot of the object that i want to move(the big one, not the gear).

Can anyone help me please ?

I tried something else : 2 gameobjects with boxcolliders( isTrigger On ) on the sides of the object that i want to move.

Here’s the code :

    Vector2 vec = new Vector2(-2f,0);
    Vector2 vec2 = new Vector2(2f,0);


    void OnTriggerEnter2D(Collider2D collider)
    {
        if (Score.CompteurScore >= 3 )
        {
        if (collider.tag == "LoopG") {
            transform.Translate (vec * Time.deltaTime);

        }
        if (collider.tag == "LoopD")
        {
            transform.Translate (vec2 * Time.deltaTime);
        }
        }
    }

But nothing happened. Is’t impossible to make him translate or i’m just doing it wrong?

I really appreciate some help.